ngram listlengths 0 67.8k |
|---|
[
"import autolens as al grid = al.Grid.uniform(shape_2d=(10, 10), pixel_scales=1.0) aplt.Grid(grid=grid) grid = al.Grid.uniform(shape_2d=(10,",
"al grid = al.Grid.uniform(shape_2d=(10, 10), pixel_scales=1.0) aplt.Grid(grid=grid) grid = al.Grid.uniform(shape_2d=(10, 10), pixel_scales=1.0, origin=(5.0,",
"= al.Grid.uniform(shape_2d=(10, 10), pixel_scales=1.0) aplt.Grid(grid=grid) grid = al.Grid.uniform(shape_2d=(10, 10), pixel_scales=1.0, origin=(5.0, 5.0)) aplt.Grid(grid=grid,",
"al.Grid.uniform(shape_2d=(10, 10), pixel_scales=1.0) aplt.Grid(grid=grid) grid = al.Grid.uniform(shape_2d=(10, 10), pixel_scales=1.0, origin=(5.0, 5.0)) aplt.Grid(grid=grid, symmetric_around_centre=False)",
"autolens as al grid = al.Grid.uniform(shape_2d=(10, 10), pixel_scales=1.0) aplt.Grid(grid=grid) grid = al.Grid.uniform(shape_2d=(10, 10),",
"as al grid = al.Grid.uniform(shape_2d=(10, 10), pixel_scales=1.0) aplt.Grid(grid=grid) grid = al.Grid.uniform(shape_2d=(10, 10), pixel_scales=1.0,",
"grid = al.Grid.uniform(shape_2d=(10, 10), pixel_scales=1.0) aplt.Grid(grid=grid) grid = al.Grid.uniform(shape_2d=(10, 10), pixel_scales=1.0, origin=(5.0, 5.0))"
] |
[
"read_data(data_file, num_epochs, shuffle): df_data = pd.read_csv( tf.gfile.Open(data_file), header=0, skipinitialspace=True, engine=\"python\") process(df_data) if \"test\"",
"shuffle=shuffle, queue_capacity=70000, num_threads=1) return inputs def process(df): df.fillna(0, inplace=True) df[\"buy_freq\"] = df[\"buy_freq\"].astype(int) df[\"visit_freq\"]",
"y) # print(sorted(Counter(y_resampled).items())) # 欠采样和过采样结合1 smote_enn = SMOTEENN(sampling_strategy=0.5, random_state=0) X_resampled, y_resampled = smote_enn.fit_sample(X,",
"(df[column] - df[column].min()) / (df[column].max() - df[column].min()) def read_data(data_file, num_epochs, shuffle): df_data =",
"print(sorted(Counter(y_resampled).items())) ## 欠采样和过采样结合2 ##smote_tomek = SMOTETomek(sampling_strategy=0.1, random_state=0) ##X_resampled, y_resampled = smote_tomek.fit_resample(X, y) ##print(sorted(Counter(y_resampled).items()))",
"from imblearn.under_sampling import NearMiss import numpy as np def scale(df, column): df[column] =",
"nm = NearMiss(random_state=0, version=3) # X_resampled, y_resampled = nm.fit_sample(X, y) # print(sorted(Counter(y_resampled).items())) #",
"= nm.fit_sample(X, y) # print(sorted(Counter(y_resampled).items())) # 欠采样和过采样结合1 smote_enn = SMOTEENN(sampling_strategy=0.5, random_state=0) X_resampled, y_resampled",
"process(df_data) if \"test\" in data_file: labels = None else: labels = df_data[\"y_buy\"] inputs",
"df_data.drop([\"y_buy\"], axis = 1) y = df_data[\"y_buy\"] X_column = X.columns y_column = [\"y_buy\"]",
"print(sorted(Counter(y).items())) # 直接欠采样 # nm = NearMiss(random_state=0, version=3) # X_resampled, y_resampled = nm.fit_sample(X,",
"num_epochs, shuffle): df_data = pd.read_csv( tf.gfile.Open(data_file), header=0, skipinitialspace=True, engine=\"python\") process(df_data) if \"test\" in",
"X_resampled = pd.DataFrame(X_resampled, columns=X_column) y_resampled = pd.DataFrame(y_resampled, columns=y_column) process(X_resampled) inputs = tf.estimator.inputs.pandas_input_fn( X_resampled,",
"SMOTETomek(sampling_strategy=0.1, random_state=0) ##X_resampled, y_resampled = smote_tomek.fit_resample(X, y) ##print(sorted(Counter(y_resampled).items())) X_resampled = pd.DataFrame(X_resampled, columns=X_column) y_resampled",
"pandas as pd from collections import Counter from imblearn.combine import SMOTEENN from imblearn.combine",
"= None else: labels = df_data[\"y_buy\"] inputs = tf.estimator.inputs.pandas_input_fn( x=df_data, y=labels, batch_size=128, num_epochs=num_epochs,",
"labels = df_data[\"y_buy\"] inputs = tf.estimator.inputs.pandas_input_fn( x=df_data, y=labels, batch_size=128, num_epochs=num_epochs, shuffle=shuffle, queue_capacity=50000, num_threads=1)",
"pd.DataFrame(X_resampled, columns=X_column) y_resampled = pd.DataFrame(y_resampled, columns=y_column) process(X_resampled) inputs = tf.estimator.inputs.pandas_input_fn( X_resampled, y_resampled, batch_size=128,",
"y_resampled = pd.DataFrame(y_resampled, columns=y_column) process(X_resampled) inputs = tf.estimator.inputs.pandas_input_fn( X_resampled, y_resampled, batch_size=128, num_epochs=num_epochs, shuffle=shuffle,",
"df[\"last_visit\"] = df[\"last_visit\"].astype(int) df[\"multiple_buy\"] = df[\"multiple_buy\"].astype(int) df[\"multiple_visit\"] = df[\"multiple_visit\"].astype(int) df[\"uniq_urls\"] = df[\"uniq_urls\"].astype(int) df[\"num_checkins\"]",
"y_column = [\"y_buy\"] print(sorted(Counter(y).items())) # 直接欠采样 # nm = NearMiss(random_state=0, version=3) # X_resampled,",
"y_resampled = smote_enn.fit_sample(X, y) print(sorted(Counter(y_resampled).items())) ## 欠采样和过采样结合2 ##smote_tomek = SMOTETomek(sampling_strategy=0.1, random_state=0) ##X_resampled, y_resampled",
"= pd.DataFrame(X_resampled, columns=X_column) y_resampled = pd.DataFrame(y_resampled, columns=y_column) process(X_resampled) inputs = tf.estimator.inputs.pandas_input_fn( X_resampled, y_resampled,",
"y_resampled = smote_tomek.fit_resample(X, y) ##print(sorted(Counter(y_resampled).items())) X_resampled = pd.DataFrame(X_resampled, columns=X_column) y_resampled = pd.DataFrame(y_resampled, columns=y_column)",
"axis = 1) y = df_data[\"y_buy\"] X_column = X.columns y_column = [\"y_buy\"] print(sorted(Counter(y).items()))",
"欠采样和过采样结合2 ##smote_tomek = SMOTETomek(sampling_strategy=0.1, random_state=0) ##X_resampled, y_resampled = smote_tomek.fit_resample(X, y) ##print(sorted(Counter(y_resampled).items())) X_resampled =",
"import NearMiss import numpy as np def scale(df, column): df[column] = (df[column] -",
"inputs # 采样 def read_data_with_sampling(data_file, num_epochs, shuffle): df_data = pd.read_csv( tf.gfile.Open(data_file), header=0, skipinitialspace=True,",
"num_epochs, shuffle): df_data = pd.read_csv( tf.gfile.Open(data_file), header=0, skipinitialspace=True, engine=\"python\") process(df_data) X = df_data.drop([\"y_buy\"],",
"None else: labels = df_data[\"y_buy\"] inputs = tf.estimator.inputs.pandas_input_fn( x=df_data, y=labels, batch_size=128, num_epochs=num_epochs, shuffle=shuffle,",
"NearMiss import numpy as np def scale(df, column): df[column] = (df[column] - df[column].min())",
"= df[\"last_buy\"].astype(int) df[\"last_visit\"] = df[\"last_visit\"].astype(int) df[\"multiple_buy\"] = df[\"multiple_buy\"].astype(int) df[\"multiple_visit\"] = df[\"multiple_visit\"].astype(int) df[\"uniq_urls\"] =",
"queue_capacity=50000, num_threads=1) return inputs # 采样 def read_data_with_sampling(data_file, num_epochs, shuffle): df_data = pd.read_csv(",
"= X.columns y_column = [\"y_buy\"] print(sorted(Counter(y).items())) # 直接欠采样 # nm = NearMiss(random_state=0, version=3)",
"df[column].min()) def read_data(data_file, num_epochs, shuffle): df_data = pd.read_csv( tf.gfile.Open(data_file), header=0, skipinitialspace=True, engine=\"python\") process(df_data)",
"return inputs def process(df): df.fillna(0, inplace=True) df[\"buy_freq\"] = df[\"buy_freq\"].astype(int) df[\"visit_freq\"] = df[\"visit_freq\"].astype(int) df[\"last_buy\"]",
"else: labels = df_data[\"y_buy\"] inputs = tf.estimator.inputs.pandas_input_fn( x=df_data, y=labels, batch_size=128, num_epochs=num_epochs, shuffle=shuffle, queue_capacity=50000,",
"data_file: labels = None else: labels = df_data[\"y_buy\"] inputs = tf.estimator.inputs.pandas_input_fn( x=df_data, y=labels,",
"df[\"visit_freq\"].astype(int) df[\"last_buy\"] = df[\"last_buy\"].astype(int) df[\"last_visit\"] = df[\"last_visit\"].astype(int) df[\"multiple_buy\"] = df[\"multiple_buy\"].astype(int) df[\"multiple_visit\"] = df[\"multiple_visit\"].astype(int)",
"y) ##print(sorted(Counter(y_resampled).items())) X_resampled = pd.DataFrame(X_resampled, columns=X_column) y_resampled = pd.DataFrame(y_resampled, columns=y_column) process(X_resampled) inputs =",
"X = df_data.drop([\"y_buy\"], axis = 1) y = df_data[\"y_buy\"] X_column = X.columns y_column",
"columns=y_column) process(X_resampled) inputs = tf.estimator.inputs.pandas_input_fn( X_resampled, y_resampled, batch_size=128, num_epochs=num_epochs, shuffle=shuffle, queue_capacity=70000, num_threads=1) return",
"columns=X_column) y_resampled = pd.DataFrame(y_resampled, columns=y_column) process(X_resampled) inputs = tf.estimator.inputs.pandas_input_fn( X_resampled, y_resampled, batch_size=128, num_epochs=num_epochs,",
"y) print(sorted(Counter(y_resampled).items())) ## 欠采样和过采样结合2 ##smote_tomek = SMOTETomek(sampling_strategy=0.1, random_state=0) ##X_resampled, y_resampled = smote_tomek.fit_resample(X, y)",
"numpy as np def scale(df, column): df[column] = (df[column] - df[column].min()) / (df[column].max()",
"process(X_resampled) inputs = tf.estimator.inputs.pandas_input_fn( X_resampled, y_resampled, batch_size=128, num_epochs=num_epochs, shuffle=shuffle, queue_capacity=70000, num_threads=1) return inputs",
"import Counter from imblearn.combine import SMOTEENN from imblearn.combine import SMOTETomek from imblearn.under_sampling import",
"inputs = tf.estimator.inputs.pandas_input_fn( X_resampled, y_resampled, batch_size=128, num_epochs=num_epochs, shuffle=shuffle, queue_capacity=70000, num_threads=1) return inputs def",
"X_resampled, y_resampled = nm.fit_sample(X, y) # print(sorted(Counter(y_resampled).items())) # 欠采样和过采样结合1 smote_enn = SMOTEENN(sampling_strategy=0.5, random_state=0)",
"from imblearn.combine import SMOTEENN from imblearn.combine import SMOTETomek from imblearn.under_sampling import NearMiss import",
"import tensorflow as tf import pandas as pd from collections import Counter from",
"X.columns y_column = [\"y_buy\"] print(sorted(Counter(y).items())) # 直接欠采样 # nm = NearMiss(random_state=0, version=3) #",
"采样 def read_data_with_sampling(data_file, num_epochs, shuffle): df_data = pd.read_csv( tf.gfile.Open(data_file), header=0, skipinitialspace=True, engine=\"python\") process(df_data)",
"X_resampled, y_resampled = smote_enn.fit_sample(X, y) print(sorted(Counter(y_resampled).items())) ## 欠采样和过采样结合2 ##smote_tomek = SMOTETomek(sampling_strategy=0.1, random_state=0) ##X_resampled,",
"x=df_data, y=labels, batch_size=128, num_epochs=num_epochs, shuffle=shuffle, queue_capacity=50000, num_threads=1) return inputs # 采样 def read_data_with_sampling(data_file,",
"# 欠采样和过采样结合1 smote_enn = SMOTEENN(sampling_strategy=0.5, random_state=0) X_resampled, y_resampled = smote_enn.fit_sample(X, y) print(sorted(Counter(y_resampled).items())) ##",
"batch_size=128, num_epochs=num_epochs, shuffle=shuffle, queue_capacity=70000, num_threads=1) return inputs def process(df): df.fillna(0, inplace=True) df[\"buy_freq\"] =",
"df[\"buy_freq\"].astype(int) df[\"visit_freq\"] = df[\"visit_freq\"].astype(int) df[\"last_buy\"] = df[\"last_buy\"].astype(int) df[\"last_visit\"] = df[\"last_visit\"].astype(int) df[\"multiple_buy\"] = df[\"multiple_buy\"].astype(int)",
"tf import pandas as pd from collections import Counter from imblearn.combine import SMOTEENN",
"engine=\"python\") process(df_data) X = df_data.drop([\"y_buy\"], axis = 1) y = df_data[\"y_buy\"] X_column =",
"y_resampled, batch_size=128, num_epochs=num_epochs, shuffle=shuffle, queue_capacity=70000, num_threads=1) return inputs def process(df): df.fillna(0, inplace=True) df[\"buy_freq\"]",
"# 采样 def read_data_with_sampling(data_file, num_epochs, shuffle): df_data = pd.read_csv( tf.gfile.Open(data_file), header=0, skipinitialspace=True, engine=\"python\")",
"num_epochs=num_epochs, shuffle=shuffle, queue_capacity=70000, num_threads=1) return inputs def process(df): df.fillna(0, inplace=True) df[\"buy_freq\"] = df[\"buy_freq\"].astype(int)",
"= df[\"visit_freq\"].astype(int) df[\"last_buy\"] = df[\"last_buy\"].astype(int) df[\"last_visit\"] = df[\"last_visit\"].astype(int) df[\"multiple_buy\"] = df[\"multiple_buy\"].astype(int) df[\"multiple_visit\"] =",
"labels = None else: labels = df_data[\"y_buy\"] inputs = tf.estimator.inputs.pandas_input_fn( x=df_data, y=labels, batch_size=128,",
"= df_data.drop([\"y_buy\"], axis = 1) y = df_data[\"y_buy\"] X_column = X.columns y_column =",
"smote_enn.fit_sample(X, y) print(sorted(Counter(y_resampled).items())) ## 欠采样和过采样结合2 ##smote_tomek = SMOTETomek(sampling_strategy=0.1, random_state=0) ##X_resampled, y_resampled = smote_tomek.fit_resample(X,",
"<reponame>camille1874/ads_classify import tensorflow as tf import pandas as pd from collections import Counter",
"smote_tomek.fit_resample(X, y) ##print(sorted(Counter(y_resampled).items())) X_resampled = pd.DataFrame(X_resampled, columns=X_column) y_resampled = pd.DataFrame(y_resampled, columns=y_column) process(X_resampled) inputs",
"shuffle=shuffle, queue_capacity=50000, num_threads=1) return inputs # 采样 def read_data_with_sampling(data_file, num_epochs, shuffle): df_data =",
"tf.gfile.Open(data_file), header=0, skipinitialspace=True, engine=\"python\") process(df_data) X = df_data.drop([\"y_buy\"], axis = 1) y =",
"欠采样和过采样结合1 smote_enn = SMOTEENN(sampling_strategy=0.5, random_state=0) X_resampled, y_resampled = smote_enn.fit_sample(X, y) print(sorted(Counter(y_resampled).items())) ## 欠采样和过采样结合2",
"##smote_tomek = SMOTETomek(sampling_strategy=0.1, random_state=0) ##X_resampled, y_resampled = smote_tomek.fit_resample(X, y) ##print(sorted(Counter(y_resampled).items())) X_resampled = pd.DataFrame(X_resampled,",
"process(df): df.fillna(0, inplace=True) df[\"buy_freq\"] = df[\"buy_freq\"].astype(int) df[\"visit_freq\"] = df[\"visit_freq\"].astype(int) df[\"last_buy\"] = df[\"last_buy\"].astype(int) df[\"last_visit\"]",
"SMOTETomek from imblearn.under_sampling import NearMiss import numpy as np def scale(df, column): df[column]",
"queue_capacity=70000, num_threads=1) return inputs def process(df): df.fillna(0, inplace=True) df[\"buy_freq\"] = df[\"buy_freq\"].astype(int) df[\"visit_freq\"] =",
"= df[\"buy_freq\"].astype(int) df[\"visit_freq\"] = df[\"visit_freq\"].astype(int) df[\"last_buy\"] = df[\"last_buy\"].astype(int) df[\"last_visit\"] = df[\"last_visit\"].astype(int) df[\"multiple_buy\"] =",
"# nm = NearMiss(random_state=0, version=3) # X_resampled, y_resampled = nm.fit_sample(X, y) # print(sorted(Counter(y_resampled).items()))",
"# X_resampled, y_resampled = nm.fit_sample(X, y) # print(sorted(Counter(y_resampled).items())) # 欠采样和过采样结合1 smote_enn = SMOTEENN(sampling_strategy=0.5,",
"in data_file: labels = None else: labels = df_data[\"y_buy\"] inputs = tf.estimator.inputs.pandas_input_fn( x=df_data,",
"= tf.estimator.inputs.pandas_input_fn( x=df_data, y=labels, batch_size=128, num_epochs=num_epochs, shuffle=shuffle, queue_capacity=50000, num_threads=1) return inputs # 采样",
"y=labels, batch_size=128, num_epochs=num_epochs, shuffle=shuffle, queue_capacity=50000, num_threads=1) return inputs # 采样 def read_data_with_sampling(data_file, num_epochs,",
"from collections import Counter from imblearn.combine import SMOTEENN from imblearn.combine import SMOTETomek from",
"batch_size=128, num_epochs=num_epochs, shuffle=shuffle, queue_capacity=50000, num_threads=1) return inputs # 采样 def read_data_with_sampling(data_file, num_epochs, shuffle):",
"= tf.estimator.inputs.pandas_input_fn( X_resampled, y_resampled, batch_size=128, num_epochs=num_epochs, shuffle=shuffle, queue_capacity=70000, num_threads=1) return inputs def process(df):",
"tf.estimator.inputs.pandas_input_fn( x=df_data, y=labels, batch_size=128, num_epochs=num_epochs, shuffle=shuffle, queue_capacity=50000, num_threads=1) return inputs # 采样 def",
"# 直接欠采样 # nm = NearMiss(random_state=0, version=3) # X_resampled, y_resampled = nm.fit_sample(X, y)",
"def read_data(data_file, num_epochs, shuffle): df_data = pd.read_csv( tf.gfile.Open(data_file), header=0, skipinitialspace=True, engine=\"python\") process(df_data) if",
"return inputs # 采样 def read_data_with_sampling(data_file, num_epochs, shuffle): df_data = pd.read_csv( tf.gfile.Open(data_file), header=0,",
"import SMOTETomek from imblearn.under_sampling import NearMiss import numpy as np def scale(df, column):",
"collections import Counter from imblearn.combine import SMOTEENN from imblearn.combine import SMOTETomek from imblearn.under_sampling",
"scale(df, column): df[column] = (df[column] - df[column].min()) / (df[column].max() - df[column].min()) def read_data(data_file,",
"tf.estimator.inputs.pandas_input_fn( X_resampled, y_resampled, batch_size=128, num_epochs=num_epochs, shuffle=shuffle, queue_capacity=70000, num_threads=1) return inputs def process(df): df.fillna(0,",
"def process(df): df.fillna(0, inplace=True) df[\"buy_freq\"] = df[\"buy_freq\"].astype(int) df[\"visit_freq\"] = df[\"visit_freq\"].astype(int) df[\"last_buy\"] = df[\"last_buy\"].astype(int)",
"import SMOTEENN from imblearn.combine import SMOTETomek from imblearn.under_sampling import NearMiss import numpy as",
"= df_data[\"y_buy\"] inputs = tf.estimator.inputs.pandas_input_fn( x=df_data, y=labels, batch_size=128, num_epochs=num_epochs, shuffle=shuffle, queue_capacity=50000, num_threads=1) return",
"df_data[\"y_buy\"] X_column = X.columns y_column = [\"y_buy\"] print(sorted(Counter(y).items())) # 直接欠采样 # nm =",
"##print(sorted(Counter(y_resampled).items())) X_resampled = pd.DataFrame(X_resampled, columns=X_column) y_resampled = pd.DataFrame(y_resampled, columns=y_column) process(X_resampled) inputs = tf.estimator.inputs.pandas_input_fn(",
"1) y = df_data[\"y_buy\"] X_column = X.columns y_column = [\"y_buy\"] print(sorted(Counter(y).items())) # 直接欠采样",
"skipinitialspace=True, engine=\"python\") process(df_data) X = df_data.drop([\"y_buy\"], axis = 1) y = df_data[\"y_buy\"] X_column",
"= NearMiss(random_state=0, version=3) # X_resampled, y_resampled = nm.fit_sample(X, y) # print(sorted(Counter(y_resampled).items())) # 欠采样和过采样结合1",
"inplace=True) df[\"buy_freq\"] = df[\"buy_freq\"].astype(int) df[\"visit_freq\"] = df[\"visit_freq\"].astype(int) df[\"last_buy\"] = df[\"last_buy\"].astype(int) df[\"last_visit\"] = df[\"last_visit\"].astype(int)",
"= SMOTETomek(sampling_strategy=0.1, random_state=0) ##X_resampled, y_resampled = smote_tomek.fit_resample(X, y) ##print(sorted(Counter(y_resampled).items())) X_resampled = pd.DataFrame(X_resampled, columns=X_column)",
"X_column = X.columns y_column = [\"y_buy\"] print(sorted(Counter(y).items())) # 直接欠采样 # nm = NearMiss(random_state=0,",
"= df[\"last_visit\"].astype(int) df[\"multiple_buy\"] = df[\"multiple_buy\"].astype(int) df[\"multiple_visit\"] = df[\"multiple_visit\"].astype(int) df[\"uniq_urls\"] = df[\"uniq_urls\"].astype(int) df[\"num_checkins\"] =",
"= pd.DataFrame(y_resampled, columns=y_column) process(X_resampled) inputs = tf.estimator.inputs.pandas_input_fn( X_resampled, y_resampled, batch_size=128, num_epochs=num_epochs, shuffle=shuffle, queue_capacity=70000,",
"直接欠采样 # nm = NearMiss(random_state=0, version=3) # X_resampled, y_resampled = nm.fit_sample(X, y) #",
"df[\"last_buy\"].astype(int) df[\"last_visit\"] = df[\"last_visit\"].astype(int) df[\"multiple_buy\"] = df[\"multiple_buy\"].astype(int) df[\"multiple_visit\"] = df[\"multiple_visit\"].astype(int) df[\"uniq_urls\"] = df[\"uniq_urls\"].astype(int)",
"= pd.read_csv( tf.gfile.Open(data_file), header=0, skipinitialspace=True, engine=\"python\") process(df_data) if \"test\" in data_file: labels =",
"= smote_enn.fit_sample(X, y) print(sorted(Counter(y_resampled).items())) ## 欠采样和过采样结合2 ##smote_tomek = SMOTETomek(sampling_strategy=0.1, random_state=0) ##X_resampled, y_resampled =",
"pd.DataFrame(y_resampled, columns=y_column) process(X_resampled) inputs = tf.estimator.inputs.pandas_input_fn( X_resampled, y_resampled, batch_size=128, num_epochs=num_epochs, shuffle=shuffle, queue_capacity=70000, num_threads=1)",
"num_epochs=num_epochs, shuffle=shuffle, queue_capacity=50000, num_threads=1) return inputs # 采样 def read_data_with_sampling(data_file, num_epochs, shuffle): df_data",
"header=0, skipinitialspace=True, engine=\"python\") process(df_data) if \"test\" in data_file: labels = None else: labels",
"pd from collections import Counter from imblearn.combine import SMOTEENN from imblearn.combine import SMOTETomek",
"header=0, skipinitialspace=True, engine=\"python\") process(df_data) X = df_data.drop([\"y_buy\"], axis = 1) y = df_data[\"y_buy\"]",
"= df_data[\"y_buy\"] X_column = X.columns y_column = [\"y_buy\"] print(sorted(Counter(y).items())) # 直接欠采样 # nm",
"import numpy as np def scale(df, column): df[column] = (df[column] - df[column].min()) /",
"df_data = pd.read_csv( tf.gfile.Open(data_file), header=0, skipinitialspace=True, engine=\"python\") process(df_data) if \"test\" in data_file: labels",
"tensorflow as tf import pandas as pd from collections import Counter from imblearn.combine",
"= [\"y_buy\"] print(sorted(Counter(y).items())) # 直接欠采样 # nm = NearMiss(random_state=0, version=3) # X_resampled, y_resampled",
"pd.read_csv( tf.gfile.Open(data_file), header=0, skipinitialspace=True, engine=\"python\") process(df_data) if \"test\" in data_file: labels = None",
"random_state=0) X_resampled, y_resampled = smote_enn.fit_sample(X, y) print(sorted(Counter(y_resampled).items())) ## 欠采样和过采样结合2 ##smote_tomek = SMOTETomek(sampling_strategy=0.1, random_state=0)",
"version=3) # X_resampled, y_resampled = nm.fit_sample(X, y) # print(sorted(Counter(y_resampled).items())) # 欠采样和过采样结合1 smote_enn =",
"= 1) y = df_data[\"y_buy\"] X_column = X.columns y_column = [\"y_buy\"] print(sorted(Counter(y).items())) #",
"column): df[column] = (df[column] - df[column].min()) / (df[column].max() - df[column].min()) def read_data(data_file, num_epochs,",
"nm.fit_sample(X, y) # print(sorted(Counter(y_resampled).items())) # 欠采样和过采样结合1 smote_enn = SMOTEENN(sampling_strategy=0.5, random_state=0) X_resampled, y_resampled =",
"y = df_data[\"y_buy\"] X_column = X.columns y_column = [\"y_buy\"] print(sorted(Counter(y).items())) # 直接欠采样 #",
"def scale(df, column): df[column] = (df[column] - df[column].min()) / (df[column].max() - df[column].min()) def",
"def read_data_with_sampling(data_file, num_epochs, shuffle): df_data = pd.read_csv( tf.gfile.Open(data_file), header=0, skipinitialspace=True, engine=\"python\") process(df_data) X",
"y_resampled = nm.fit_sample(X, y) # print(sorted(Counter(y_resampled).items())) # 欠采样和过采样结合1 smote_enn = SMOTEENN(sampling_strategy=0.5, random_state=0) X_resampled,",
"np def scale(df, column): df[column] = (df[column] - df[column].min()) / (df[column].max() - df[column].min())",
"# print(sorted(Counter(y_resampled).items())) # 欠采样和过采样结合1 smote_enn = SMOTEENN(sampling_strategy=0.5, random_state=0) X_resampled, y_resampled = smote_enn.fit_sample(X, y)",
"SMOTEENN(sampling_strategy=0.5, random_state=0) X_resampled, y_resampled = smote_enn.fit_sample(X, y) print(sorted(Counter(y_resampled).items())) ## 欠采样和过采样结合2 ##smote_tomek = SMOTETomek(sampling_strategy=0.1,",
"num_threads=1) return inputs # 采样 def read_data_with_sampling(data_file, num_epochs, shuffle): df_data = pd.read_csv( tf.gfile.Open(data_file),",
"df[\"visit_freq\"] = df[\"visit_freq\"].astype(int) df[\"last_buy\"] = df[\"last_buy\"].astype(int) df[\"last_visit\"] = df[\"last_visit\"].astype(int) df[\"multiple_buy\"] = df[\"multiple_buy\"].astype(int) df[\"multiple_visit\"]",
"random_state=0) ##X_resampled, y_resampled = smote_tomek.fit_resample(X, y) ##print(sorted(Counter(y_resampled).items())) X_resampled = pd.DataFrame(X_resampled, columns=X_column) y_resampled =",
"df[\"last_visit\"].astype(int) df[\"multiple_buy\"] = df[\"multiple_buy\"].astype(int) df[\"multiple_visit\"] = df[\"multiple_visit\"].astype(int) df[\"uniq_urls\"] = df[\"uniq_urls\"].astype(int) df[\"num_checkins\"] = df[\"num_checkins\"].astype(int)",
"imblearn.under_sampling import NearMiss import numpy as np def scale(df, column): df[column] = (df[column]",
"shuffle): df_data = pd.read_csv( tf.gfile.Open(data_file), header=0, skipinitialspace=True, engine=\"python\") process(df_data) if \"test\" in data_file:",
"imblearn.combine import SMOTEENN from imblearn.combine import SMOTETomek from imblearn.under_sampling import NearMiss import numpy",
"inputs def process(df): df.fillna(0, inplace=True) df[\"buy_freq\"] = df[\"buy_freq\"].astype(int) df[\"visit_freq\"] = df[\"visit_freq\"].astype(int) df[\"last_buy\"] =",
"df[column] = (df[column] - df[column].min()) / (df[column].max() - df[column].min()) def read_data(data_file, num_epochs, shuffle):",
"df[column].min()) / (df[column].max() - df[column].min()) def read_data(data_file, num_epochs, shuffle): df_data = pd.read_csv( tf.gfile.Open(data_file),",
"(df[column].max() - df[column].min()) def read_data(data_file, num_epochs, shuffle): df_data = pd.read_csv( tf.gfile.Open(data_file), header=0, skipinitialspace=True,",
"df_data[\"y_buy\"] inputs = tf.estimator.inputs.pandas_input_fn( x=df_data, y=labels, batch_size=128, num_epochs=num_epochs, shuffle=shuffle, queue_capacity=50000, num_threads=1) return inputs",
"X_resampled, y_resampled, batch_size=128, num_epochs=num_epochs, shuffle=shuffle, queue_capacity=70000, num_threads=1) return inputs def process(df): df.fillna(0, inplace=True)",
"shuffle): df_data = pd.read_csv( tf.gfile.Open(data_file), header=0, skipinitialspace=True, engine=\"python\") process(df_data) X = df_data.drop([\"y_buy\"], axis",
"process(df_data) X = df_data.drop([\"y_buy\"], axis = 1) y = df_data[\"y_buy\"] X_column = X.columns",
"/ (df[column].max() - df[column].min()) def read_data(data_file, num_epochs, shuffle): df_data = pd.read_csv( tf.gfile.Open(data_file), header=0,",
"print(sorted(Counter(y_resampled).items())) # 欠采样和过采样结合1 smote_enn = SMOTEENN(sampling_strategy=0.5, random_state=0) X_resampled, y_resampled = smote_enn.fit_sample(X, y) print(sorted(Counter(y_resampled).items()))",
"df.fillna(0, inplace=True) df[\"buy_freq\"] = df[\"buy_freq\"].astype(int) df[\"visit_freq\"] = df[\"visit_freq\"].astype(int) df[\"last_buy\"] = df[\"last_buy\"].astype(int) df[\"last_visit\"] =",
"##X_resampled, y_resampled = smote_tomek.fit_resample(X, y) ##print(sorted(Counter(y_resampled).items())) X_resampled = pd.DataFrame(X_resampled, columns=X_column) y_resampled = pd.DataFrame(y_resampled,",
"## 欠采样和过采样结合2 ##smote_tomek = SMOTETomek(sampling_strategy=0.1, random_state=0) ##X_resampled, y_resampled = smote_tomek.fit_resample(X, y) ##print(sorted(Counter(y_resampled).items())) X_resampled",
"- df[column].min()) / (df[column].max() - df[column].min()) def read_data(data_file, num_epochs, shuffle): df_data = pd.read_csv(",
"skipinitialspace=True, engine=\"python\") process(df_data) if \"test\" in data_file: labels = None else: labels =",
"smote_enn = SMOTEENN(sampling_strategy=0.5, random_state=0) X_resampled, y_resampled = smote_enn.fit_sample(X, y) print(sorted(Counter(y_resampled).items())) ## 欠采样和过采样结合2 ##smote_tomek",
"pd.read_csv( tf.gfile.Open(data_file), header=0, skipinitialspace=True, engine=\"python\") process(df_data) X = df_data.drop([\"y_buy\"], axis = 1) y",
"= SMOTEENN(sampling_strategy=0.5, random_state=0) X_resampled, y_resampled = smote_enn.fit_sample(X, y) print(sorted(Counter(y_resampled).items())) ## 欠采样和过采样结合2 ##smote_tomek =",
"= pd.read_csv( tf.gfile.Open(data_file), header=0, skipinitialspace=True, engine=\"python\") process(df_data) X = df_data.drop([\"y_buy\"], axis = 1)",
"= (df[column] - df[column].min()) / (df[column].max() - df[column].min()) def read_data(data_file, num_epochs, shuffle): df_data",
"import pandas as pd from collections import Counter from imblearn.combine import SMOTEENN from",
"\"test\" in data_file: labels = None else: labels = df_data[\"y_buy\"] inputs = tf.estimator.inputs.pandas_input_fn(",
"num_threads=1) return inputs def process(df): df.fillna(0, inplace=True) df[\"buy_freq\"] = df[\"buy_freq\"].astype(int) df[\"visit_freq\"] = df[\"visit_freq\"].astype(int)",
"as tf import pandas as pd from collections import Counter from imblearn.combine import",
"df[\"last_buy\"] = df[\"last_buy\"].astype(int) df[\"last_visit\"] = df[\"last_visit\"].astype(int) df[\"multiple_buy\"] = df[\"multiple_buy\"].astype(int) df[\"multiple_visit\"] = df[\"multiple_visit\"].astype(int) df[\"uniq_urls\"]",
"as np def scale(df, column): df[column] = (df[column] - df[column].min()) / (df[column].max() -",
"if \"test\" in data_file: labels = None else: labels = df_data[\"y_buy\"] inputs =",
"inputs = tf.estimator.inputs.pandas_input_fn( x=df_data, y=labels, batch_size=128, num_epochs=num_epochs, shuffle=shuffle, queue_capacity=50000, num_threads=1) return inputs #",
"Counter from imblearn.combine import SMOTEENN from imblearn.combine import SMOTETomek from imblearn.under_sampling import NearMiss",
"tf.gfile.Open(data_file), header=0, skipinitialspace=True, engine=\"python\") process(df_data) if \"test\" in data_file: labels = None else:",
"imblearn.combine import SMOTETomek from imblearn.under_sampling import NearMiss import numpy as np def scale(df,",
"- df[column].min()) def read_data(data_file, num_epochs, shuffle): df_data = pd.read_csv( tf.gfile.Open(data_file), header=0, skipinitialspace=True, engine=\"python\")",
"SMOTEENN from imblearn.combine import SMOTETomek from imblearn.under_sampling import NearMiss import numpy as np",
"df_data = pd.read_csv( tf.gfile.Open(data_file), header=0, skipinitialspace=True, engine=\"python\") process(df_data) X = df_data.drop([\"y_buy\"], axis =",
"NearMiss(random_state=0, version=3) # X_resampled, y_resampled = nm.fit_sample(X, y) # print(sorted(Counter(y_resampled).items())) # 欠采样和过采样结合1 smote_enn",
"engine=\"python\") process(df_data) if \"test\" in data_file: labels = None else: labels = df_data[\"y_buy\"]",
"[\"y_buy\"] print(sorted(Counter(y).items())) # 直接欠采样 # nm = NearMiss(random_state=0, version=3) # X_resampled, y_resampled =",
"from imblearn.combine import SMOTETomek from imblearn.under_sampling import NearMiss import numpy as np def",
"as pd from collections import Counter from imblearn.combine import SMOTEENN from imblearn.combine import",
"read_data_with_sampling(data_file, num_epochs, shuffle): df_data = pd.read_csv( tf.gfile.Open(data_file), header=0, skipinitialspace=True, engine=\"python\") process(df_data) X =",
"= smote_tomek.fit_resample(X, y) ##print(sorted(Counter(y_resampled).items())) X_resampled = pd.DataFrame(X_resampled, columns=X_column) y_resampled = pd.DataFrame(y_resampled, columns=y_column) process(X_resampled)",
"df[\"buy_freq\"] = df[\"buy_freq\"].astype(int) df[\"visit_freq\"] = df[\"visit_freq\"].astype(int) df[\"last_buy\"] = df[\"last_buy\"].astype(int) df[\"last_visit\"] = df[\"last_visit\"].astype(int) df[\"multiple_buy\"]"
] |
[
"g, i_mc, grid, controls, mdr, P, Q, parms) return res def residuals(f, g,",
"parms): N = s.shape[0] n_s = s.shape[1] n_ms = P.shape[0] # number of",
"= Q[i_ms, I_ms] S = g(m, s, xm, M, parms) XM[:,:] = dr(I_ms,",
"parms) XM[:,:] = dr(I_ms, S) rr = f(m,s,xm,M,S,XM,parms) res[:,:] += prob*rr return res",
"g = lambda m,s,x,M,p: gg(m,s,x,aa(m,s,x,p),M,p) P,Q = model.markov_chain parms = model.calibration['parameters'] controls =",
"Q, parms) return res def residuals(f, g, i_ms, s, x, dr, P, Q,",
"for markov index i_ms # m = P[i_ms,:][None,:] m = numpy.tile(P[i_ms,:],(N,1)) xm =",
"numpy.tile(P[I_ms,:], (N,1)) prob = Q[i_ms, I_ms] S = g(m, s, xm, M, parms)",
"markov variable res = numpy.zeros_like(x) XM = numpy.zeros_like(x) import time # solving on",
"dr, grid): ff = model.functions['arbitrage'] gg = model.functions['transition'] aa = model.functions['auxiliary'] f =",
"import time # solving on grid for markov index i_ms # m =",
"m,s,x,M,S,X,p: ff(m,s,x,aa(m,s,x,p),M,S,X,aa(M,S,X,p),p) g = lambda m,s,x,M,p: gg(m,s,x,aa(m,s,x,p),M,p) P,Q = model.markov_chain parms = model.calibration['parameters']",
"model.markov_chain parms = model.calibration['parameters'] controls = dr(grid) res = residuals(f, g, i_mc, grid,",
"x[:,:] for I_ms in range(n_ms): # M = P[I_ms,:][None,:] M = numpy.tile(P[I_ms,:], (N,1))",
"= P.shape[1] # number of markov variable res = numpy.zeros_like(x) XM = numpy.zeros_like(x)",
"controls, mdr, P, Q, parms) return res def residuals(f, g, i_ms, s, x,",
"= numpy.tile(P[i_ms,:],(N,1)) xm = x[:,:] for I_ms in range(n_ms): # M = P[I_ms,:][None,:]",
"of markov variable res = numpy.zeros_like(x) XM = numpy.zeros_like(x) import time # solving",
"= model.functions['auxiliary'] f = lambda m,s,x,M,S,X,p: ff(m,s,x,aa(m,s,x,p),M,S,X,aa(M,S,X,p),p) g = lambda m,s,x,M,p: gg(m,s,x,aa(m,s,x,p),M,p) P,Q",
"s, xm, M, parms) XM[:,:] = dr(I_ms, S) rr = f(m,s,xm,M,S,XM,parms) res[:,:] +=",
"gg = model.functions['transition'] aa = model.functions['auxiliary'] f = lambda m,s,x,M,S,X,p: ff(m,s,x,aa(m,s,x,p),M,S,X,aa(M,S,X,p),p) g =",
"division def compute_residuals(model, dr, grid): ff = model.functions['arbitrage'] gg = model.functions['transition'] aa =",
"# m = P[i_ms,:][None,:] m = numpy.tile(P[i_ms,:],(N,1)) xm = x[:,:] for I_ms in",
"s.shape[1] n_ms = P.shape[0] # number of markov states n_mv = P.shape[1] #",
"grid for markov index i_ms # m = P[i_ms,:][None,:] m = numpy.tile(P[i_ms,:],(N,1)) xm",
"numpy.tile(P[i_ms,:],(N,1)) xm = x[:,:] for I_ms in range(n_ms): # M = P[I_ms,:][None,:] M",
"g, i_ms, s, x, dr, P, Q, parms): N = s.shape[0] n_s =",
"P.shape[0] # number of markov states n_mv = P.shape[1] # number of markov",
"M = numpy.tile(P[I_ms,:], (N,1)) prob = Q[i_ms, I_ms] S = g(m, s, xm,",
"res = numpy.zeros_like(x) XM = numpy.zeros_like(x) import time # solving on grid for",
"on grid for markov index i_ms # m = P[i_ms,:][None,:] m = numpy.tile(P[i_ms,:],(N,1))",
"N = s.shape[0] n_s = s.shape[1] n_ms = P.shape[0] # number of markov",
"__future__ import division def compute_residuals(model, dr, grid): ff = model.functions['arbitrage'] gg = model.functions['transition']",
"compute_residuals(model, dr, grid): ff = model.functions['arbitrage'] gg = model.functions['transition'] aa = model.functions['auxiliary'] f",
"solving on grid for markov index i_ms # m = P[i_ms,:][None,:] m =",
"= g(m, s, xm, M, parms) XM[:,:] = dr(I_ms, S) rr = f(m,s,xm,M,S,XM,parms)",
"prob = Q[i_ms, I_ms] S = g(m, s, xm, M, parms) XM[:,:] =",
"= dr(grid) res = residuals(f, g, i_mc, grid, controls, mdr, P, Q, parms)",
"P.shape[1] # number of markov variable res = numpy.zeros_like(x) XM = numpy.zeros_like(x) import",
"(N,1)) prob = Q[i_ms, I_ms] S = g(m, s, xm, M, parms) XM[:,:]",
"M = P[I_ms,:][None,:] M = numpy.tile(P[I_ms,:], (N,1)) prob = Q[i_ms, I_ms] S =",
"n_ms = P.shape[0] # number of markov states n_mv = P.shape[1] # number",
"s, x, dr, P, Q, parms): N = s.shape[0] n_s = s.shape[1] n_ms",
"aa = model.functions['auxiliary'] f = lambda m,s,x,M,S,X,p: ff(m,s,x,aa(m,s,x,p),M,S,X,aa(M,S,X,p),p) g = lambda m,s,x,M,p: gg(m,s,x,aa(m,s,x,p),M,p)",
"i_ms # m = P[i_ms,:][None,:] m = numpy.tile(P[i_ms,:],(N,1)) xm = x[:,:] for I_ms",
"f = lambda m,s,x,M,S,X,p: ff(m,s,x,aa(m,s,x,p),M,S,X,aa(M,S,X,p),p) g = lambda m,s,x,M,p: gg(m,s,x,aa(m,s,x,p),M,p) P,Q = model.markov_chain",
"P[i_ms,:][None,:] m = numpy.tile(P[i_ms,:],(N,1)) xm = x[:,:] for I_ms in range(n_ms): # M",
"controls = dr(grid) res = residuals(f, g, i_mc, grid, controls, mdr, P, Q,",
"P[I_ms,:][None,:] M = numpy.tile(P[I_ms,:], (N,1)) prob = Q[i_ms, I_ms] S = g(m, s,",
"model.calibration['parameters'] controls = dr(grid) res = residuals(f, g, i_mc, grid, controls, mdr, P,",
"ff = model.functions['arbitrage'] gg = model.functions['transition'] aa = model.functions['auxiliary'] f = lambda m,s,x,M,S,X,p:",
"= lambda m,s,x,M,S,X,p: ff(m,s,x,aa(m,s,x,p),M,S,X,aa(M,S,X,p),p) g = lambda m,s,x,M,p: gg(m,s,x,aa(m,s,x,p),M,p) P,Q = model.markov_chain parms",
"xm = x[:,:] for I_ms in range(n_ms): # M = P[I_ms,:][None,:] M =",
"i_mc, grid, controls, mdr, P, Q, parms) return res def residuals(f, g, i_ms,",
"= residuals(f, g, i_mc, grid, controls, mdr, P, Q, parms) return res def",
"I_ms in range(n_ms): # M = P[I_ms,:][None,:] M = numpy.tile(P[I_ms,:], (N,1)) prob =",
"time # solving on grid for markov index i_ms # m = P[i_ms,:][None,:]",
"XM = numpy.zeros_like(x) import time # solving on grid for markov index i_ms",
"for I_ms in range(n_ms): # M = P[I_ms,:][None,:] M = numpy.tile(P[I_ms,:], (N,1)) prob",
"in range(n_ms): # M = P[I_ms,:][None,:] M = numpy.tile(P[I_ms,:], (N,1)) prob = Q[i_ms,",
"= x[:,:] for I_ms in range(n_ms): # M = P[I_ms,:][None,:] M = numpy.tile(P[I_ms,:],",
"dr(grid) res = residuals(f, g, i_mc, grid, controls, mdr, P, Q, parms) return",
"numpy.zeros_like(x) import time # solving on grid for markov index i_ms # m",
"= model.calibration['parameters'] controls = dr(grid) res = residuals(f, g, i_mc, grid, controls, mdr,",
"number of markov variable res = numpy.zeros_like(x) XM = numpy.zeros_like(x) import time #",
"gg(m,s,x,aa(m,s,x,p),M,p) P,Q = model.markov_chain parms = model.calibration['parameters'] controls = dr(grid) res = residuals(f,",
"s.shape[0] n_s = s.shape[1] n_ms = P.shape[0] # number of markov states n_mv",
"return res def residuals(f, g, i_ms, s, x, dr, P, Q, parms): N",
"parms) return res def residuals(f, g, i_ms, s, x, dr, P, Q, parms):",
"n_s = s.shape[1] n_ms = P.shape[0] # number of markov states n_mv =",
"ff(m,s,x,aa(m,s,x,p),M,S,X,aa(M,S,X,p),p) g = lambda m,s,x,M,p: gg(m,s,x,aa(m,s,x,p),M,p) P,Q = model.markov_chain parms = model.calibration['parameters'] controls",
"= model.markov_chain parms = model.calibration['parameters'] controls = dr(grid) res = residuals(f, g, i_mc,",
"# M = P[I_ms,:][None,:] M = numpy.tile(P[I_ms,:], (N,1)) prob = Q[i_ms, I_ms] S",
"= numpy.tile(P[I_ms,:], (N,1)) prob = Q[i_ms, I_ms] S = g(m, s, xm, M,",
"# number of markov variable res = numpy.zeros_like(x) XM = numpy.zeros_like(x) import time",
"lambda m,s,x,M,S,X,p: ff(m,s,x,aa(m,s,x,p),M,S,X,aa(M,S,X,p),p) g = lambda m,s,x,M,p: gg(m,s,x,aa(m,s,x,p),M,p) P,Q = model.markov_chain parms =",
"model.functions['auxiliary'] f = lambda m,s,x,M,S,X,p: ff(m,s,x,aa(m,s,x,p),M,S,X,aa(M,S,X,p),p) g = lambda m,s,x,M,p: gg(m,s,x,aa(m,s,x,p),M,p) P,Q =",
"= P[i_ms,:][None,:] m = numpy.tile(P[i_ms,:],(N,1)) xm = x[:,:] for I_ms in range(n_ms): #",
"range(n_ms): # M = P[I_ms,:][None,:] M = numpy.tile(P[I_ms,:], (N,1)) prob = Q[i_ms, I_ms]",
"of markov states n_mv = P.shape[1] # number of markov variable res =",
"I_ms] S = g(m, s, xm, M, parms) XM[:,:] = dr(I_ms, S) rr",
"def residuals(f, g, i_ms, s, x, dr, P, Q, parms): N = s.shape[0]",
"m = numpy.tile(P[i_ms,:],(N,1)) xm = x[:,:] for I_ms in range(n_ms): # M =",
"res = residuals(f, g, i_mc, grid, controls, mdr, P, Q, parms) return res",
"variable res = numpy.zeros_like(x) XM = numpy.zeros_like(x) import time # solving on grid",
"# solving on grid for markov index i_ms # m = P[i_ms,:][None,:] m",
"P,Q = model.markov_chain parms = model.calibration['parameters'] controls = dr(grid) res = residuals(f, g,",
"residuals(f, g, i_mc, grid, controls, mdr, P, Q, parms) return res def residuals(f,",
"= P[I_ms,:][None,:] M = numpy.tile(P[I_ms,:], (N,1)) prob = Q[i_ms, I_ms] S = g(m,",
"xm, M, parms) XM[:,:] = dr(I_ms, S) rr = f(m,s,xm,M,S,XM,parms) res[:,:] += prob*rr",
"= s.shape[0] n_s = s.shape[1] n_ms = P.shape[0] # number of markov states",
"M, parms) XM[:,:] = dr(I_ms, S) rr = f(m,s,xm,M,S,XM,parms) res[:,:] += prob*rr return",
"states n_mv = P.shape[1] # number of markov variable res = numpy.zeros_like(x) XM",
"= numpy.zeros_like(x) import time # solving on grid for markov index i_ms #",
"parms = model.calibration['parameters'] controls = dr(grid) res = residuals(f, g, i_mc, grid, controls,",
"grid): ff = model.functions['arbitrage'] gg = model.functions['transition'] aa = model.functions['auxiliary'] f = lambda",
"= lambda m,s,x,M,p: gg(m,s,x,aa(m,s,x,p),M,p) P,Q = model.markov_chain parms = model.calibration['parameters'] controls = dr(grid)",
"P, Q, parms) return res def residuals(f, g, i_ms, s, x, dr, P,",
"m,s,x,M,p: gg(m,s,x,aa(m,s,x,p),M,p) P,Q = model.markov_chain parms = model.calibration['parameters'] controls = dr(grid) res =",
"number of markov states n_mv = P.shape[1] # number of markov variable res",
"import division def compute_residuals(model, dr, grid): ff = model.functions['arbitrage'] gg = model.functions['transition'] aa",
"dr, P, Q, parms): N = s.shape[0] n_s = s.shape[1] n_ms = P.shape[0]",
"i_ms, s, x, dr, P, Q, parms): N = s.shape[0] n_s = s.shape[1]",
"= P.shape[0] # number of markov states n_mv = P.shape[1] # number of",
"S = g(m, s, xm, M, parms) XM[:,:] = dr(I_ms, S) rr =",
"mdr, P, Q, parms) return res def residuals(f, g, i_ms, s, x, dr,",
"P, Q, parms): N = s.shape[0] n_s = s.shape[1] n_ms = P.shape[0] #",
"= numpy.zeros_like(x) XM = numpy.zeros_like(x) import time # solving on grid for markov",
"model.functions['transition'] aa = model.functions['auxiliary'] f = lambda m,s,x,M,S,X,p: ff(m,s,x,aa(m,s,x,p),M,S,X,aa(M,S,X,p),p) g = lambda m,s,x,M,p:",
"Q, parms): N = s.shape[0] n_s = s.shape[1] n_ms = P.shape[0] # number",
"# number of markov states n_mv = P.shape[1] # number of markov variable",
"g(m, s, xm, M, parms) XM[:,:] = dr(I_ms, S) rr = f(m,s,xm,M,S,XM,parms) res[:,:]",
"markov states n_mv = P.shape[1] # number of markov variable res = numpy.zeros_like(x)",
"residuals(f, g, i_ms, s, x, dr, P, Q, parms): N = s.shape[0] n_s",
"lambda m,s,x,M,p: gg(m,s,x,aa(m,s,x,p),M,p) P,Q = model.markov_chain parms = model.calibration['parameters'] controls = dr(grid) res",
"from __future__ import division def compute_residuals(model, dr, grid): ff = model.functions['arbitrage'] gg =",
"def compute_residuals(model, dr, grid): ff = model.functions['arbitrage'] gg = model.functions['transition'] aa = model.functions['auxiliary']",
"= s.shape[1] n_ms = P.shape[0] # number of markov states n_mv = P.shape[1]",
"model.functions['arbitrage'] gg = model.functions['transition'] aa = model.functions['auxiliary'] f = lambda m,s,x,M,S,X,p: ff(m,s,x,aa(m,s,x,p),M,S,X,aa(M,S,X,p),p) g",
"= model.functions['transition'] aa = model.functions['auxiliary'] f = lambda m,s,x,M,S,X,p: ff(m,s,x,aa(m,s,x,p),M,S,X,aa(M,S,X,p),p) g = lambda",
"x, dr, P, Q, parms): N = s.shape[0] n_s = s.shape[1] n_ms =",
"Q[i_ms, I_ms] S = g(m, s, xm, M, parms) XM[:,:] = dr(I_ms, S)",
"index i_ms # m = P[i_ms,:][None,:] m = numpy.tile(P[i_ms,:],(N,1)) xm = x[:,:] for",
"n_mv = P.shape[1] # number of markov variable res = numpy.zeros_like(x) XM =",
"numpy.zeros_like(x) XM = numpy.zeros_like(x) import time # solving on grid for markov index",
"grid, controls, mdr, P, Q, parms) return res def residuals(f, g, i_ms, s,",
"m = P[i_ms,:][None,:] m = numpy.tile(P[i_ms,:],(N,1)) xm = x[:,:] for I_ms in range(n_ms):",
"markov index i_ms # m = P[i_ms,:][None,:] m = numpy.tile(P[i_ms,:],(N,1)) xm = x[:,:]",
"= model.functions['arbitrage'] gg = model.functions['transition'] aa = model.functions['auxiliary'] f = lambda m,s,x,M,S,X,p: ff(m,s,x,aa(m,s,x,p),M,S,X,aa(M,S,X,p),p)",
"res def residuals(f, g, i_ms, s, x, dr, P, Q, parms): N ="
] |
[
"token): invite = MemberInvite.query.filter_by(token=token).first() if not invite: flash(\"Invalid invite link\", \"error\") return redirect(url_for(\"auth.login\",",
"has been sent\", \"success\") return redirect( url_for(\"dashboard.index\", org_username=invite.organization.username) ) return render_template( \"members/join.html\", invite=invite,",
"flash(\"Member account is already enabled\", \"error\") elif member == current_user: flash(\"You can not",
"render_template( \"members/index.html\", all_invites=all_invites, members=members ) @members.route(\"/invite/<invite_id>/remove\", methods=[\"POST\"]) @login_required def remove_invite(org_username, invite_id): invite =",
"\"POST\"]) def join(org_username, token): invite = MemberInvite.query.filter_by(token=token).first() if not invite: flash(\"Invalid invite link\",",
"own account\", \"error\") else: member.disabled_at = None db.session.commit() flash(\"Member account has been enabled\",",
") @members.route(\"/invite/<invite_id>/remove\", methods=[\"POST\"]) @login_required def remove_invite(org_username, invite_id): invite = MemberInvite.query.filter_by( organization=current_user.organization, id=invite_id ).first()",
"@members.route(\"/enable/\", methods=[\"POST\"]) @login_required def enable_account(org_username): member_id = request.form.get(\"member_id\") member = Member.query.filter_by( id=member_id, organization=current_user.organization",
"is None: flash(\"Member account is not found\", \"error\") elif member.disabled_at: flash(\"Member account is",
"= request.form.get(\"member_id\") member = Member.query.filter_by( id=member_id, organization=current_user.organization ).first() if member is None: flash(\"Member",
"if invite is None: flash(\"Unable to find invite to remove\", \"error\") else: db.session.delete(invite)",
"from flask_login import current_user, login_required, login_user from flask_mail import Message from .forms import",
"= Message( \"Worktable organization join invite\", sender=\"<EMAIL>\", recipients=[new_invite.email], ) msg.body = render_template( \"members/invite_mail.txt\",",
"is None: flash(\"Unable to find invite to remove\", \"error\") else: db.session.delete(invite) db.session.commit() flash(\"Invite",
"is already enabled\", \"error\") elif member == current_user: flash(\"You can not enable your",
"db.session.add(new_member) db.session.delete(invite) db.session.commit() login_user(new_member) flash(\"New member invite has been sent\", \"success\") return redirect(",
"if member is None: flash(\"Member account is not found\", \"error\") elif member.disabled_at is",
") return render_template(\"members/invite.html\", form=member_invite) @members.route(\"/join/<token>\", methods=[\"GET\", \"POST\"]) def join(org_username, token): invite = MemberInvite.query.filter_by(token=token).first()",
"organization join invite\", sender=\"<EMAIL>\", recipients=[new_invite.email], ) msg.body = render_template( \"members/invite_mail.txt\", join_link=invite_link, org_name=current_user.organization.name, )",
") msg.html = render_template( \"members/invite_mail.html\", join_link=invite_link, org_name=current_user.organization.name, ) mail.send(msg) flash(\"New member invite has",
"methods=[\"GET\", \"POST\"]) def join(org_username, token): invite = MemberInvite.query.filter_by(token=token).first() if not invite: flash(\"Invalid invite",
"to find invite to remove\", \"error\") else: db.session.delete(invite) db.session.commit() flash(\"Invite removed successfully\", \"success\")",
") msg.body = render_template( \"members/invite_mail.txt\", join_link=invite_link, org_name=current_user.organization.name, ) msg.html = render_template( \"members/invite_mail.html\", join_link=invite_link,",
"invite: flash(\"Invite already sent.\", \"warning\") return redirect( url_for( \"members.index\", org_username=current_user.organization.username, ) ) new_invite",
"invite: flash(\"Invalid invite link\", \"error\") return redirect(url_for(\"auth.login\", org_username=org_username)) member_join = MemberJoinForm() if member_join.validate_on_submit():",
"redirect_url = url_for(\".index\", org_username=current_user.organization.username) return redirect(redirect_url) @members.route(\"/enable/\", methods=[\"POST\"]) @login_required def enable_account(org_username): member_id =",
"MemberInviteForm, MemberJoinForm members = Blueprint( \"members\", __name__, subdomain=\"<org_username>\", template_folder=\"templates\" ) @members.route(\"/\") @login_required def",
"= MemberInvite.query.filter_by( organization=current_user.organization ).all() return render_template( \"members/index.html\", all_invites=all_invites, members=members ) @members.route(\"/invite/<invite_id>/remove\", methods=[\"POST\"]) @login_required",
"db.session.commit() flash(\"Member account has been enabled\", \"success\") redirect_url = url_for(\".index\", org_username=current_user.organization.username) return redirect(redirect_url)",
"if member_join.validate_on_submit(): new_member = Member( first_name=member_join.first_name.data, last_name=member_join.last_name.data, email=invite.email, organization=invite.organization, ) new_member.password = member_join.password.data",
"return redirect( url_for( \"members.index\", org_username=current_user.organization.username, ) ) @members.route(\"/invite/\", methods=[\"GET\", \"POST\"]) @login_required def invite(org_username):",
"import MemberInviteForm, MemberJoinForm members = Blueprint( \"members\", __name__, subdomain=\"<org_username>\", template_folder=\"templates\" ) @members.route(\"/\") @login_required",
"elif member.disabled_at: flash(\"Member account is already disabled\", \"error\") elif member == current_user: flash(\"You",
"== current_user: flash(\"You can not disabled your own account\", \"error\") else: member.disabled_at =",
"datetime.datetime.utcnow() db.session.commit() flash(\"Member account has been disabled\", \"success\") redirect_url = url_for(\".index\", org_username=current_user.organization.username) return",
"Member.query.filter_by(organization=current_user.organization).paginate( int(member_page), 5 ) all_invites = MemberInvite.query.filter_by( organization=current_user.organization ).all() return render_template( \"members/index.html\", all_invites=all_invites,",
"not disabled your own account\", \"error\") else: member.disabled_at = datetime.datetime.utcnow() db.session.commit() flash(\"Member account",
"is None: flash(\"Member account is not found\", \"error\") elif member.disabled_at is None: flash(\"Member",
"msg.body = render_template( \"members/invite_mail.txt\", join_link=invite_link, org_name=current_user.organization.name, ) msg.html = render_template( \"members/invite_mail.html\", join_link=invite_link, org_name=current_user.organization.name,",
"return redirect( url_for(\"dashboard.index\", org_username=invite.organization.username) ) return render_template( \"members/join.html\", invite=invite, form=member_join, token=token ) @members.route(\"/disable/\",",
"None db.session.commit() flash(\"Member account has been enabled\", \"success\") redirect_url = url_for(\".index\", org_username=current_user.organization.username) return",
"token=new_invite.token, _external=True, ) msg = Message( \"Worktable organization join invite\", sender=\"<EMAIL>\", recipients=[new_invite.email], )",
"been sent\", \"success\") return redirect( url_for(\"dashboard.index\", org_username=invite.organization.username) ) return render_template( \"members/join.html\", invite=invite, form=member_join,",
"org_username=current_user.organization.username) return redirect(redirect_url) @members.route(\"/enable/\", methods=[\"POST\"]) @login_required def enable_account(org_username): member_id = request.form.get(\"member_id\") member =",
"member_join.validate_on_submit(): new_member = Member( first_name=member_join.first_name.data, last_name=member_join.last_name.data, email=invite.email, organization=invite.organization, ) new_member.password = member_join.password.data db.session.add(new_member)",
"= url_for( \".join\", org_username=current_user.organization.username, token=new_invite.token, _external=True, ) msg = Message( \"Worktable organization join",
"invite has been sent\", \"success\") return redirect( url_for(\"dashboard.index\", org_username=invite.organization.username) ) return render_template( \"members/join.html\",",
"\"members/join.html\", invite=invite, form=member_join, token=token ) @members.route(\"/disable/\", methods=[\"POST\"]) @login_required def disable_account(org_username): member_id = request.form.get(\"member_id\")",
"= member_invite.email.data.lower() member = Member.query.filter_by( email=email, organization=current_user.organization ).first() if member: flash(\"Email is already",
"org_username=org_username)) member_join = MemberJoinForm() if member_join.validate_on_submit(): new_member = Member( first_name=member_join.first_name.data, last_name=member_join.last_name.data, email=invite.email, organization=invite.organization,",
"flash(\"You can not enable your own account\", \"error\") else: member.disabled_at = None db.session.commit()",
"db.session.add(new_invite) db.session.commit() invite_link = url_for( \".join\", org_username=current_user.organization.username, token=new_invite.token, _external=True, ) msg = Message(",
"url_for( \"members.index\", org_username=current_user.organization.username, ) ) @members.route(\"/invite/\", methods=[\"GET\", \"POST\"]) @login_required def invite(org_username): member_invite =",
"_external=True, ) msg = Message( \"Worktable organization join invite\", sender=\"<EMAIL>\", recipients=[new_invite.email], ) msg.body",
"\"error\") elif member.disabled_at is None: flash(\"Member account is already enabled\", \"error\") elif member",
") mail.send(msg) flash(\"New member invite has been sent\", \"success\") return redirect( url_for(\"members.index\", org_username=current_user.organization.username)",
"can not disabled your own account\", \"error\") else: member.disabled_at = datetime.datetime.utcnow() db.session.commit() flash(\"Member",
"MemberInvite from flask import Blueprint, flash, redirect, render_template, request, url_for from flask_login import",
"flask_login import current_user, login_required, login_user from flask_mail import Message from .forms import MemberInviteForm,",
"your own account\", \"error\") else: member.disabled_at = datetime.datetime.utcnow() db.session.commit() flash(\"Member account has been",
"redirect(redirect_url) @members.route(\"/enable/\", methods=[\"POST\"]) @login_required def enable_account(org_username): member_id = request.form.get(\"member_id\") member = Member.query.filter_by( id=member_id,",
"email=invite.email, organization=invite.organization, ) new_member.password = member_join.password.data db.session.add(new_member) db.session.delete(invite) db.session.commit() login_user(new_member) flash(\"New member invite",
"= MemberInvite.query.filter_by(token=token).first() if not invite: flash(\"Invalid invite link\", \"error\") return redirect(url_for(\"auth.login\", org_username=org_username)) member_join",
"return redirect( url_for(\"members.index\", org_username=current_user.organization.username) ) return render_template(\"members/invite.html\", form=member_invite) @members.route(\"/join/<token>\", methods=[\"GET\", \"POST\"]) def join(org_username,",
"request.form.get(\"member_id\") member = Member.query.filter_by( id=member_id, organization=current_user.organization ).first() if member is None: flash(\"Member account",
"member is None: flash(\"Member account is not found\", \"error\") elif member.disabled_at: flash(\"Member account",
"last_name=member_join.last_name.data, email=invite.email, organization=invite.organization, ) new_member.password = member_join.password.data db.session.add(new_member) db.session.delete(invite) db.session.commit() login_user(new_member) flash(\"New member",
"url_for( \".join\", org_username=current_user.organization.username, token=new_invite.token, _external=True, ) msg = Message( \"Worktable organization join invite\",",
"= None db.session.commit() flash(\"Member account has been enabled\", \"success\") redirect_url = url_for(\".index\", org_username=current_user.organization.username)",
"return redirect(redirect_url) @members.route(\"/enable/\", methods=[\"POST\"]) @login_required def enable_account(org_username): member_id = request.form.get(\"member_id\") member = Member.query.filter_by(",
"db, mail from app.models import Member, MemberInvite from flask import Blueprint, flash, redirect,",
"\"error\") elif member == current_user: flash(\"You can not disabled your own account\", \"error\")",
"login_required, login_user from flask_mail import Message from .forms import MemberInviteForm, MemberJoinForm members =",
"org_username=current_user.organization.username, token=new_invite.token, _external=True, ) msg = Message( \"Worktable organization join invite\", sender=\"<EMAIL>\", recipients=[new_invite.email],",
"flash(\"Invite removed successfully\", \"success\") return redirect( url_for( \"members.index\", org_username=current_user.organization.username, ) ) @members.route(\"/invite/\", methods=[\"GET\",",
"all_invites=all_invites, members=members ) @members.route(\"/invite/<invite_id>/remove\", methods=[\"POST\"]) @login_required def remove_invite(org_username, invite_id): invite = MemberInvite.query.filter_by( organization=current_user.organization,",
"recipients=[new_invite.email], ) msg.body = render_template( \"members/invite_mail.txt\", join_link=invite_link, org_name=current_user.organization.name, ) msg.html = render_template( \"members/invite_mail.html\",",
").first() if member is None: flash(\"Member account is not found\", \"error\") elif member.disabled_at",
") @members.route(\"/disable/\", methods=[\"POST\"]) @login_required def disable_account(org_username): member_id = request.form.get(\"member_id\") member = Member.query.filter_by( id=member_id,",
"@login_required def index(org_username): member_page = request.args.get(\"member_page\", 1) members = Member.query.filter_by(organization=current_user.organization).paginate( int(member_page), 5 )",
"MemberInvite.query.filter_by(token=token).first() if not invite: flash(\"Invalid invite link\", \"error\") return redirect(url_for(\"auth.login\", org_username=org_username)) member_join =",
"import db, mail from app.models import Member, MemberInvite from flask import Blueprint, flash,",
"request, url_for from flask_login import current_user, login_required, login_user from flask_mail import Message from",
"def invite(org_username): member_invite = MemberInviteForm() if member_invite.validate_on_submit(): email = member_invite.email.data.lower() member = Member.query.filter_by(",
"MemberInviteForm() if member_invite.validate_on_submit(): email = member_invite.email.data.lower() member = Member.query.filter_by( email=email, organization=current_user.organization ).first() if",
"MemberInvite.query.filter_by( organization=current_user.organization, id=invite_id ).first() if invite is None: flash(\"Unable to find invite to",
"= MemberJoinForm() if member_join.validate_on_submit(): new_member = Member( first_name=member_join.first_name.data, last_name=member_join.last_name.data, email=invite.email, organization=invite.organization, ) new_member.password",
"url_for(\"dashboard.index\", org_username=invite.organization.username) ) return render_template( \"members/join.html\", invite=invite, form=member_join, token=token ) @members.route(\"/disable/\", methods=[\"POST\"]) @login_required",
"\"Worktable organization join invite\", sender=\"<EMAIL>\", recipients=[new_invite.email], ) msg.body = render_template( \"members/invite_mail.txt\", join_link=invite_link, org_name=current_user.organization.name,",
"request.args.get(\"member_page\", 1) members = Member.query.filter_by(organization=current_user.organization).paginate( int(member_page), 5 ) all_invites = MemberInvite.query.filter_by( organization=current_user.organization ).all()",
"= Member.query.filter_by( email=email, organization=current_user.organization ).first() if member: flash(\"Email is already a member\", \"error\")",
"invite has been sent\", \"success\") return redirect( url_for(\"members.index\", org_username=current_user.organization.username) ) return render_template(\"members/invite.html\", form=member_invite)",
"datetime from app import db, mail from app.models import Member, MemberInvite from flask",
"flash(\"Member account is already disabled\", \"error\") elif member == current_user: flash(\"You can not",
"redirect( url_for( \"members.index\", org_username=current_user.organization.username, ) ) invite = MemberInvite.query.filter_by( organization=current_user.organization, email=email ).first() if",
"org_username=invite.organization.username) ) return render_template( \"members/join.html\", invite=invite, form=member_join, token=token ) @members.route(\"/disable/\", methods=[\"POST\"]) @login_required def",
"sent\", \"success\") return redirect( url_for(\"dashboard.index\", org_username=invite.organization.username) ) return render_template( \"members/join.html\", invite=invite, form=member_join, token=token",
"def join(org_username, token): invite = MemberInvite.query.filter_by(token=token).first() if not invite: flash(\"Invalid invite link\", \"error\")",
") new_member.password = member_join.password.data db.session.add(new_member) db.session.delete(invite) db.session.commit() login_user(new_member) flash(\"New member invite has been",
"if invite: flash(\"Invite already sent.\", \"warning\") return redirect( url_for( \"members.index\", org_username=current_user.organization.username, ) )",
"invite to remove\", \"error\") else: db.session.delete(invite) db.session.commit() flash(\"Invite removed successfully\", \"success\") return redirect(",
"can not enable your own account\", \"error\") else: member.disabled_at = None db.session.commit() flash(\"Member",
"flash(\"Unable to find invite to remove\", \"error\") else: db.session.delete(invite) db.session.commit() flash(\"Invite removed successfully\",",
"redirect(url_for(\"auth.login\", org_username=org_username)) member_join = MemberJoinForm() if member_join.validate_on_submit(): new_member = Member( first_name=member_join.first_name.data, last_name=member_join.last_name.data, email=invite.email,",
"import Message from .forms import MemberInviteForm, MemberJoinForm members = Blueprint( \"members\", __name__, subdomain=\"<org_username>\",",
"@login_required def remove_invite(org_username, invite_id): invite = MemberInvite.query.filter_by( organization=current_user.organization, id=invite_id ).first() if invite is",
"sender=\"<EMAIL>\", recipients=[new_invite.email], ) msg.body = render_template( \"members/invite_mail.txt\", join_link=invite_link, org_name=current_user.organization.name, ) msg.html = render_template(",
"member is None: flash(\"Member account is not found\", \"error\") elif member.disabled_at is None:",
"invite_link = url_for( \".join\", org_username=current_user.organization.username, token=new_invite.token, _external=True, ) msg = Message( \"Worktable organization",
"\"error\") return redirect(url_for(\"auth.login\", org_username=org_username)) member_join = MemberJoinForm() if member_join.validate_on_submit(): new_member = Member( first_name=member_join.first_name.data,",
"account\", \"error\") else: member.disabled_at = datetime.datetime.utcnow() db.session.commit() flash(\"Member account has been disabled\", \"success\")",
"has been sent\", \"success\") return redirect( url_for(\"members.index\", org_username=current_user.organization.username) ) return render_template(\"members/invite.html\", form=member_invite) @members.route(\"/join/<token>\",",
"= request.args.get(\"member_page\", 1) members = Member.query.filter_by(organization=current_user.organization).paginate( int(member_page), 5 ) all_invites = MemberInvite.query.filter_by( organization=current_user.organization",
"join_link=invite_link, org_name=current_user.organization.name, ) msg.html = render_template( \"members/invite_mail.html\", join_link=invite_link, org_name=current_user.organization.name, ) mail.send(msg) flash(\"New member",
"disabled\", \"error\") elif member == current_user: flash(\"You can not disabled your own account\",",
"import Blueprint, flash, redirect, render_template, request, url_for from flask_login import current_user, login_required, login_user",
"5 ) all_invites = MemberInvite.query.filter_by( organization=current_user.organization ).all() return render_template( \"members/index.html\", all_invites=all_invites, members=members )",
"render_template( \"members/invite_mail.html\", join_link=invite_link, org_name=current_user.organization.name, ) mail.send(msg) flash(\"New member invite has been sent\", \"success\")",
"MemberInvite(email=email, organization=current_user.organization) db.session.add(new_invite) db.session.commit() invite_link = url_for( \".join\", org_username=current_user.organization.username, token=new_invite.token, _external=True, ) msg",
"link\", \"error\") return redirect(url_for(\"auth.login\", org_username=org_username)) member_join = MemberJoinForm() if member_join.validate_on_submit(): new_member = Member(",
"member.disabled_at is None: flash(\"Member account is already enabled\", \"error\") elif member == current_user:",
"members=members ) @members.route(\"/invite/<invite_id>/remove\", methods=[\"POST\"]) @login_required def remove_invite(org_username, invite_id): invite = MemberInvite.query.filter_by( organization=current_user.organization, id=invite_id",
"member_invite.validate_on_submit(): email = member_invite.email.data.lower() member = Member.query.filter_by( email=email, organization=current_user.organization ).first() if member: flash(\"Email",
"= member_join.password.data db.session.add(new_member) db.session.delete(invite) db.session.commit() login_user(new_member) flash(\"New member invite has been sent\", \"success\")",
"Message from .forms import MemberInviteForm, MemberJoinForm members = Blueprint( \"members\", __name__, subdomain=\"<org_username>\", template_folder=\"templates\"",
"= Blueprint( \"members\", __name__, subdomain=\"<org_username>\", template_folder=\"templates\" ) @members.route(\"/\") @login_required def index(org_username): member_page =",
"@login_required def invite(org_username): member_invite = MemberInviteForm() if member_invite.validate_on_submit(): email = member_invite.email.data.lower() member =",
"email=email ).first() if invite: flash(\"Invite already sent.\", \"warning\") return redirect( url_for( \"members.index\", org_username=current_user.organization.username,",
"template_folder=\"templates\" ) @members.route(\"/\") @login_required def index(org_username): member_page = request.args.get(\"member_page\", 1) members = Member.query.filter_by(organization=current_user.organization).paginate(",
"member invite has been sent\", \"success\") return redirect( url_for(\"dashboard.index\", org_username=invite.organization.username) ) return render_template(",
"already disabled\", \"error\") elif member == current_user: flash(\"You can not disabled your own",
"remove_invite(org_username, invite_id): invite = MemberInvite.query.filter_by( organization=current_user.organization, id=invite_id ).first() if invite is None: flash(\"Unable",
"current_user: flash(\"You can not disabled your own account\", \"error\") else: member.disabled_at = datetime.datetime.utcnow()",
"organization=current_user.organization ).first() if member: flash(\"Email is already a member\", \"error\") return redirect( url_for(",
"current_user, login_required, login_user from flask_mail import Message from .forms import MemberInviteForm, MemberJoinForm members",
"return redirect(url_for(\"auth.login\", org_username=org_username)) member_join = MemberJoinForm() if member_join.validate_on_submit(): new_member = Member( first_name=member_join.first_name.data, last_name=member_join.last_name.data,",
"\"error\") elif member == current_user: flash(\"You can not enable your own account\", \"error\")",
"member_join.password.data db.session.add(new_member) db.session.delete(invite) db.session.commit() login_user(new_member) flash(\"New member invite has been sent\", \"success\") return",
"Member.query.filter_by( id=member_id, organization=current_user.organization ).first() if member is None: flash(\"Member account is not found\",",
"member == current_user: flash(\"You can not disabled your own account\", \"error\") else: member.disabled_at",
"def remove_invite(org_username, invite_id): invite = MemberInvite.query.filter_by( organization=current_user.organization, id=invite_id ).first() if invite is None:",
"find invite to remove\", \"error\") else: db.session.delete(invite) db.session.commit() flash(\"Invite removed successfully\", \"success\") return",
"disable_account(org_username): member_id = request.form.get(\"member_id\") member = Member.query.filter_by( id=member_id, organization=current_user.organization ).first() if member is",
"redirect( url_for( \"members.index\", org_username=current_user.organization.username, ) ) @members.route(\"/invite/\", methods=[\"GET\", \"POST\"]) @login_required def invite(org_username): member_invite",
"member.disabled_at = datetime.datetime.utcnow() db.session.commit() flash(\"Member account has been disabled\", \"success\") redirect_url = url_for(\".index\",",
") @members.route(\"/\") @login_required def index(org_username): member_page = request.args.get(\"member_page\", 1) members = Member.query.filter_by(organization=current_user.organization).paginate( int(member_page),",
"to remove\", \"error\") else: db.session.delete(invite) db.session.commit() flash(\"Invite removed successfully\", \"success\") return redirect( url_for(",
"redirect, render_template, request, url_for from flask_login import current_user, login_required, login_user from flask_mail import",
") ) new_invite = MemberInvite(email=email, organization=current_user.organization) db.session.add(new_invite) db.session.commit() invite_link = url_for( \".join\", org_username=current_user.organization.username,",
"form=member_invite) @members.route(\"/join/<token>\", methods=[\"GET\", \"POST\"]) def join(org_username, token): invite = MemberInvite.query.filter_by(token=token).first() if not invite:",
"current_user: flash(\"You can not enable your own account\", \"error\") else: member.disabled_at = None",
"remove\", \"error\") else: db.session.delete(invite) db.session.commit() flash(\"Invite removed successfully\", \"success\") return redirect( url_for( \"members.index\",",
"account is not found\", \"error\") elif member.disabled_at: flash(\"Member account is already disabled\", \"error\")",
"org_name=current_user.organization.name, ) msg.html = render_template( \"members/invite_mail.html\", join_link=invite_link, org_name=current_user.organization.name, ) mail.send(msg) flash(\"New member invite",
"member: flash(\"Email is already a member\", \"error\") return redirect( url_for( \"members.index\", org_username=current_user.organization.username, )",
"= render_template( \"members/invite_mail.html\", join_link=invite_link, org_name=current_user.organization.name, ) mail.send(msg) flash(\"New member invite has been sent\",",
"not found\", \"error\") elif member.disabled_at: flash(\"Member account is already disabled\", \"error\") elif member",
"app import db, mail from app.models import Member, MemberInvite from flask import Blueprint,",
"return redirect( url_for( \"members.index\", org_username=current_user.organization.username, ) ) invite = MemberInvite.query.filter_by( organization=current_user.organization, email=email ).first()",
"url_for(\"members.index\", org_username=current_user.organization.username) ) return render_template(\"members/invite.html\", form=member_invite) @members.route(\"/join/<token>\", methods=[\"GET\", \"POST\"]) def join(org_username, token): invite",
"invite = MemberInvite.query.filter_by(token=token).first() if not invite: flash(\"Invalid invite link\", \"error\") return redirect(url_for(\"auth.login\", org_username=org_username))",
"has been disabled\", \"success\") redirect_url = url_for(\".index\", org_username=current_user.organization.username) return redirect(redirect_url) @members.route(\"/enable/\", methods=[\"POST\"]) @login_required",
"render_template( \"members/join.html\", invite=invite, form=member_join, token=token ) @members.route(\"/disable/\", methods=[\"POST\"]) @login_required def disable_account(org_username): member_id =",
"\"error\") else: member.disabled_at = datetime.datetime.utcnow() db.session.commit() flash(\"Member account has been disabled\", \"success\") redirect_url",
") return render_template( \"members/join.html\", invite=invite, form=member_join, token=token ) @members.route(\"/disable/\", methods=[\"POST\"]) @login_required def disable_account(org_username):",
"\"members.index\", org_username=current_user.organization.username, ) ) invite = MemberInvite.query.filter_by( organization=current_user.organization, email=email ).first() if invite: flash(\"Invite",
"org_username=current_user.organization.username, ) ) @members.route(\"/invite/\", methods=[\"GET\", \"POST\"]) @login_required def invite(org_username): member_invite = MemberInviteForm() if",
"@members.route(\"/join/<token>\", methods=[\"GET\", \"POST\"]) def join(org_username, token): invite = MemberInvite.query.filter_by(token=token).first() if not invite: flash(\"Invalid",
"from flask import Blueprint, flash, redirect, render_template, request, url_for from flask_login import current_user,",
"url_for from flask_login import current_user, login_required, login_user from flask_mail import Message from .forms",
"else: member.disabled_at = None db.session.commit() flash(\"Member account has been enabled\", \"success\") redirect_url =",
"members = Member.query.filter_by(organization=current_user.organization).paginate( int(member_page), 5 ) all_invites = MemberInvite.query.filter_by( organization=current_user.organization ).all() return render_template(",
"invite = MemberInvite.query.filter_by( organization=current_user.organization, email=email ).first() if invite: flash(\"Invite already sent.\", \"warning\") return",
"methods=[\"GET\", \"POST\"]) @login_required def invite(org_username): member_invite = MemberInviteForm() if member_invite.validate_on_submit(): email = member_invite.email.data.lower()",
"invite link\", \"error\") return redirect(url_for(\"auth.login\", org_username=org_username)) member_join = MemberJoinForm() if member_join.validate_on_submit(): new_member =",
"elif member == current_user: flash(\"You can not disabled your own account\", \"error\") else:",
") ) @members.route(\"/invite/\", methods=[\"GET\", \"POST\"]) @login_required def invite(org_username): member_invite = MemberInviteForm() if member_invite.validate_on_submit():",
"subdomain=\"<org_username>\", template_folder=\"templates\" ) @members.route(\"/\") @login_required def index(org_username): member_page = request.args.get(\"member_page\", 1) members =",
") ) invite = MemberInvite.query.filter_by( organization=current_user.organization, email=email ).first() if invite: flash(\"Invite already sent.\",",
"id=invite_id ).first() if invite is None: flash(\"Unable to find invite to remove\", \"error\")",
"elif member.disabled_at is None: flash(\"Member account is already enabled\", \"error\") elif member ==",
"all_invites = MemberInvite.query.filter_by( organization=current_user.organization ).all() return render_template( \"members/index.html\", all_invites=all_invites, members=members ) @members.route(\"/invite/<invite_id>/remove\", methods=[\"POST\"])",
"@members.route(\"/invite/\", methods=[\"GET\", \"POST\"]) @login_required def invite(org_username): member_invite = MemberInviteForm() if member_invite.validate_on_submit(): email =",
"= MemberInvite.query.filter_by( organization=current_user.organization, email=email ).first() if invite: flash(\"Invite already sent.\", \"warning\") return redirect(",
"render_template( \"members/invite_mail.txt\", join_link=invite_link, org_name=current_user.organization.name, ) msg.html = render_template( \"members/invite_mail.html\", join_link=invite_link, org_name=current_user.organization.name, ) mail.send(msg)",
"__name__, subdomain=\"<org_username>\", template_folder=\"templates\" ) @members.route(\"/\") @login_required def index(org_username): member_page = request.args.get(\"member_page\", 1) members",
"url_for( \"members.index\", org_username=current_user.organization.username, ) ) new_invite = MemberInvite(email=email, organization=current_user.organization) db.session.add(new_invite) db.session.commit() invite_link =",
"MemberInvite.query.filter_by( organization=current_user.organization ).all() return render_template( \"members/index.html\", all_invites=all_invites, members=members ) @members.route(\"/invite/<invite_id>/remove\", methods=[\"POST\"]) @login_required def",
"new_member.password = member_join.password.data db.session.add(new_member) db.session.delete(invite) db.session.commit() login_user(new_member) flash(\"New member invite has been sent\",",
"db.session.delete(invite) db.session.commit() flash(\"Invite removed successfully\", \"success\") return redirect( url_for( \"members.index\", org_username=current_user.organization.username, ) )",
"sent.\", \"warning\") return redirect( url_for( \"members.index\", org_username=current_user.organization.username, ) ) new_invite = MemberInvite(email=email, organization=current_user.organization)",
").first() if member is None: flash(\"Member account is not found\", \"error\") elif member.disabled_at:",
"account has been disabled\", \"success\") redirect_url = url_for(\".index\", org_username=current_user.organization.username) return redirect(redirect_url) @members.route(\"/enable/\", methods=[\"POST\"])",
"index(org_username): member_page = request.args.get(\"member_page\", 1) members = Member.query.filter_by(organization=current_user.organization).paginate( int(member_page), 5 ) all_invites =",
"None: flash(\"Member account is not found\", \"error\") elif member.disabled_at: flash(\"Member account is already",
"msg.html = render_template( \"members/invite_mail.html\", join_link=invite_link, org_name=current_user.organization.name, ) mail.send(msg) flash(\"New member invite has been",
"return render_template( \"members/join.html\", invite=invite, form=member_join, token=token ) @members.route(\"/disable/\", methods=[\"POST\"]) @login_required def disable_account(org_username): member_id",
"member_invite = MemberInviteForm() if member_invite.validate_on_submit(): email = member_invite.email.data.lower() member = Member.query.filter_by( email=email, organization=current_user.organization",
"organization=current_user.organization, email=email ).first() if invite: flash(\"Invite already sent.\", \"warning\") return redirect( url_for( \"members.index\",",
"first_name=member_join.first_name.data, last_name=member_join.last_name.data, email=invite.email, organization=invite.organization, ) new_member.password = member_join.password.data db.session.add(new_member) db.session.delete(invite) db.session.commit() login_user(new_member) flash(\"New",
"\"success\") return redirect( url_for(\"members.index\", org_username=current_user.organization.username) ) return render_template(\"members/invite.html\", form=member_invite) @members.route(\"/join/<token>\", methods=[\"GET\", \"POST\"]) def",
"flash(\"Member account is not found\", \"error\") elif member.disabled_at: flash(\"Member account is already disabled\",",
"members = Blueprint( \"members\", __name__, subdomain=\"<org_username>\", template_folder=\"templates\" ) @members.route(\"/\") @login_required def index(org_username): member_page",
"MemberJoinForm() if member_join.validate_on_submit(): new_member = Member( first_name=member_join.first_name.data, last_name=member_join.last_name.data, email=invite.email, organization=invite.organization, ) new_member.password =",
"flash(\"Member account is not found\", \"error\") elif member.disabled_at is None: flash(\"Member account is",
"sent\", \"success\") return redirect( url_for(\"members.index\", org_username=current_user.organization.username) ) return render_template(\"members/invite.html\", form=member_invite) @members.route(\"/join/<token>\", methods=[\"GET\", \"POST\"])",
"redirect( url_for(\"members.index\", org_username=current_user.organization.username) ) return render_template(\"members/invite.html\", form=member_invite) @members.route(\"/join/<token>\", methods=[\"GET\", \"POST\"]) def join(org_username, token):",
"account\", \"error\") else: member.disabled_at = None db.session.commit() flash(\"Member account has been enabled\", \"success\")",
") @members.route(\"/invite/\", methods=[\"GET\", \"POST\"]) @login_required def invite(org_username): member_invite = MemberInviteForm() if member_invite.validate_on_submit(): email",
"organization=current_user.organization, id=invite_id ).first() if invite is None: flash(\"Unable to find invite to remove\",",
"def disable_account(org_username): member_id = request.form.get(\"member_id\") member = Member.query.filter_by( id=member_id, organization=current_user.organization ).first() if member",
"invite=invite, form=member_join, token=token ) @members.route(\"/disable/\", methods=[\"POST\"]) @login_required def disable_account(org_username): member_id = request.form.get(\"member_id\") member",
"render_template, request, url_for from flask_login import current_user, login_required, login_user from flask_mail import Message",
"from .forms import MemberInviteForm, MemberJoinForm members = Blueprint( \"members\", __name__, subdomain=\"<org_username>\", template_folder=\"templates\" )",
"@members.route(\"/disable/\", methods=[\"POST\"]) @login_required def disable_account(org_username): member_id = request.form.get(\"member_id\") member = Member.query.filter_by( id=member_id, organization=current_user.organization",
"account is already disabled\", \"error\") elif member == current_user: flash(\"You can not disabled",
"\"success\") redirect_url = url_for(\".index\", org_username=current_user.organization.username) return redirect(redirect_url) @members.route(\"/enable/\", methods=[\"POST\"]) @login_required def enable_account(org_username): member_id",
"db.session.delete(invite) db.session.commit() login_user(new_member) flash(\"New member invite has been sent\", \"success\") return redirect( url_for(\"dashboard.index\",",
"not enable your own account\", \"error\") else: member.disabled_at = None db.session.commit() flash(\"Member account",
"flash(\"Invalid invite link\", \"error\") return redirect(url_for(\"auth.login\", org_username=org_username)) member_join = MemberJoinForm() if member_join.validate_on_submit(): new_member",
"disabled\", \"success\") redirect_url = url_for(\".index\", org_username=current_user.organization.username) return redirect(redirect_url) @members.route(\"/enable/\", methods=[\"POST\"]) @login_required def enable_account(org_username):",
"email = member_invite.email.data.lower() member = Member.query.filter_by( email=email, organization=current_user.organization ).first() if member: flash(\"Email is",
"organization=current_user.organization ).all() return render_template( \"members/index.html\", all_invites=all_invites, members=members ) @members.route(\"/invite/<invite_id>/remove\", methods=[\"POST\"]) @login_required def remove_invite(org_username,",
"new_member = Member( first_name=member_join.first_name.data, last_name=member_join.last_name.data, email=invite.email, organization=invite.organization, ) new_member.password = member_join.password.data db.session.add(new_member) db.session.delete(invite)",
"member.disabled_at: flash(\"Member account is already disabled\", \"error\") elif member == current_user: flash(\"You can",
"import datetime from app import db, mail from app.models import Member, MemberInvite from",
"is not found\", \"error\") elif member.disabled_at: flash(\"Member account is already disabled\", \"error\") elif",
"invite_id): invite = MemberInvite.query.filter_by( organization=current_user.organization, id=invite_id ).first() if invite is None: flash(\"Unable to",
"db.session.commit() invite_link = url_for( \".join\", org_username=current_user.organization.username, token=new_invite.token, _external=True, ) msg = Message( \"Worktable",
"email=email, organization=current_user.organization ).first() if member: flash(\"Email is already a member\", \"error\") return redirect(",
"= render_template( \"members/invite_mail.txt\", join_link=invite_link, org_name=current_user.organization.name, ) msg.html = render_template( \"members/invite_mail.html\", join_link=invite_link, org_name=current_user.organization.name, )",
"org_username=current_user.organization.username, ) ) new_invite = MemberInvite(email=email, organization=current_user.organization) db.session.add(new_invite) db.session.commit() invite_link = url_for( \".join\",",
"\"members/invite_mail.txt\", join_link=invite_link, org_name=current_user.organization.name, ) msg.html = render_template( \"members/invite_mail.html\", join_link=invite_link, org_name=current_user.organization.name, ) mail.send(msg) flash(\"New",
"\"error\") elif member.disabled_at: flash(\"Member account is already disabled\", \"error\") elif member == current_user:",
"from app.models import Member, MemberInvite from flask import Blueprint, flash, redirect, render_template, request,",
"if member: flash(\"Email is already a member\", \"error\") return redirect( url_for( \"members.index\", org_username=current_user.organization.username,",
"invite = MemberInvite.query.filter_by( organization=current_user.organization, id=invite_id ).first() if invite is None: flash(\"Unable to find",
"form=member_join, token=token ) @members.route(\"/disable/\", methods=[\"POST\"]) @login_required def disable_account(org_username): member_id = request.form.get(\"member_id\") member =",
").first() if invite: flash(\"Invite already sent.\", \"warning\") return redirect( url_for( \"members.index\", org_username=current_user.organization.username, )",
"org_username=current_user.organization.username) ) return render_template(\"members/invite.html\", form=member_invite) @members.route(\"/join/<token>\", methods=[\"GET\", \"POST\"]) def join(org_username, token): invite =",
"\"members\", __name__, subdomain=\"<org_username>\", template_folder=\"templates\" ) @members.route(\"/\") @login_required def index(org_username): member_page = request.args.get(\"member_page\", 1)",
"member == current_user: flash(\"You can not enable your own account\", \"error\") else: member.disabled_at",
"flash(\"New member invite has been sent\", \"success\") return redirect( url_for(\"dashboard.index\", org_username=invite.organization.username) ) return",
"not found\", \"error\") elif member.disabled_at is None: flash(\"Member account is already enabled\", \"error\")",
") invite = MemberInvite.query.filter_by( organization=current_user.organization, email=email ).first() if invite: flash(\"Invite already sent.\", \"warning\")",
"mail from app.models import Member, MemberInvite from flask import Blueprint, flash, redirect, render_template,",
"url_for(\".index\", org_username=current_user.organization.username) return redirect(redirect_url) @members.route(\"/enable/\", methods=[\"POST\"]) @login_required def enable_account(org_username): member_id = request.form.get(\"member_id\") member",
"methods=[\"POST\"]) @login_required def remove_invite(org_username, invite_id): invite = MemberInvite.query.filter_by( organization=current_user.organization, id=invite_id ).first() if invite",
"\"members/invite_mail.html\", join_link=invite_link, org_name=current_user.organization.name, ) mail.send(msg) flash(\"New member invite has been sent\", \"success\") return",
"redirect( url_for(\"dashboard.index\", org_username=invite.organization.username) ) return render_template( \"members/join.html\", invite=invite, form=member_join, token=token ) @members.route(\"/disable/\", methods=[\"POST\"])",
"if not invite: flash(\"Invalid invite link\", \"error\") return redirect(url_for(\"auth.login\", org_username=org_username)) member_join = MemberJoinForm()",
"\"POST\"]) @login_required def invite(org_username): member_invite = MemberInviteForm() if member_invite.validate_on_submit(): email = member_invite.email.data.lower() member",
"1) members = Member.query.filter_by(organization=current_user.organization).paginate( int(member_page), 5 ) all_invites = MemberInvite.query.filter_by( organization=current_user.organization ).all() return",
"@members.route(\"/invite/<invite_id>/remove\", methods=[\"POST\"]) @login_required def remove_invite(org_username, invite_id): invite = MemberInvite.query.filter_by( organization=current_user.organization, id=invite_id ).first() if",
"Member( first_name=member_join.first_name.data, last_name=member_join.last_name.data, email=invite.email, organization=invite.organization, ) new_member.password = member_join.password.data db.session.add(new_member) db.session.delete(invite) db.session.commit() login_user(new_member)",
"is None: flash(\"Member account is already enabled\", \"error\") elif member == current_user: flash(\"You",
"= MemberInviteForm() if member_invite.validate_on_submit(): email = member_invite.email.data.lower() member = Member.query.filter_by( email=email, organization=current_user.organization ).first()",
"your own account\", \"error\") else: member.disabled_at = None db.session.commit() flash(\"Member account has been",
"flash(\"Member account has been disabled\", \"success\") redirect_url = url_for(\".index\", org_username=current_user.organization.username) return redirect(redirect_url) @members.route(\"/enable/\",",
"None: flash(\"Unable to find invite to remove\", \"error\") else: db.session.delete(invite) db.session.commit() flash(\"Invite removed",
"already enabled\", \"error\") elif member == current_user: flash(\"You can not enable your own",
"if member is None: flash(\"Member account is not found\", \"error\") elif member.disabled_at: flash(\"Member",
"\"members.index\", org_username=current_user.organization.username, ) ) new_invite = MemberInvite(email=email, organization=current_user.organization) db.session.add(new_invite) db.session.commit() invite_link = url_for(",
"== current_user: flash(\"You can not enable your own account\", \"error\") else: member.disabled_at =",
"\"error\") return redirect( url_for( \"members.index\", org_username=current_user.organization.username, ) ) invite = MemberInvite.query.filter_by( organization=current_user.organization, email=email",
"member.disabled_at = None db.session.commit() flash(\"Member account has been enabled\", \"success\") redirect_url = url_for(\".index\",",
"Blueprint, flash, redirect, render_template, request, url_for from flask_login import current_user, login_required, login_user from",
"None: flash(\"Member account is not found\", \"error\") elif member.disabled_at is None: flash(\"Member account",
") msg = Message( \"Worktable organization join invite\", sender=\"<EMAIL>\", recipients=[new_invite.email], ) msg.body =",
"a member\", \"error\") return redirect( url_for( \"members.index\", org_username=current_user.organization.username, ) ) invite = MemberInvite.query.filter_by(",
"Message( \"Worktable organization join invite\", sender=\"<EMAIL>\", recipients=[new_invite.email], ) msg.body = render_template( \"members/invite_mail.txt\", join_link=invite_link,",
"MemberInvite.query.filter_by( organization=current_user.organization, email=email ).first() if invite: flash(\"Invite already sent.\", \"warning\") return redirect( url_for(",
"return redirect( url_for( \"members.index\", org_username=current_user.organization.username, ) ) new_invite = MemberInvite(email=email, organization=current_user.organization) db.session.add(new_invite) db.session.commit()",
"organization=current_user.organization ).first() if member is None: flash(\"Member account is not found\", \"error\") elif",
"def index(org_username): member_page = request.args.get(\"member_page\", 1) members = Member.query.filter_by(organization=current_user.organization).paginate( int(member_page), 5 ) all_invites",
"id=member_id, organization=current_user.organization ).first() if member is None: flash(\"Member account is not found\", \"error\")",
"enable your own account\", \"error\") else: member.disabled_at = None db.session.commit() flash(\"Member account has",
"int(member_page), 5 ) all_invites = MemberInvite.query.filter_by( organization=current_user.organization ).all() return render_template( \"members/index.html\", all_invites=all_invites, members=members",
"def enable_account(org_username): member_id = request.form.get(\"member_id\") member = Member.query.filter_by( id=member_id, organization=current_user.organization ).first() if member",
"new_invite = MemberInvite(email=email, organization=current_user.organization) db.session.add(new_invite) db.session.commit() invite_link = url_for( \".join\", org_username=current_user.organization.username, token=new_invite.token, _external=True,",
"own account\", \"error\") else: member.disabled_at = datetime.datetime.utcnow() db.session.commit() flash(\"Member account has been disabled\",",
"organization=current_user.organization) db.session.add(new_invite) db.session.commit() invite_link = url_for( \".join\", org_username=current_user.organization.username, token=new_invite.token, _external=True, ) msg =",
"account is already enabled\", \"error\") elif member == current_user: flash(\"You can not enable",
"= url_for(\".index\", org_username=current_user.organization.username) return redirect(redirect_url) @members.route(\"/enable/\", methods=[\"POST\"]) @login_required def enable_account(org_username): member_id = request.form.get(\"member_id\")",
"else: db.session.delete(invite) db.session.commit() flash(\"Invite removed successfully\", \"success\") return redirect( url_for( \"members.index\", org_username=current_user.organization.username, )",
"url_for( \"members.index\", org_username=current_user.organization.username, ) ) invite = MemberInvite.query.filter_by( organization=current_user.organization, email=email ).first() if invite:",
"flash(\"Invite already sent.\", \"warning\") return redirect( url_for( \"members.index\", org_username=current_user.organization.username, ) ) new_invite =",
"flash(\"You can not disabled your own account\", \"error\") else: member.disabled_at = datetime.datetime.utcnow() db.session.commit()",
".forms import MemberInviteForm, MemberJoinForm members = Blueprint( \"members\", __name__, subdomain=\"<org_username>\", template_folder=\"templates\" ) @members.route(\"/\")",
"if member_invite.validate_on_submit(): email = member_invite.email.data.lower() member = Member.query.filter_by( email=email, organization=current_user.organization ).first() if member:",
"member = Member.query.filter_by( email=email, organization=current_user.organization ).first() if member: flash(\"Email is already a member\",",
"been sent\", \"success\") return redirect( url_for(\"members.index\", org_username=current_user.organization.username) ) return render_template(\"members/invite.html\", form=member_invite) @members.route(\"/join/<token>\", methods=[\"GET\",",
"invite\", sender=\"<EMAIL>\", recipients=[new_invite.email], ) msg.body = render_template( \"members/invite_mail.txt\", join_link=invite_link, org_name=current_user.organization.name, ) msg.html =",
"\"members/index.html\", all_invites=all_invites, members=members ) @members.route(\"/invite/<invite_id>/remove\", methods=[\"POST\"]) @login_required def remove_invite(org_username, invite_id): invite = MemberInvite.query.filter_by(",
"account is not found\", \"error\") elif member.disabled_at is None: flash(\"Member account is already",
"db.session.commit() login_user(new_member) flash(\"New member invite has been sent\", \"success\") return redirect( url_for(\"dashboard.index\", org_username=invite.organization.username)",
"invite(org_username): member_invite = MemberInviteForm() if member_invite.validate_on_submit(): email = member_invite.email.data.lower() member = Member.query.filter_by( email=email,",
"organization=invite.organization, ) new_member.password = member_join.password.data db.session.add(new_member) db.session.delete(invite) db.session.commit() login_user(new_member) flash(\"New member invite has",
"= datetime.datetime.utcnow() db.session.commit() flash(\"Member account has been disabled\", \"success\") redirect_url = url_for(\".index\", org_username=current_user.organization.username)",
"org_username=current_user.organization.username, ) ) invite = MemberInvite.query.filter_by( organization=current_user.organization, email=email ).first() if invite: flash(\"Invite already",
"= Member( first_name=member_join.first_name.data, last_name=member_join.last_name.data, email=invite.email, organization=invite.organization, ) new_member.password = member_join.password.data db.session.add(new_member) db.session.delete(invite) db.session.commit()",
"= MemberInvite(email=email, organization=current_user.organization) db.session.add(new_invite) db.session.commit() invite_link = url_for( \".join\", org_username=current_user.organization.username, token=new_invite.token, _external=True, )",
"flash, redirect, render_template, request, url_for from flask_login import current_user, login_required, login_user from flask_mail",
"removed successfully\", \"success\") return redirect( url_for( \"members.index\", org_username=current_user.organization.username, ) ) @members.route(\"/invite/\", methods=[\"GET\", \"POST\"])",
"MemberJoinForm members = Blueprint( \"members\", __name__, subdomain=\"<org_username>\", template_folder=\"templates\" ) @members.route(\"/\") @login_required def index(org_username):",
"= Member.query.filter_by( id=member_id, organization=current_user.organization ).first() if member is None: flash(\"Member account is not",
"from flask_mail import Message from .forms import MemberInviteForm, MemberJoinForm members = Blueprint( \"members\",",
"else: member.disabled_at = datetime.datetime.utcnow() db.session.commit() flash(\"Member account has been disabled\", \"success\") redirect_url =",
"db.session.commit() flash(\"Member account has been disabled\", \"success\") redirect_url = url_for(\".index\", org_username=current_user.organization.username) return redirect(redirect_url)",
"import Member, MemberInvite from flask import Blueprint, flash, redirect, render_template, request, url_for from",
"render_template(\"members/invite.html\", form=member_invite) @members.route(\"/join/<token>\", methods=[\"GET\", \"POST\"]) def join(org_username, token): invite = MemberInvite.query.filter_by(token=token).first() if not",
"msg = Message( \"Worktable organization join invite\", sender=\"<EMAIL>\", recipients=[new_invite.email], ) msg.body = render_template(",
"token=token ) @members.route(\"/disable/\", methods=[\"POST\"]) @login_required def disable_account(org_username): member_id = request.form.get(\"member_id\") member = Member.query.filter_by(",
"methods=[\"POST\"]) @login_required def disable_account(org_username): member_id = request.form.get(\"member_id\") member = Member.query.filter_by( id=member_id, organization=current_user.organization ).first()",
"login_user(new_member) flash(\"New member invite has been sent\", \"success\") return redirect( url_for(\"dashboard.index\", org_username=invite.organization.username) )",
"disabled your own account\", \"error\") else: member.disabled_at = datetime.datetime.utcnow() db.session.commit() flash(\"Member account has",
"found\", \"error\") elif member.disabled_at: flash(\"Member account is already disabled\", \"error\") elif member ==",
"mail.send(msg) flash(\"New member invite has been sent\", \"success\") return redirect( url_for(\"members.index\", org_username=current_user.organization.username) )",
"join invite\", sender=\"<EMAIL>\", recipients=[new_invite.email], ) msg.body = render_template( \"members/invite_mail.txt\", join_link=invite_link, org_name=current_user.organization.name, ) msg.html",
"\"warning\") return redirect( url_for( \"members.index\", org_username=current_user.organization.username, ) ) new_invite = MemberInvite(email=email, organization=current_user.organization) db.session.add(new_invite)",
"\"members.index\", org_username=current_user.organization.username, ) ) @members.route(\"/invite/\", methods=[\"GET\", \"POST\"]) @login_required def invite(org_username): member_invite = MemberInviteForm()",
"@members.route(\"/\") @login_required def index(org_username): member_page = request.args.get(\"member_page\", 1) members = Member.query.filter_by(organization=current_user.organization).paginate( int(member_page), 5",
"\"error\") else: db.session.delete(invite) db.session.commit() flash(\"Invite removed successfully\", \"success\") return redirect( url_for( \"members.index\", org_username=current_user.organization.username,",
"db.session.commit() flash(\"Invite removed successfully\", \"success\") return redirect( url_for( \"members.index\", org_username=current_user.organization.username, ) ) @members.route(\"/invite/\",",
"\"success\") return redirect( url_for( \"members.index\", org_username=current_user.organization.username, ) ) @members.route(\"/invite/\", methods=[\"GET\", \"POST\"]) @login_required def",
"methods=[\"POST\"]) @login_required def enable_account(org_username): member_id = request.form.get(\"member_id\") member = Member.query.filter_by( id=member_id, organization=current_user.organization ).first()",
").all() return render_template( \"members/index.html\", all_invites=all_invites, members=members ) @members.route(\"/invite/<invite_id>/remove\", methods=[\"POST\"]) @login_required def remove_invite(org_username, invite_id):",
"\"success\") return redirect( url_for(\"dashboard.index\", org_username=invite.organization.username) ) return render_template( \"members/join.html\", invite=invite, form=member_join, token=token )",
"successfully\", \"success\") return redirect( url_for( \"members.index\", org_username=current_user.organization.username, ) ) @members.route(\"/invite/\", methods=[\"GET\", \"POST\"]) @login_required",
"member\", \"error\") return redirect( url_for( \"members.index\", org_username=current_user.organization.username, ) ) invite = MemberInvite.query.filter_by( organization=current_user.organization,",
"flash(\"Email is already a member\", \"error\") return redirect( url_for( \"members.index\", org_username=current_user.organization.username, ) )",
"member_join = MemberJoinForm() if member_join.validate_on_submit(): new_member = Member( first_name=member_join.first_name.data, last_name=member_join.last_name.data, email=invite.email, organization=invite.organization, )",
"found\", \"error\") elif member.disabled_at is None: flash(\"Member account is already enabled\", \"error\") elif",
"org_name=current_user.organization.name, ) mail.send(msg) flash(\"New member invite has been sent\", \"success\") return redirect( url_for(\"members.index\",",
"already a member\", \"error\") return redirect( url_for( \"members.index\", org_username=current_user.organization.username, ) ) invite =",
"member_invite.email.data.lower() member = Member.query.filter_by( email=email, organization=current_user.organization ).first() if member: flash(\"Email is already a",
"flask_mail import Message from .forms import MemberInviteForm, MemberJoinForm members = Blueprint( \"members\", __name__,",
"is not found\", \"error\") elif member.disabled_at is None: flash(\"Member account is already enabled\",",
").first() if invite is None: flash(\"Unable to find invite to remove\", \"error\") else:",
"= MemberInvite.query.filter_by( organization=current_user.organization, id=invite_id ).first() if invite is None: flash(\"Unable to find invite",
"login_user from flask_mail import Message from .forms import MemberInviteForm, MemberJoinForm members = Blueprint(",
"= Member.query.filter_by(organization=current_user.organization).paginate( int(member_page), 5 ) all_invites = MemberInvite.query.filter_by( organization=current_user.organization ).all() return render_template( \"members/index.html\",",
"been disabled\", \"success\") redirect_url = url_for(\".index\", org_username=current_user.organization.username) return redirect(redirect_url) @members.route(\"/enable/\", methods=[\"POST\"]) @login_required def",
"member_page = request.args.get(\"member_page\", 1) members = Member.query.filter_by(organization=current_user.organization).paginate( int(member_page), 5 ) all_invites = MemberInvite.query.filter_by(",
"@login_required def enable_account(org_username): member_id = request.form.get(\"member_id\") member = Member.query.filter_by( id=member_id, organization=current_user.organization ).first() if",
"flash(\"New member invite has been sent\", \"success\") return redirect( url_for(\"members.index\", org_username=current_user.organization.username) ) return",
"import current_user, login_required, login_user from flask_mail import Message from .forms import MemberInviteForm, MemberJoinForm",
"\"error\") else: member.disabled_at = None db.session.commit() flash(\"Member account has been enabled\", \"success\") redirect_url",
"member invite has been sent\", \"success\") return redirect( url_for(\"members.index\", org_username=current_user.organization.username) ) return render_template(\"members/invite.html\",",
"Member.query.filter_by( email=email, organization=current_user.organization ).first() if member: flash(\"Email is already a member\", \"error\") return",
"None: flash(\"Member account is already enabled\", \"error\") elif member == current_user: flash(\"You can",
"is already disabled\", \"error\") elif member == current_user: flash(\"You can not disabled your",
"flask import Blueprint, flash, redirect, render_template, request, url_for from flask_login import current_user, login_required,",
"redirect( url_for( \"members.index\", org_username=current_user.organization.username, ) ) new_invite = MemberInvite(email=email, organization=current_user.organization) db.session.add(new_invite) db.session.commit() invite_link",
"enable_account(org_username): member_id = request.form.get(\"member_id\") member = Member.query.filter_by( id=member_id, organization=current_user.organization ).first() if member is",
") all_invites = MemberInvite.query.filter_by( organization=current_user.organization ).all() return render_template( \"members/index.html\", all_invites=all_invites, members=members ) @members.route(\"/invite/<invite_id>/remove\",",
"Member, MemberInvite from flask import Blueprint, flash, redirect, render_template, request, url_for from flask_login",
"member_id = request.form.get(\"member_id\") member = Member.query.filter_by( id=member_id, organization=current_user.organization ).first() if member is None:",
"invite is None: flash(\"Unable to find invite to remove\", \"error\") else: db.session.delete(invite) db.session.commit()",
").first() if member: flash(\"Email is already a member\", \"error\") return redirect( url_for( \"members.index\",",
"already sent.\", \"warning\") return redirect( url_for( \"members.index\", org_username=current_user.organization.username, ) ) new_invite = MemberInvite(email=email,",
"member = Member.query.filter_by( id=member_id, organization=current_user.organization ).first() if member is None: flash(\"Member account is",
"return render_template(\"members/invite.html\", form=member_invite) @members.route(\"/join/<token>\", methods=[\"GET\", \"POST\"]) def join(org_username, token): invite = MemberInvite.query.filter_by(token=token).first() if",
"return render_template( \"members/index.html\", all_invites=all_invites, members=members ) @members.route(\"/invite/<invite_id>/remove\", methods=[\"POST\"]) @login_required def remove_invite(org_username, invite_id): invite",
"join_link=invite_link, org_name=current_user.organization.name, ) mail.send(msg) flash(\"New member invite has been sent\", \"success\") return redirect(",
"join(org_username, token): invite = MemberInvite.query.filter_by(token=token).first() if not invite: flash(\"Invalid invite link\", \"error\") return",
") new_invite = MemberInvite(email=email, organization=current_user.organization) db.session.add(new_invite) db.session.commit() invite_link = url_for( \".join\", org_username=current_user.organization.username, token=new_invite.token,",
"app.models import Member, MemberInvite from flask import Blueprint, flash, redirect, render_template, request, url_for",
"elif member == current_user: flash(\"You can not enable your own account\", \"error\") else:",
"from app import db, mail from app.models import Member, MemberInvite from flask import",
"is already a member\", \"error\") return redirect( url_for( \"members.index\", org_username=current_user.organization.username, ) ) invite",
"enabled\", \"error\") elif member == current_user: flash(\"You can not enable your own account\",",
"\".join\", org_username=current_user.organization.username, token=new_invite.token, _external=True, ) msg = Message( \"Worktable organization join invite\", sender=\"<EMAIL>\",",
"@login_required def disable_account(org_username): member_id = request.form.get(\"member_id\") member = Member.query.filter_by( id=member_id, organization=current_user.organization ).first() if",
"Blueprint( \"members\", __name__, subdomain=\"<org_username>\", template_folder=\"templates\" ) @members.route(\"/\") @login_required def index(org_username): member_page = request.args.get(\"member_page\",",
"not invite: flash(\"Invalid invite link\", \"error\") return redirect(url_for(\"auth.login\", org_username=org_username)) member_join = MemberJoinForm() if"
] |
[
"..modules.particleFlowRecHitECAL_cfi import * from ..tasks.particleFlowClusterECALTask_cfi import * pfClusteringECALTask = cms.Task( particleFlowClusterECALTask, particleFlowClusterECALUncorrected, particleFlowRecHitECAL",
"import * from ..tasks.particleFlowClusterECALTask_cfi import * pfClusteringECALTask = cms.Task( particleFlowClusterECALTask, particleFlowClusterECALUncorrected, particleFlowRecHitECAL )",
"from ..modules.particleFlowRecHitECAL_cfi import * from ..tasks.particleFlowClusterECALTask_cfi import * pfClusteringECALTask = cms.Task( particleFlowClusterECALTask, particleFlowClusterECALUncorrected,",
"..modules.particleFlowClusterECALUncorrected_cfi import * from ..modules.particleFlowRecHitECAL_cfi import * from ..tasks.particleFlowClusterECALTask_cfi import * pfClusteringECALTask =",
"* from ..modules.particleFlowRecHitECAL_cfi import * from ..tasks.particleFlowClusterECALTask_cfi import * pfClusteringECALTask = cms.Task( particleFlowClusterECALTask,",
"<reponame>PKUfudawei/cmssw import FWCore.ParameterSet.Config as cms from ..modules.particleFlowClusterECALUncorrected_cfi import * from ..modules.particleFlowRecHitECAL_cfi import *",
"cms from ..modules.particleFlowClusterECALUncorrected_cfi import * from ..modules.particleFlowRecHitECAL_cfi import * from ..tasks.particleFlowClusterECALTask_cfi import *",
"from ..modules.particleFlowClusterECALUncorrected_cfi import * from ..modules.particleFlowRecHitECAL_cfi import * from ..tasks.particleFlowClusterECALTask_cfi import * pfClusteringECALTask",
"as cms from ..modules.particleFlowClusterECALUncorrected_cfi import * from ..modules.particleFlowRecHitECAL_cfi import * from ..tasks.particleFlowClusterECALTask_cfi import",
"import FWCore.ParameterSet.Config as cms from ..modules.particleFlowClusterECALUncorrected_cfi import * from ..modules.particleFlowRecHitECAL_cfi import * from",
"FWCore.ParameterSet.Config as cms from ..modules.particleFlowClusterECALUncorrected_cfi import * from ..modules.particleFlowRecHitECAL_cfi import * from ..tasks.particleFlowClusterECALTask_cfi",
"import * from ..modules.particleFlowRecHitECAL_cfi import * from ..tasks.particleFlowClusterECALTask_cfi import * pfClusteringECALTask = cms.Task("
] |
[
"# # Licensed under the Apache License, Version 2.0 (the \"License\"); # you",
"writing, software # distributed under the License is distributed on an \"AS IS\"",
"(i.e normally once in every x hours) if isinstance(window, beam.transforms.window.GlobalWindow): logging.info( f\"(Re)loading side",
"data from basepath {element.decode()} for window: {util.get_formatted_time(window.start)} - {util.get_formatted_time(window.end)}\" ) for sideinput_type in",
"process (i.e normally once in every x hours) if isinstance(window, beam.transforms.window.GlobalWindow): logging.info( f\"(Re)loading",
"KIND, either express or implied. # See the License for the specific language",
"Unless required by applicable law or agreed to in writing, software # distributed",
"You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 #",
"the License is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR",
"# See the License for the specific language governing permissions and # limitations",
"side input refresh frequency Attributes: sideinput_types: List of Side input types file_prefix: file_prefix",
"of side input refresh process. Statement will be logged only whenever the pubsub",
"from basepath {element.decode()} for window: {util.get_formatted_time(window.start)} - {util.get_formatted_time(window.end)}\" ) for sideinput_type in self.sideinput_types:",
"License. # You may obtain a copy of the License at # #",
"refresh process (i.e normally once in every x hours) if isinstance(window, beam.transforms.window.GlobalWindow): logging.info(",
"is * indicating all files \"\"\" def __init__(self, sideinput_types: List[str], file_prefix: str =",
"logging.info( f\"(Re)loading side input data from basepath {element.decode()} for window: {util.get_formatted_time(window.start)} - {util.get_formatted_time(window.end)}\"",
"language governing permissions and # limitations under the License. import logging from typing",
"audit triggering of side input refresh process. Statement will be logged only whenever",
"law or agreed to in writing, software # distributed under the License is",
"the License. import logging from typing import List import apache_beam as beam from",
"the License for the specific language governing permissions and # limitations under the",
"specific language governing permissions and # limitations under the License. import logging from",
"x hours matching the side input refresh frequency Attributes: sideinput_types: List of Side",
"compliance with the License. # You may obtain a copy of the License",
"data from basepath {element.decode()} for global window: {timestamp} - {window}\" ) else: logging.info(",
"def __init__(self, sideinput_types: List[str], file_prefix: str = \"*\"): self.sideinput_types = sideinput_types self.file_prefix =",
"on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,",
"this file except in compliance with the License. # You may obtain a",
"matching required files. Default is * indicating all files \"\"\" def __init__(self, sideinput_types:",
"for window: {util.get_formatted_time(window.start)} - {util.get_formatted_time(window.end)}\" ) for sideinput_type in self.sideinput_types: yield beam.pvalue.TaggedOutput( sideinput_type,",
"input refresh process (i.e normally once in every x hours) if isinstance(window, beam.transforms.window.GlobalWindow):",
"side input type combining root path received via file notification subscription and side",
"the Apache License, Version 2.0 (the \"License\"); # you may not use this",
"path for each side input type combining root path received via file notification",
"path and will be fired once every x hours matching the side input",
"List of Side input types file_prefix: file_prefix matching required files. Default is *",
"Side input types file_prefix: file_prefix matching required files. Default is * indicating all",
"you may not use this file except in compliance with the License. #",
"for the specific language governing permissions and # limitations under the License. import",
"Attributes: sideinput_types: List of Side input types file_prefix: file_prefix matching required files. Default",
"triggering of side input refresh process. Statement will be logged only whenever the",
"only whenever the pubsub notification # triggers side input refresh process (i.e normally",
"once every x hours matching the side input refresh frequency Attributes: sideinput_types: List",
"apache_beam.io.filesystems import FileSystems from sideinput_refresh import util @beam.typehints.with_input_types(bytes) @beam.typehints.with_output_types(beam.pvalue.TaggedOutput) class SplitToMultiple(beam.DoFn): \"\"\"Generates a",
"of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable",
"matching the side input refresh frequency Attributes: sideinput_types: List of Side input types",
"file_prefix: file_prefix matching required files. Default is * indicating all files \"\"\" def",
"base path for each side input type combining root path received via file",
"# triggers side input refresh process (i.e normally once in every x hours)",
"process. Statement will be logged only whenever the pubsub notification # triggers side",
"element, timestamp=beam.DoFn.TimestampParam, window=beam.DoFn.WindowParam, pane_info=beam.DoFn.PaneInfoParam): # Logging to audit triggering of side input refresh",
"ANY KIND, either express or implied. # See the License for the specific",
"received via file notification subscription and side input type. PCollection recieved will contain",
"side input refresh process (i.e normally once in every x hours) if isinstance(window,",
"import FileSystems from sideinput_refresh import util @beam.typehints.with_input_types(bytes) @beam.typehints.with_output_types(beam.pvalue.TaggedOutput) class SplitToMultiple(beam.DoFn): \"\"\"Generates a base",
"in compliance with the License. # You may obtain a copy of the",
"util @beam.typehints.with_input_types(bytes) @beam.typehints.with_output_types(beam.pvalue.TaggedOutput) class SplitToMultiple(beam.DoFn): \"\"\"Generates a base path for each side input",
"single element representing base path and will be fired once every x hours",
"License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or",
"window=beam.DoFn.WindowParam, pane_info=beam.DoFn.PaneInfoParam): # Logging to audit triggering of side input refresh process. Statement",
"Statement will be logged only whenever the pubsub notification # triggers side input",
"in every x hours) if isinstance(window, beam.transforms.window.GlobalWindow): logging.info( f\"(Re)loading side input data from",
"Logging to audit triggering of side input refresh process. Statement will be logged",
"# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. #",
"for global window: {timestamp} - {window}\" ) else: logging.info( f\"(Re)loading side input data",
"else: logging.info( f\"(Re)loading side input data from basepath {element.decode()} for window: {util.get_formatted_time(window.start)} -",
"use this file except in compliance with the License. # You may obtain",
"notification subscription and side input type. PCollection recieved will contain only single element",
"at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed",
"representing base path and will be fired once every x hours matching the",
"str = \"*\"): self.sideinput_types = sideinput_types self.file_prefix = file_prefix def process(self, element, timestamp=beam.DoFn.TimestampParam,",
"once in every x hours) if isinstance(window, beam.transforms.window.GlobalWindow): logging.info( f\"(Re)loading side input data",
"hours) if isinstance(window, beam.transforms.window.GlobalWindow): logging.info( f\"(Re)loading side input data from basepath {element.decode()} for",
"not use this file except in compliance with the License. # You may",
"from sideinput_refresh import util @beam.typehints.with_input_types(bytes) @beam.typehints.with_output_types(beam.pvalue.TaggedOutput) class SplitToMultiple(beam.DoFn): \"\"\"Generates a base path for",
"normally once in every x hours) if isinstance(window, beam.transforms.window.GlobalWindow): logging.info( f\"(Re)loading side input",
"WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See",
"{window}\" ) else: logging.info( f\"(Re)loading side input data from basepath {element.decode()} for window:",
"required files. Default is * indicating all files \"\"\" def __init__(self, sideinput_types: List[str],",
"See the License for the specific language governing permissions and # limitations under",
"for each side input type combining root path received via file notification subscription",
"all files \"\"\" def __init__(self, sideinput_types: List[str], file_prefix: str = \"*\"): self.sideinput_types =",
"Copyright 2020 Google Inc. # # Licensed under the Apache License, Version 2.0",
"BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.",
"- {window}\" ) else: logging.info( f\"(Re)loading side input data from basepath {element.decode()} for",
"{util.get_formatted_time(window.start)} - {util.get_formatted_time(window.end)}\" ) for sideinput_type in self.sideinput_types: yield beam.pvalue.TaggedOutput( sideinput_type, FileSystems.join(element.decode(), sideinput_type,",
"License, Version 2.0 (the \"License\"); # you may not use this file except",
"# Licensed under the Apache License, Version 2.0 (the \"License\"); # you may",
"type. PCollection recieved will contain only single element representing base path and will",
"refresh frequency Attributes: sideinput_types: List of Side input types file_prefix: file_prefix matching required",
"IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or",
"and # limitations under the License. import logging from typing import List import",
"files. Default is * indicating all files \"\"\" def __init__(self, sideinput_types: List[str], file_prefix:",
"a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required",
"= sideinput_types self.file_prefix = file_prefix def process(self, element, timestamp=beam.DoFn.TimestampParam, window=beam.DoFn.WindowParam, pane_info=beam.DoFn.PaneInfoParam): # Logging",
"Default is * indicating all files \"\"\" def __init__(self, sideinput_types: List[str], file_prefix: str",
"{timestamp} - {window}\" ) else: logging.info( f\"(Re)loading side input data from basepath {element.decode()}",
"f\"(Re)loading side input data from basepath {element.decode()} for global window: {timestamp} - {window}\"",
"distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY",
"beam from apache_beam.io.filesystems import FileSystems from sideinput_refresh import util @beam.typehints.with_input_types(bytes) @beam.typehints.with_output_types(beam.pvalue.TaggedOutput) class SplitToMultiple(beam.DoFn):",
"fired once every x hours matching the side input refresh frequency Attributes: sideinput_types:",
"# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in",
"SplitToMultiple(beam.DoFn): \"\"\"Generates a base path for each side input type combining root path",
"pane_info=beam.DoFn.PaneInfoParam): # Logging to audit triggering of side input refresh process. Statement will",
"Google Inc. # # Licensed under the Apache License, Version 2.0 (the \"License\");",
"PCollection recieved will contain only single element representing base path and will be",
"apache_beam as beam from apache_beam.io.filesystems import FileSystems from sideinput_refresh import util @beam.typehints.with_input_types(bytes) @beam.typehints.with_output_types(beam.pvalue.TaggedOutput)",
"type combining root path received via file notification subscription and side input type.",
"OF ANY KIND, either express or implied. # See the License for the",
"pubsub notification # triggers side input refresh process (i.e normally once in every",
"window: {timestamp} - {window}\" ) else: logging.info( f\"(Re)loading side input data from basepath",
"2.0 (the \"License\"); # you may not use this file except in compliance",
"self.file_prefix = file_prefix def process(self, element, timestamp=beam.DoFn.TimestampParam, window=beam.DoFn.WindowParam, pane_info=beam.DoFn.PaneInfoParam): # Logging to audit",
"# you may not use this file except in compliance with the License.",
"frequency Attributes: sideinput_types: List of Side input types file_prefix: file_prefix matching required files.",
"agreed to in writing, software # distributed under the License is distributed on",
"be logged only whenever the pubsub notification # triggers side input refresh process",
"FileSystems from sideinput_refresh import util @beam.typehints.with_input_types(bytes) @beam.typehints.with_output_types(beam.pvalue.TaggedOutput) class SplitToMultiple(beam.DoFn): \"\"\"Generates a base path",
"@beam.typehints.with_input_types(bytes) @beam.typehints.with_output_types(beam.pvalue.TaggedOutput) class SplitToMultiple(beam.DoFn): \"\"\"Generates a base path for each side input type",
"\"\"\"Generates a base path for each side input type combining root path received",
"permissions and # limitations under the License. import logging from typing import List",
"WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the",
"side input data from basepath {element.decode()} for global window: {timestamp} - {window}\" )",
"x hours) if isinstance(window, beam.transforms.window.GlobalWindow): logging.info( f\"(Re)loading side input data from basepath {element.decode()}",
"subscription and side input type. PCollection recieved will contain only single element representing",
"governing permissions and # limitations under the License. import logging from typing import",
"(the \"License\"); # you may not use this file except in compliance with",
"input data from basepath {element.decode()} for window: {util.get_formatted_time(window.start)} - {util.get_formatted_time(window.end)}\" ) for sideinput_type",
"import util @beam.typehints.with_input_types(bytes) @beam.typehints.with_output_types(beam.pvalue.TaggedOutput) class SplitToMultiple(beam.DoFn): \"\"\"Generates a base path for each side",
"every x hours) if isinstance(window, beam.transforms.window.GlobalWindow): logging.info( f\"(Re)loading side input data from basepath",
"typing import List import apache_beam as beam from apache_beam.io.filesystems import FileSystems from sideinput_refresh",
"# # Unless required by applicable law or agreed to in writing, software",
"and side input type. PCollection recieved will contain only single element representing base",
"- {util.get_formatted_time(window.end)}\" ) for sideinput_type in self.sideinput_types: yield beam.pvalue.TaggedOutput( sideinput_type, FileSystems.join(element.decode(), sideinput_type, self.file_prefix))",
"express or implied. # See the License for the specific language governing permissions",
"import List import apache_beam as beam from apache_beam.io.filesystems import FileSystems from sideinput_refresh import",
"Version 2.0 (the \"License\"); # you may not use this file except in",
"# Unless required by applicable law or agreed to in writing, software #",
"file_prefix def process(self, element, timestamp=beam.DoFn.TimestampParam, window=beam.DoFn.WindowParam, pane_info=beam.DoFn.PaneInfoParam): # Logging to audit triggering of",
"except in compliance with the License. # You may obtain a copy of",
"input type combining root path received via file notification subscription and side input",
"the pubsub notification # triggers side input refresh process (i.e normally once in",
"by applicable law or agreed to in writing, software # distributed under the",
") else: logging.info( f\"(Re)loading side input data from basepath {element.decode()} for window: {util.get_formatted_time(window.start)}",
"timestamp=beam.DoFn.TimestampParam, window=beam.DoFn.WindowParam, pane_info=beam.DoFn.PaneInfoParam): # Logging to audit triggering of side input refresh process.",
"from apache_beam.io.filesystems import FileSystems from sideinput_refresh import util @beam.typehints.with_input_types(bytes) @beam.typehints.with_output_types(beam.pvalue.TaggedOutput) class SplitToMultiple(beam.DoFn): \"\"\"Generates",
"via file notification subscription and side input type. PCollection recieved will contain only",
"file notification subscription and side input type. PCollection recieved will contain only single",
"copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by",
"side input type. PCollection recieved will contain only single element representing base path",
"every x hours matching the side input refresh frequency Attributes: sideinput_types: List of",
"either express or implied. # See the License for the specific language governing",
"refresh process. Statement will be logged only whenever the pubsub notification # triggers",
"recieved will contain only single element representing base path and will be fired",
"2020 Google Inc. # # Licensed under the Apache License, Version 2.0 (the",
"software # distributed under the License is distributed on an \"AS IS\" BASIS,",
"Inc. # # Licensed under the Apache License, Version 2.0 (the \"License\"); #",
"# You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0",
"may not use this file except in compliance with the License. # You",
"License is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS",
"\"*\"): self.sideinput_types = sideinput_types self.file_prefix = file_prefix def process(self, element, timestamp=beam.DoFn.TimestampParam, window=beam.DoFn.WindowParam, pane_info=beam.DoFn.PaneInfoParam):",
"file_prefix: str = \"*\"): self.sideinput_types = sideinput_types self.file_prefix = file_prefix def process(self, element,",
"from typing import List import apache_beam as beam from apache_beam.io.filesystems import FileSystems from",
"input types file_prefix: file_prefix matching required files. Default is * indicating all files",
"sideinput_refresh import util @beam.typehints.with_input_types(bytes) @beam.typehints.with_output_types(beam.pvalue.TaggedOutput) class SplitToMultiple(beam.DoFn): \"\"\"Generates a base path for each",
"as beam from apache_beam.io.filesystems import FileSystems from sideinput_refresh import util @beam.typehints.with_input_types(bytes) @beam.typehints.with_output_types(beam.pvalue.TaggedOutput) class",
"sideinput_types self.file_prefix = file_prefix def process(self, element, timestamp=beam.DoFn.TimestampParam, window=beam.DoFn.WindowParam, pane_info=beam.DoFn.PaneInfoParam): # Logging to",
"Licensed under the Apache License, Version 2.0 (the \"License\"); # you may not",
"an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either",
"# # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to",
"= \"*\"): self.sideinput_types = sideinput_types self.file_prefix = file_prefix def process(self, element, timestamp=beam.DoFn.TimestampParam, window=beam.DoFn.WindowParam,",
"self.sideinput_types = sideinput_types self.file_prefix = file_prefix def process(self, element, timestamp=beam.DoFn.TimestampParam, window=beam.DoFn.WindowParam, pane_info=beam.DoFn.PaneInfoParam): #",
"will contain only single element representing base path and will be fired once",
"file except in compliance with the License. # You may obtain a copy",
"# limitations under the License. import logging from typing import List import apache_beam",
"isinstance(window, beam.transforms.window.GlobalWindow): logging.info( f\"(Re)loading side input data from basepath {element.decode()} for global window:",
"__init__(self, sideinput_types: List[str], file_prefix: str = \"*\"): self.sideinput_types = sideinput_types self.file_prefix = file_prefix",
"* indicating all files \"\"\" def __init__(self, sideinput_types: List[str], file_prefix: str = \"*\"):",
"beam.transforms.window.GlobalWindow): logging.info( f\"(Re)loading side input data from basepath {element.decode()} for global window: {timestamp}",
"logging.info( f\"(Re)loading side input data from basepath {element.decode()} for global window: {timestamp} -",
"contain only single element representing base path and will be fired once every",
"under the License is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES",
"logging from typing import List import apache_beam as beam from apache_beam.io.filesystems import FileSystems",
"sideinput_types: List[str], file_prefix: str = \"*\"): self.sideinput_types = sideinput_types self.file_prefix = file_prefix def",
"basepath {element.decode()} for global window: {timestamp} - {window}\" ) else: logging.info( f\"(Re)loading side",
"License for the specific language governing permissions and # limitations under the License.",
"hours matching the side input refresh frequency Attributes: sideinput_types: List of Side input",
"the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law",
"input refresh frequency Attributes: sideinput_types: List of Side input types file_prefix: file_prefix matching",
"# Copyright 2020 Google Inc. # # Licensed under the Apache License, Version",
"List[str], file_prefix: str = \"*\"): self.sideinput_types = sideinput_types self.file_prefix = file_prefix def process(self,",
"will be logged only whenever the pubsub notification # triggers side input refresh",
"logged only whenever the pubsub notification # triggers side input refresh process (i.e",
"basepath {element.decode()} for window: {util.get_formatted_time(window.start)} - {util.get_formatted_time(window.end)}\" ) for sideinput_type in self.sideinput_types: yield",
"the License. # You may obtain a copy of the License at #",
"import apache_beam as beam from apache_beam.io.filesystems import FileSystems from sideinput_refresh import util @beam.typehints.with_input_types(bytes)",
"to audit triggering of side input refresh process. Statement will be logged only",
"element representing base path and will be fired once every x hours matching",
"# Logging to audit triggering of side input refresh process. Statement will be",
"types file_prefix: file_prefix matching required files. Default is * indicating all files \"\"\"",
"to in writing, software # distributed under the License is distributed on an",
"import logging from typing import List import apache_beam as beam from apache_beam.io.filesystems import",
"\"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express",
"def process(self, element, timestamp=beam.DoFn.TimestampParam, window=beam.DoFn.WindowParam, pane_info=beam.DoFn.PaneInfoParam): # Logging to audit triggering of side",
"whenever the pubsub notification # triggers side input refresh process (i.e normally once",
"License. import logging from typing import List import apache_beam as beam from apache_beam.io.filesystems",
"class SplitToMultiple(beam.DoFn): \"\"\"Generates a base path for each side input type combining root",
"from basepath {element.decode()} for global window: {timestamp} - {window}\" ) else: logging.info( f\"(Re)loading",
"f\"(Re)loading side input data from basepath {element.decode()} for window: {util.get_formatted_time(window.start)} - {util.get_formatted_time(window.end)}\" )",
"# distributed under the License is distributed on an \"AS IS\" BASIS, #",
"@beam.typehints.with_output_types(beam.pvalue.TaggedOutput) class SplitToMultiple(beam.DoFn): \"\"\"Generates a base path for each side input type combining",
"implied. # See the License for the specific language governing permissions and #",
"limitations under the License. import logging from typing import List import apache_beam as",
"be fired once every x hours matching the side input refresh frequency Attributes:",
"input data from basepath {element.decode()} for global window: {timestamp} - {window}\" ) else:",
"\"License\"); # you may not use this file except in compliance with the",
"window: {util.get_formatted_time(window.start)} - {util.get_formatted_time(window.end)}\" ) for sideinput_type in self.sideinput_types: yield beam.pvalue.TaggedOutput( sideinput_type, FileSystems.join(element.decode(),",
"is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF",
"obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless",
"root path received via file notification subscription and side input type. PCollection recieved",
"required by applicable law or agreed to in writing, software # distributed under",
"input type. PCollection recieved will contain only single element representing base path and",
"file_prefix matching required files. Default is * indicating all files \"\"\" def __init__(self,",
"List import apache_beam as beam from apache_beam.io.filesystems import FileSystems from sideinput_refresh import util",
"if isinstance(window, beam.transforms.window.GlobalWindow): logging.info( f\"(Re)loading side input data from basepath {element.decode()} for global",
"applicable law or agreed to in writing, software # distributed under the License",
"a base path for each side input type combining root path received via",
"notification # triggers side input refresh process (i.e normally once in every x",
"will be fired once every x hours matching the side input refresh frequency",
"= file_prefix def process(self, element, timestamp=beam.DoFn.TimestampParam, window=beam.DoFn.WindowParam, pane_info=beam.DoFn.PaneInfoParam): # Logging to audit triggering",
"process(self, element, timestamp=beam.DoFn.TimestampParam, window=beam.DoFn.WindowParam, pane_info=beam.DoFn.PaneInfoParam): # Logging to audit triggering of side input",
"of Side input types file_prefix: file_prefix matching required files. Default is * indicating",
"\"\"\" def __init__(self, sideinput_types: List[str], file_prefix: str = \"*\"): self.sideinput_types = sideinput_types self.file_prefix",
"only single element representing base path and will be fired once every x",
"or agreed to in writing, software # distributed under the License is distributed",
"sideinput_types: List of Side input types file_prefix: file_prefix matching required files. Default is",
"or implied. # See the License for the specific language governing permissions and",
"and will be fired once every x hours matching the side input refresh",
"global window: {timestamp} - {window}\" ) else: logging.info( f\"(Re)loading side input data from",
"under the License. import logging from typing import List import apache_beam as beam",
"the side input refresh frequency Attributes: sideinput_types: List of Side input types file_prefix:",
"{element.decode()} for window: {util.get_formatted_time(window.start)} - {util.get_formatted_time(window.end)}\" ) for sideinput_type in self.sideinput_types: yield beam.pvalue.TaggedOutput(",
"side input data from basepath {element.decode()} for window: {util.get_formatted_time(window.start)} - {util.get_formatted_time(window.end)}\" ) for",
"files \"\"\" def __init__(self, sideinput_types: List[str], file_prefix: str = \"*\"): self.sideinput_types = sideinput_types",
"distributed under the License is distributed on an \"AS IS\" BASIS, # WITHOUT",
"CONDITIONS OF ANY KIND, either express or implied. # See the License for",
"Apache License, Version 2.0 (the \"License\"); # you may not use this file",
"OR CONDITIONS OF ANY KIND, either express or implied. # See the License",
"may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # #",
"indicating all files \"\"\" def __init__(self, sideinput_types: List[str], file_prefix: str = \"*\"): self.sideinput_types",
"triggers side input refresh process (i.e normally once in every x hours) if",
"input refresh process. Statement will be logged only whenever the pubsub notification #",
"each side input type combining root path received via file notification subscription and",
"with the License. # You may obtain a copy of the License at",
"the specific language governing permissions and # limitations under the License. import logging",
"{element.decode()} for global window: {timestamp} - {window}\" ) else: logging.info( f\"(Re)loading side input",
"side input refresh process. Statement will be logged only whenever the pubsub notification",
"http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing,",
"path received via file notification subscription and side input type. PCollection recieved will",
"in writing, software # distributed under the License is distributed on an \"AS",
"combining root path received via file notification subscription and side input type. PCollection",
"base path and will be fired once every x hours matching the side",
"under the Apache License, Version 2.0 (the \"License\"); # you may not use"
] |
[
"from rest_framework.decorators import action from rest_framework.permissions import IsAdminUser from .models import SendGridMail from",
".models import SendGridMail from .serializers import SendGridMailSerializer class MailViewSet(ModelViewSet): queryset = SendGridMail.objects.all() serializer_class",
"from .models import SendGridMail from .serializers import SendGridMailSerializer class MailViewSet(ModelViewSet): queryset = SendGridMail.objects.all()",
"from rest_framework.permissions import IsAdminUser from .models import SendGridMail from .serializers import SendGridMailSerializer class",
"django.shortcuts import redirect from django.urls import reverse from rest_framework.viewsets import ModelViewSet from rest_framework.decorators",
"from django.urls import reverse from rest_framework.viewsets import ModelViewSet from rest_framework.decorators import action from",
"SendGridMail from .serializers import SendGridMailSerializer class MailViewSet(ModelViewSet): queryset = SendGridMail.objects.all() serializer_class = SendGridMailSerializer",
"MailViewSet(ModelViewSet): queryset = SendGridMail.objects.all() serializer_class = SendGridMailSerializer permission_classes = [IsAdminUser] http_method_names = ['get',",
"permission_classes = [IsAdminUser] http_method_names = ['get', 'post', 'retrieve'] @action(methods=['GET'], detail=True) def resend(self, request,",
"[IsAdminUser] http_method_names = ['get', 'post', 'retrieve'] @action(methods=['GET'], detail=True) def resend(self, request, pk=None): mail",
"queryset = SendGridMail.objects.all() serializer_class = SendGridMailSerializer permission_classes = [IsAdminUser] http_method_names = ['get', 'post',",
"import ModelViewSet from rest_framework.decorators import action from rest_framework.permissions import IsAdminUser from .models import",
"serializer_class = SendGridMailSerializer permission_classes = [IsAdminUser] http_method_names = ['get', 'post', 'retrieve'] @action(methods=['GET'], detail=True)",
"SendGridMail.objects.all() serializer_class = SendGridMailSerializer permission_classes = [IsAdminUser] http_method_names = ['get', 'post', 'retrieve'] @action(methods=['GET'],",
"import IsAdminUser from .models import SendGridMail from .serializers import SendGridMailSerializer class MailViewSet(ModelViewSet): queryset",
"SendGridMailSerializer permission_classes = [IsAdminUser] http_method_names = ['get', 'post', 'retrieve'] @action(methods=['GET'], detail=True) def resend(self,",
"rest_framework.permissions import IsAdminUser from .models import SendGridMail from .serializers import SendGridMailSerializer class MailViewSet(ModelViewSet):",
"SendGridMailSerializer class MailViewSet(ModelViewSet): queryset = SendGridMail.objects.all() serializer_class = SendGridMailSerializer permission_classes = [IsAdminUser] http_method_names",
"import redirect from django.urls import reverse from rest_framework.viewsets import ModelViewSet from rest_framework.decorators import",
"redirect from django.urls import reverse from rest_framework.viewsets import ModelViewSet from rest_framework.decorators import action",
"['get', 'post', 'retrieve'] @action(methods=['GET'], detail=True) def resend(self, request, pk=None): mail = SendGridMail.objects.get(id=pk) mail.send()",
"@action(methods=['GET'], detail=True) def resend(self, request, pk=None): mail = SendGridMail.objects.get(id=pk) mail.send() return redirect(reverse(\"admin:cases_case_change\", args=(mail.case.id,)))",
"action from rest_framework.permissions import IsAdminUser from .models import SendGridMail from .serializers import SendGridMailSerializer",
"class MailViewSet(ModelViewSet): queryset = SendGridMail.objects.all() serializer_class = SendGridMailSerializer permission_classes = [IsAdminUser] http_method_names =",
"import SendGridMail from .serializers import SendGridMailSerializer class MailViewSet(ModelViewSet): queryset = SendGridMail.objects.all() serializer_class =",
"rest_framework.decorators import action from rest_framework.permissions import IsAdminUser from .models import SendGridMail from .serializers",
"IsAdminUser from .models import SendGridMail from .serializers import SendGridMailSerializer class MailViewSet(ModelViewSet): queryset =",
"from .serializers import SendGridMailSerializer class MailViewSet(ModelViewSet): queryset = SendGridMail.objects.all() serializer_class = SendGridMailSerializer permission_classes",
"= [IsAdminUser] http_method_names = ['get', 'post', 'retrieve'] @action(methods=['GET'], detail=True) def resend(self, request, pk=None):",
"import action from rest_framework.permissions import IsAdminUser from .models import SendGridMail from .serializers import",
".serializers import SendGridMailSerializer class MailViewSet(ModelViewSet): queryset = SendGridMail.objects.all() serializer_class = SendGridMailSerializer permission_classes =",
"reverse from rest_framework.viewsets import ModelViewSet from rest_framework.decorators import action from rest_framework.permissions import IsAdminUser",
"from rest_framework.viewsets import ModelViewSet from rest_framework.decorators import action from rest_framework.permissions import IsAdminUser from",
"= SendGridMailSerializer permission_classes = [IsAdminUser] http_method_names = ['get', 'post', 'retrieve'] @action(methods=['GET'], detail=True) def",
"'retrieve'] @action(methods=['GET'], detail=True) def resend(self, request, pk=None): mail = SendGridMail.objects.get(id=pk) mail.send() return redirect(reverse(\"admin:cases_case_change\",",
"from django.shortcuts import redirect from django.urls import reverse from rest_framework.viewsets import ModelViewSet from",
"import SendGridMailSerializer class MailViewSet(ModelViewSet): queryset = SendGridMail.objects.all() serializer_class = SendGridMailSerializer permission_classes = [IsAdminUser]",
"= ['get', 'post', 'retrieve'] @action(methods=['GET'], detail=True) def resend(self, request, pk=None): mail = SendGridMail.objects.get(id=pk)",
"django.urls import reverse from rest_framework.viewsets import ModelViewSet from rest_framework.decorators import action from rest_framework.permissions",
"'post', 'retrieve'] @action(methods=['GET'], detail=True) def resend(self, request, pk=None): mail = SendGridMail.objects.get(id=pk) mail.send() return",
"ModelViewSet from rest_framework.decorators import action from rest_framework.permissions import IsAdminUser from .models import SendGridMail",
"http_method_names = ['get', 'post', 'retrieve'] @action(methods=['GET'], detail=True) def resend(self, request, pk=None): mail =",
"rest_framework.viewsets import ModelViewSet from rest_framework.decorators import action from rest_framework.permissions import IsAdminUser from .models",
"= SendGridMail.objects.all() serializer_class = SendGridMailSerializer permission_classes = [IsAdminUser] http_method_names = ['get', 'post', 'retrieve']",
"import reverse from rest_framework.viewsets import ModelViewSet from rest_framework.decorators import action from rest_framework.permissions import",
"<gh_stars>100-1000 from django.shortcuts import redirect from django.urls import reverse from rest_framework.viewsets import ModelViewSet"
] |
[
"index: return [index, dt[complement]] # Add entry for future checks dt[num] = index",
"if complement in dt and dt[complement] != index: return [index, dt[complement]] # Add",
"int) -> List[int]: dt = {} for index, num in enumerate(nums): # Check",
"return [index, dt[complement]] # Add entry for future checks dt[num] = index return",
"[index, dt[complement]] # Add entry for future checks dt[num] = index return []",
"Check If Complement Exists in dictionary complement = target - num if complement",
"List class Solution: def twoSum(self, nums: List[int], target: int) -> List[int]: dt =",
"num in enumerate(nums): # Check If Complement Exists in dictionary complement = target",
"If Complement Exists in dictionary complement = target - num if complement in",
"def twoSum(self, nums: List[int], target: int) -> List[int]: dt = {} for index,",
"for index, num in enumerate(nums): # Check If Complement Exists in dictionary complement",
"Solution: def twoSum(self, nums: List[int], target: int) -> List[int]: dt = {} for",
"class Solution: def twoSum(self, nums: List[int], target: int) -> List[int]: dt = {}",
"dictionary complement = target - num if complement in dt and dt[complement] !=",
"!= index: return [index, dt[complement]] # Add entry for future checks dt[num] =",
"- num if complement in dt and dt[complement] != index: return [index, dt[complement]]",
"index, num in enumerate(nums): # Check If Complement Exists in dictionary complement =",
"dt and dt[complement] != index: return [index, dt[complement]] # Add entry for future",
"in dictionary complement = target - num if complement in dt and dt[complement]",
"target - num if complement in dt and dt[complement] != index: return [index,",
"enumerate(nums): # Check If Complement Exists in dictionary complement = target - num",
"complement = target - num if complement in dt and dt[complement] != index:",
"Exists in dictionary complement = target - num if complement in dt and",
"in dt and dt[complement] != index: return [index, dt[complement]] # Add entry for",
"List[int], target: int) -> List[int]: dt = {} for index, num in enumerate(nums):",
"nums: List[int], target: int) -> List[int]: dt = {} for index, num in",
"{} for index, num in enumerate(nums): # Check If Complement Exists in dictionary",
"typing import List class Solution: def twoSum(self, nums: List[int], target: int) -> List[int]:",
"complement in dt and dt[complement] != index: return [index, dt[complement]] # Add entry",
"in enumerate(nums): # Check If Complement Exists in dictionary complement = target -",
"dt[complement] != index: return [index, dt[complement]] # Add entry for future checks dt[num]",
"target: int) -> List[int]: dt = {} for index, num in enumerate(nums): #",
"and dt[complement] != index: return [index, dt[complement]] # Add entry for future checks",
"dt = {} for index, num in enumerate(nums): # Check If Complement Exists",
"= target - num if complement in dt and dt[complement] != index: return",
"# Check If Complement Exists in dictionary complement = target - num if",
"num if complement in dt and dt[complement] != index: return [index, dt[complement]] #",
"Complement Exists in dictionary complement = target - num if complement in dt",
"= {} for index, num in enumerate(nums): # Check If Complement Exists in",
"twoSum(self, nums: List[int], target: int) -> List[int]: dt = {} for index, num",
"from typing import List class Solution: def twoSum(self, nums: List[int], target: int) ->",
"List[int]: dt = {} for index, num in enumerate(nums): # Check If Complement",
"import List class Solution: def twoSum(self, nums: List[int], target: int) -> List[int]: dt",
"-> List[int]: dt = {} for index, num in enumerate(nums): # Check If"
] |
[
"LoginForm(request.form) if request.method == 'GET': return render_template( self.template_name, form=form) user = User.get_username(form.username.data) print(user.check_password(form.password.data))",
".models import LoginForm, User class AuthView(BaseView): def dispatch_request(self): form = LoginForm(request.form) if request.method",
"== 'GET': return render_template( self.template_name, form=form) user = User.get_username(form.username.data) print(user.check_password(form.password.data)) if user and",
"print(user.check_password(form.password.data)) if user and user.check_password(form.password.data): login_user(user, form.remember.data) return redirect( url_for('dashboard_bp.dashboard_page') ) return redirect(url_for('auth_bp.auth_view'))",
"user and user.check_password(form.password.data): login_user(user, form.remember.data) return redirect( url_for('dashboard_bp.dashboard_page') ) return redirect(url_for('auth_bp.auth_view')) class LogoutView(BaseView):",
"url_for) from flask_login import login_user, logout_user from app.helpers import BaseView from .models import",
"flask_login import login_user, logout_user from app.helpers import BaseView from .models import LoginForm, User",
"render_template, request, redirect, url_for) from flask_login import login_user, logout_user from app.helpers import BaseView",
"User.get_username(form.username.data) print(user.check_password(form.password.data)) if user and user.check_password(form.password.data): login_user(user, form.remember.data) return redirect( url_for('dashboard_bp.dashboard_page') ) return",
"= LoginForm(request.form) if request.method == 'GET': return render_template( self.template_name, form=form) user = User.get_username(form.username.data)",
"redirect, url_for) from flask_login import login_user, logout_user from app.helpers import BaseView from .models",
"logout_user from app.helpers import BaseView from .models import LoginForm, User class AuthView(BaseView): def",
"form = LoginForm(request.form) if request.method == 'GET': return render_template( self.template_name, form=form) user =",
"render_template( self.template_name, form=form) user = User.get_username(form.username.data) print(user.check_password(form.password.data)) if user and user.check_password(form.password.data): login_user(user, form.remember.data)",
"request.method == 'GET': return render_template( self.template_name, form=form) user = User.get_username(form.username.data) print(user.check_password(form.password.data)) if user",
"request, redirect, url_for) from flask_login import login_user, logout_user from app.helpers import BaseView from",
"from app.helpers import BaseView from .models import LoginForm, User class AuthView(BaseView): def dispatch_request(self):",
"from flask_login import login_user, logout_user from app.helpers import BaseView from .models import LoginForm,",
"import BaseView from .models import LoginForm, User class AuthView(BaseView): def dispatch_request(self): form =",
"user = User.get_username(form.username.data) print(user.check_password(form.password.data)) if user and user.check_password(form.password.data): login_user(user, form.remember.data) return redirect( url_for('dashboard_bp.dashboard_page')",
"user.check_password(form.password.data): login_user(user, form.remember.data) return redirect( url_for('dashboard_bp.dashboard_page') ) return redirect(url_for('auth_bp.auth_view')) class LogoutView(BaseView): def dispatch_request(self):",
"and user.check_password(form.password.data): login_user(user, form.remember.data) return redirect( url_for('dashboard_bp.dashboard_page') ) return redirect(url_for('auth_bp.auth_view')) class LogoutView(BaseView): def",
"redirect( url_for('dashboard_bp.dashboard_page') ) return redirect(url_for('auth_bp.auth_view')) class LogoutView(BaseView): def dispatch_request(self): logout_user() return redirect( url_for('auth_bp.auth_view')",
"app.helpers import BaseView from .models import LoginForm, User class AuthView(BaseView): def dispatch_request(self): form",
"flask import ( render_template, request, redirect, url_for) from flask_login import login_user, logout_user from",
"BaseView from .models import LoginForm, User class AuthView(BaseView): def dispatch_request(self): form = LoginForm(request.form)",
"LoginForm, User class AuthView(BaseView): def dispatch_request(self): form = LoginForm(request.form) if request.method == 'GET':",
"self.template_name, form=form) user = User.get_username(form.username.data) print(user.check_password(form.password.data)) if user and user.check_password(form.password.data): login_user(user, form.remember.data) return",
"import LoginForm, User class AuthView(BaseView): def dispatch_request(self): form = LoginForm(request.form) if request.method ==",
"dispatch_request(self): form = LoginForm(request.form) if request.method == 'GET': return render_template( self.template_name, form=form) user",
"form.remember.data) return redirect( url_for('dashboard_bp.dashboard_page') ) return redirect(url_for('auth_bp.auth_view')) class LogoutView(BaseView): def dispatch_request(self): logout_user() return",
"import ( render_template, request, redirect, url_for) from flask_login import login_user, logout_user from app.helpers",
"login_user(user, form.remember.data) return redirect( url_for('dashboard_bp.dashboard_page') ) return redirect(url_for('auth_bp.auth_view')) class LogoutView(BaseView): def dispatch_request(self): logout_user()",
"from flask import ( render_template, request, redirect, url_for) from flask_login import login_user, logout_user",
"if request.method == 'GET': return render_template( self.template_name, form=form) user = User.get_username(form.username.data) print(user.check_password(form.password.data)) if",
"form=form) user = User.get_username(form.username.data) print(user.check_password(form.password.data)) if user and user.check_password(form.password.data): login_user(user, form.remember.data) return redirect(",
"( render_template, request, redirect, url_for) from flask_login import login_user, logout_user from app.helpers import",
"login_user, logout_user from app.helpers import BaseView from .models import LoginForm, User class AuthView(BaseView):",
"url_for('dashboard_bp.dashboard_page') ) return redirect(url_for('auth_bp.auth_view')) class LogoutView(BaseView): def dispatch_request(self): logout_user() return redirect( url_for('auth_bp.auth_view') )",
"'GET': return render_template( self.template_name, form=form) user = User.get_username(form.username.data) print(user.check_password(form.password.data)) if user and user.check_password(form.password.data):",
"AuthView(BaseView): def dispatch_request(self): form = LoginForm(request.form) if request.method == 'GET': return render_template( self.template_name,",
"if user and user.check_password(form.password.data): login_user(user, form.remember.data) return redirect( url_for('dashboard_bp.dashboard_page') ) return redirect(url_for('auth_bp.auth_view')) class",
"return render_template( self.template_name, form=form) user = User.get_username(form.username.data) print(user.check_password(form.password.data)) if user and user.check_password(form.password.data): login_user(user,",
"User class AuthView(BaseView): def dispatch_request(self): form = LoginForm(request.form) if request.method == 'GET': return",
"def dispatch_request(self): form = LoginForm(request.form) if request.method == 'GET': return render_template( self.template_name, form=form)",
"return redirect( url_for('dashboard_bp.dashboard_page') ) return redirect(url_for('auth_bp.auth_view')) class LogoutView(BaseView): def dispatch_request(self): logout_user() return redirect(",
"class AuthView(BaseView): def dispatch_request(self): form = LoginForm(request.form) if request.method == 'GET': return render_template(",
"from .models import LoginForm, User class AuthView(BaseView): def dispatch_request(self): form = LoginForm(request.form) if",
"= User.get_username(form.username.data) print(user.check_password(form.password.data)) if user and user.check_password(form.password.data): login_user(user, form.remember.data) return redirect( url_for('dashboard_bp.dashboard_page') )",
"import login_user, logout_user from app.helpers import BaseView from .models import LoginForm, User class"
] |
[
"= big_save_len self.big_save_freq = big_save_freq self.state_descriptor = state_descriptor def postprocess(self, training_results, batch): global_step",
"'model_parameters' : self.um.var_list} def update(self, sess): batch = self.dp.dequeue_batch() feed_dict = { self.wm.action",
"learning_rate_params['world_model']) self.wm_opt_params, wm_opt = get_optimizer(wm_learning_rate, self.world_model.loss, self.global_step, optimizer_params['world_model']) self.world_model_targets = {'given' : self.world_model.processed_input,",
"'objects1']: # prepped[desc] = np.array([[timepoint if timepoint is not None else np.zeros(obs[desc][-1].shape, dtype",
"# next_depth = np.array([batch.next_state['depths1']]) # return depths, actions, next_depth def postprocess_batch_for_actionmap(batch, state_desc): obs,",
"dtype = np.uint8), 'objects1' : hdf5.require_dataset('objects1', shape = (N, height, width, 3), dtype",
"self.wm.action_post : batch['action_post'] } res = sess.run(self.targets, feed_dict = feed_dict) res['batch'] = batch",
"to do one forward pass each index because action sampling is the 'batch.'",
"self.global_step, optimizer_params['uncertainty_model']) self.global_step = self.global_step / 2 self.um_targets = {'loss' : self.um.uncertainty_loss, 'learning_rate'",
"updater_params): self.data_provider = data_provider fn = updater_params['hdf5_filename'] N = updater_params['N_save'] height, width =",
"tf.constant_initializer(0, dtype = tf.int32)) print(learning_rate_params.keys()) um_lr_params, um_lr = get_learning_rate(self.global_step, **learning_rate_params['uncertainty_model']) um_opt_params, um_opt =",
"'global_step' : self.global_step} def update(self, sess, visualize = False): batch = {} for",
"deets') print(global_step) print(self.big_save_freq) print(self.big_save_len) if (global_step) % self.big_save_freq < self.big_save_len: print('big time') save_keys",
"= batch['msg'][-1] entropies = [other[0] for other in batch['recent']['other']] entropies = np.mean(entropies) res['entropy']",
"self.um_lr_params, um_lr = get_learning_rate(self.global_step, ** learning_rate_params['uncertainty_model']) num_not_frozen = 0 self.targets = {} self.state_desc",
"= get_optimizer(um_lr, self.um.uncertainty_loss, self.um_step, optimizer_params['uncertainty_model'], var_list = self.um.var_list) self.targets['um_opt'] = um_opt self.targets['um_lr'] =",
"np.array([replace_the_nones(act)]) actions_post = np.array([replace_the_nones(act_post)]) return obs_past, actions, actions_post, obs_fut # def postprocess_batch_depth(batch): #",
"for idx in self.map_draw_example_indices: # obs_for_actor = [batch[self.state_desc][idx][t] for t in self.map_draw_timestep_indices] #",
"np.mean(mean_per_provider) res['obj_freq_per_provider_noprint'] = mean_per_provider return res class UncertaintyPostprocessor: def __init__(self, big_save_keys = None,",
"objects } world_model_res = sess.run(self.world_model_targets, feed_dict = wm_feed_dict) if visualize: cv2.imshow('pred', world_model_res['prediction'][0] /",
"= tf.placeholder(tf.float32, [None]) log_prob_tf = tf.nn.log_softmax(rl_model.logits) prob_tf = tf.nn.softmax(rl_model.logits) pi_loss = -tf.reduce_sum(tf.reduce_sum(log_prob_tf *",
"self.um.uncertainty_loss, 'um_lr' : um_lr, 'um_optimizer' : um_opt, # 'global_step' : self.global_step, 'loss_per_example' :",
"batch[state_desc][:, :-1], self.um.action_sample : batch['action'][:, -1], self.um.true_loss : world_model_res['loss_per_example'] } um_res = sess.run(self.um_targets,",
"updater_params.get('state_desc', 'depths1') if not freeze_wm: act_lr_params, act_lr = get_learning_rate(self.act_step, **learning_rate_params['world_model']['act_model']) fut_lr_params, fut_lr =",
"'a') dt = h5py.special_dtype(vlen = str) self.handles = {'msg' : hdf5.require_dataset('msg', shape =",
"= self.postprocessor.postprocess(wm_res_new, batch) return res class DamianWMUncertaintyUpdater: def __init__(self, world_model, uncertainty_model, data_provider, optimizer_params,",
"np.mean(entropies) # res['entropy'] = entropies if 'msg' in batch['recent']: looking_at_obj = [1 if",
"map_draw_res res = self.postprocessor.postprocess(res, batch) return res, global_step class JustUncertaintyUpdater: def __init__(self, models,",
"if desc == 'obj_there': res['batch'][desc] = val elif desc != 'recent': res['batch'][desc] =",
"action, entropy, estimated_world_loss = self.um.act(sess, action_samples, obs_for_actor) to_add = {'example_id' : idx, 'action_sample'",
"= get_learning_rate(self.global_step, ** learning_rate_params['world_model']) self.wm_opt_params, wm_opt = get_optimizer(wm_learning_rate, self.world_model.loss, self.global_step, optimizer_params['world_model']) self.world_model_targets =",
"np.array([[timepoint if timepoint is not None else np.zeros(obs[desc][-1].shape, dtype = obs[desc][-1].dtype) for timepoint",
"seen action_ids_list.append(idx) action_ids = np.array([action_ids_list]) return depths_past, objects, actions, action_ids, depths_fut # def",
"self.um.just_random: print('Selecting action at random') batch = {} for i, dp in enumerate(self.data_provider):",
"in batch['recent']['other']] entropies = np.mean(entropies) res['entropy'] = entropies looking_at_obj = [1 if msg",
"do one forward pass each index because action sampling is the 'batch.' #self.action_sampler",
"import numpy as np import cv2 from curiosity.interaction import models import h5py import",
"'fut_loss' : self.wm.fut_loss, 'act_loss' : self.wm.act_loss, # 'estimated_world_loss' : self.um.estimated_world_loss, # '' #",
"'global_step' : self.global_step, 'loss_per_example' : self.um.true_loss}) self.state_desc = updater_params['state_desc'] #checking that we don't",
"= um_opt self.targets['um_lr'] = um_lr self.targets['global_step'] = self.global_step global_increment = tf.assign_add(self.global_step, 1) um_increment",
"batch['action'], self.wm.obj_there : batch['obj_there'] } res = sess.run(self.targets, feed_dict = feed_dict) res =",
"print('state desc! ' + self.state_desc) res = sess.run(self.targets, feed_dict = feed_dict) res.pop('um_increment') global_step",
"= self.um.var_list) self.global_step = self.global_step / 3 self.targets = {'encoding_i' : self.wm.encoding_i, 'encoding_f'",
"'action_samples' : action_samples, 'depths1' : batch[self.state_desc][idx], # 'action' : batch['action'][idx], 'action_post' : batch['action_post'][idx]}",
"= {'um_loss' : self.um.uncertainty_loss, 'um_lr' : um_lr, 'um_optimizer' : um_opt, 'global_step' : self.global_step,",
"= False): batch = self.data_provider.dequeue_batch() state_desc = self.state_desc #depths, actions, actions_post, next_depth =",
"elif desc != 'recent': res['batch'][desc] = val[:, -1] res['recent'] = batch['recent'] class ObjectThereValidater:",
"act_opt self.targets['fut_opt'] = fut_opt self.targets['act_lr'] = act_lr self.targets['fut_lr'] = fut_lr if not freeze_um:",
"entropies = np.mean(entropies) res['entropy'] = entropies looking_at_obj = [1 if msg is not",
"updater_params): self.data_provider = data_provider\\ if isinstance(data_provider, list) else [data_provider] self.wm = models['world_model'] self.um",
"class SquareForceMagUpdater: def __init__(self, models, data_provider, optimizer_params, learning_rate_params, postprocessor, updater_params): self.dp = data_provider",
"[None] + world_model.action_one_hot.get_shape().as_list()[1:]) self.adv = tf.placeholder(tf.float32, [None]) self.r = tf.placeholder(tf.float32, [None]) log_prob_tf =",
"False): batch = self.dp.dequeue_batch() state_desc = self.state_desc feed_dict = { self.wm.states : batch[state_desc],",
"res['global_step'] = res.pop('um_global_step') res = self.postprocessor.postprocess(wm_res_new, batch) return res class DamianWMUncertaintyUpdater: def __init__(self,",
"* log_prob_tf) self.rl_loss = pi_loss + 0.5 * vf_loss - entropy * 0.01",
"res, global_step class JustUncertaintyUpdater: def __init__(self, models, data_provider, optimizer_params, learning_rate_params, postprocessor, updater_params, action_sampler",
"= self.global_step.assign_add(1) self.um_lr_params, um_learning_rate = get_learning_rate(self.global_step, **learning_rate_params['uncertainty_model']) self.um_lr_params, um_opt = get_optimizer(um_learning_rate, self.um.uncertainty_loss, self.global_step,",
"'fut_loss' : self.wm.fut_loss, 'act_loss' : self.wm.act_loss, 'um_loss' : self.um.uncertainty_loss, 'estimated_world_loss' : self.um.estimated_world_loss, 'loss_per_example'",
"self.um = models['uncertainty_model'] self.wm = models['world_model'] self.targets = { 'act_pred' : self.wm.act_pred, 'fut_loss'",
"= sess.run(self.targets, feed_dict = feed_dict) res = self.postprocessor.postprocess(res, batch) return res class LatentFreezeUpdater:",
"not freeze_um: num_not_frozen += 1 um_opt_params, um_opt = get_optimizer(um_lr, self.um.uncertainty_loss, self.global_step, optimizer_params['uncertainty_model'], var_list",
"batch) return res class UncertaintyUpdater: def __init__(self, world_model, uncertainty_model, data_provider, optimizer_params, learning_rate_params, postprocessor):",
"if not freeze_um: num_not_frozen += 1 um_opt_params, um_opt = get_optimizer(um_lr, self.um.uncertainty_loss, self.global_step, optimizer_params['uncertainty_model'],",
"= self.um.var_list) self.targets['um_opt'] = um_opt if num_not_frozen == 0: self.targets['global_step'] = self.global_step self.targets['increment']",
"= int(action_msg[0]['id']) else: idx = -10000#just something that's not an id seen action_ids_list.append(idx)",
"little_save_keys self.big_save_len = big_save_len self.big_save_freq = big_save_freq self.state_descriptor = state_descriptor self.big_save_keys.append('map_draw') self.little_save_keys.append('map_draw') self.big_save_keys.extend(['act_lr',",
"= [batch[self.state_desc][idx][t] for t in self.map_draw_timestep_indices] # action_samples = self.action_sampler.sample_actions() # action, entropy,",
"self.global_step res = sess.run(self.targets, feed_dict = feed_dict) glstep = res['global_step'] res = self.postprocessor.postprocess(res,",
"isinstance(data_provider, list) else [data_provider] self.wm = models['world_model'] self.um = models['uncertainty_model'] self.postprocessor = postprocessor",
"the 'batch.' #self.action_sampler = action_sampler #assert self.map_draw_mode == 'specified_indices' and self.action_sampler is not",
"postprocess_batch_depth(batch): # depths = np.array([[timepoint if timepoint is not None else np.zeros(obs['depths1'][-1].shape, dtype",
"[other[0] for other in batch['recent']['other']] entropies = np.mean(entropies) res['entropy'] = entropies looking_at_obj =",
": batch['action_post'][idx]} # map_draw_res.append(to_add) # res['map_draw'] = map_draw_res res = self.postprocessor.postprocess(res, batch) return",
"{} self.targets.update({k : v for k, v in self.wm.readouts.items() if k not in",
"don't have repeat names def start(self, sess): self.data_provider.start_runner(sess) sess.run(tf.global_variables_initializer()) def update(self, sess, visualize",
"dp.dequeue_batch() for k in provider_batch: if k in batch: batch[k].append(provider_batch[k]) else: batch[k] =",
"in ['action', 'action_post', 'depths1']: batch[k] = np.concatenate(batch[k], axis=0) state_desc = 'depths1' #depths, actions,",
"postprocessor self.global_step = tf.get_variable('global_step', [], tf.int32, initializer = tf.constant_initializer(0,dtype = tf.int32)) self.act_lr_params, act_lr",
"tensorflow as tf from tfutils.base import get_optimizer, get_learning_rate import numpy as np import",
"in obs[desc]] for obs in batch.states]) # actions = np.array([[np.zeros(batch.next_state['action'][-1].shape, batch.next_state['action'][-1].dtype) if timepoint",
"res = sess.run(self.targets, feed_dict = feed_dict) #TODO case it for online res['recent'] =",
"get_optimizer(fut_lr, self.wm.fut_loss, self.global_step, optimizer_params['world_model']['fut_model'], var_list = self.wm.fut_var_list) um_opt_params, um_opt = get_optimizer(um_lr, self.um.uncertainty_loss, self.global_step,",
"now just assuming one sort of specification self.state_desc = updater_params.get('state_desc', 'depths1') self.map_draw_mode =",
"res['entropy'] = entropies if 'msg' in batch['recent']: looking_at_obj = [1 if msg is",
"self.um.state_descriptor wm_feed_dict = { self.world_model.states : batch[state_desc], self.world_model.action : batch['action'][:, -self.world_action_time : ]",
"action_ids_list.append(idx) # action_ids = np.array([action_ids_list]) # next_depths = np.array([batch.next_state['depths1']]) # return prepped['depths1'], prepped['objects1'],",
"batch): global_step = training_results['global_step'] res = {} if (global_step) % self.big_save_freq < self.big_save_len:",
": self.wm.act_loss, # 'estimated_world_loss' : self.um.estimated_world_loss, # '' # } #self.targets.update({'um_loss' : self.um.uncertainty_loss,",
"self.start = end def close(self): self.hdf5.close() class LatentUncertaintyValidator: def __init__(self, models, data_provider): self.um",
"if batch.next_state['msg'][i] is not None else [] # if len(action_msg): # idx =",
"= np.uint8), 'action' : hdf5.require_dataset('action', shape = (N, act_dim), dtype = np.float32), 'action_post'",
"= postprocessor self.global_step = tf.get_variable('global_step', [], tf.int32, initializer = tf.constant_initializer(0,dtype = tf.int32)) self.um_lr_params,",
"self.um = uncertainty_model self.global_step = tf.get_variable('global_step', [], tf.int32, initializer = tf.constant_initializer(0,dtype = tf.int32))",
"batch[k].append(provider_batch[k]) else: batch[k] = [provider_batch[k]] for k in ['action', 'action_post', 'depths1']: batch[k] =",
"= self.state_desc #depths, actions, actions_post, next_depth = postprocess_batch_depth(batch, state_desc) feed_dict = { self.wm.states",
"self.data_provider.start_runner(sess) sess.run(tf.global_variables_initializer()) def update(self, sess, visualize = False): batch = self.data_provider.dequeue_batch() depths, objects,",
"self.targets['um_opt'] = um_opt if num_not_frozen == 0: self.targets['global_step'] = self.global_step self.targets['increment'] = tf.assign_add(self.global_step,",
"get_optimizer(wm_learning_rate, self.world_model.loss, self.global_step, optimizer_params['world_model']) self.world_model_targets = {'given' : self.world_model.processed_input, 'loss' : self.world_model.loss, 'learning_rate'",
": self.um.true_loss, 'estimated_world_loss' : self.um.estimated_world_loss} self.dp = data_provider def run(self, sess): batch =",
"at random') batch = {} for i, dp in enumerate(self.data_provider): provider_batch = dp.dequeue_batch()",
"as tf from tfutils.base import get_optimizer, get_learning_rate import numpy as np import cv2",
"optimizer_params['uncertainty_model'], var_list = self.um.var_list) self.global_step = self.global_step / 3 self.targets = {'encoding_i' :",
"batch['recent']['msg']] self.start = end def close(self): self.hdf5.close() class LatentUncertaintyValidator: def __init__(self, models, data_provider):",
"= training_results['global_step'] res = {} if (global_step) % self.big_save_freq < self.big_save_len: save_keys =",
"'depths1') #self.map_draw_mode = updater_params['map_draw_mode'] #this specification specifices batch example indices for which we",
"get_learning_rate(self.global_step, ** learning_rate_params['world_model']['fut_model']) self.um_lr_params, um_lr = get_learning_rate(self.global_step, ** learning_rate_params['uncertainty_model']) act_opt_params, act_opt = get_optimizer(act_lr,",
"is not None, (self.map_draw_mode, action_sampler) #self.map_draw_example_indices = updater_params['map_draw_example_indices'] #self.map_draw_timestep_indices = updater_params['map_draw_timestep_indices'] #self.map_draw_freq =",
"# actions = np.array(batch.actions) # next_depth = np.array([batch.next_state['depths1']]) # return depths, actions, next_depth",
"desc != 'recent': res['batch'][desc] = val[:, -1] res['recent'] = batch['recent'] class ObjectThereValidater: def",
"for online res['recent'] = {} #if self.map_draw_mode == 'specified_indices': # map_draw_res = []",
"batch['action'], self.wm.action_post : batch['action_post'] } res = sess.run(self.targets, feed_dict = feed_dict) res.pop('um_increment') res.pop('global_increment')",
"uncertainty_model, data_provider, optimizer_params, learning_rate_params, postprocessor): self.data_provider = data_provider self.world_model = world_model self.um =",
"assert set(self.wm.readouts.keys()) != set(self.um.readouts.keys()) self.targets.update(self.wm.readouts) self.targets.update(self.um.readouts) #self.targets = { # 'fut_pred' : self.wm.fut_pred,",
"'depths1') if not freeze_wm: act_lr_params, act_lr = get_learning_rate(self.act_step, **learning_rate_params['world_model']['act_model']) fut_lr_params, fut_lr = get_learning_rate(self.fut_step,",
"depths_fut = np.array([depths[:1]]) objects = np.array([replace_the_nones(obs[state_desc])[:-1]]) actions = np.array([replace_the_nones(act)]) action_ids_list = [] for",
"for elt in my_list] def postprocess_batch_depth(batch, state_desc): obs, msg, act, act_post = batch",
": self.um.true_loss, 'global_step' : self.global_step} def update(self, sess, visualize = False): batch =",
"This is probably where we can put parallelization. Not finished! ''' def __init__(world_model,",
"self.um.true_loss : world_model_res['loss_per_example'] } um_res = sess.run(self.um_targets, feed_dict = um_feed_dict) wm_res_new = dict(('wm_'",
"sess, visualize = False): batch = self.data_provider.dequeue_batch() state_desc = self.um.state_descriptor wm_feed_dict = {",
"} res = sess.run(self.targets, feed_dict = feed_dict) res = self.postprocessor.postprocess(res, batch) return res",
"entropy, estimated_world_loss = self.um.act(sess, action_samples, obs_for_actor) # to_add = {'example_id' : idx, 'action_sample'",
"batch.next_state['msg'][i] is not None else [] # if len(action_msg): # idx = int(action_msg[0]['id'])",
"something that's not an id seen action_ids_list.append(idx) action_ids = np.array([action_ids_list]) return depths_past, objects,",
"} #self.targets.update({'um_loss' : self.um.uncertainty_loss, 'um_lr' : um_lr, 'um_optimizer' : um_opt, # 'global_step' :",
"in range(2): # action_msg = batch.next_state['msg'][i]['msg']['actions'] if batch.next_state['msg'][i] is not None else []",
"** learning_rate_params['uncertainty_model']) um_opt_params, um_opt = get_optimizer(um_lr, self.um.uncertainty_loss, self.global_step, optimizer_params['uncertainty_model'], var_list = self.um.var_list) self.targets",
"loc set up') self.start = 0 def update(self): batch = self.data_provider.dequeue_batch() bs =",
"tosave = tosave.astype(np.float32) self.handles[k][self.start : end] = batch['recent'][k] self.handles['msg'][self.start : end] = [json.dumps(msg)",
"tf.reduce_sum(tf.square(rl_model.vf - self.r)) entropy = -tf.reduce_sum(prob_tf * log_prob_tf) self.rl_loss = pi_loss + 0.5",
"looking_at_obj = [1 if msg is not None and msg['msg']['action_type'] == 'OBJ_ACT' else",
"'optimizer' : um_opt, 'global_step' : self.global_step} self.postprocessor = postprocessor def start(self, sess): self.data_provider.start_runner(sess)",
"= get_optimizer(um_lr, self.um.uncertainty_loss, self.global_step, optimizer_params['uncertainty_model'], var_list = self.um.var_list) self.targets = {'um_loss' : self.um.uncertainty_loss,",
"else True def run(self, sess): batch = self.dp.dequeue_batch() feed_dict = { self.wm.states :",
"batch.states]) # actions = np.array(batch.actions) # next_depth = np.array([batch.next_state['depths1']]) # return depths, actions,",
"in batch: batch[k].append(provider_batch[k]) else: batch[k] = [provider_batch[k]] for k in ['action', 'action_post', 'depths1']:",
"res['global_step'] #if self.map_draw_mode is not None and global_step % self.map_draw_freq == 0: #",
"[], tf.int32, initializer = tf.constant_initializer(0,dtype = tf.int32)) self.targets = {} self.state_desc = updater_params.get('state_desc',",
"batch['action'], self.wm.action_post : batch['action_post'] } res = sess.run(self.targets, feed_dict = feed_dict) res['batch'] =",
"'action' : batch['action'][idx], 'action_post' : batch['action_post'][idx]} # map_draw_res.append(to_add) #res['map_draw'] = map_draw_res return res",
": batch[self.state_desc], self.wm.action : batch['action'], self.wm.action_post : batch ['action_post'] } if self.insert_objthere: feed_dict[self.wm.obj_there_via_msg]",
"[other[1] for other in batch['recent']['other']] action_sample = [other[2] for other in batch['recent']['other']] res['batch']",
"= postprocessor self.global_step = tf.get_variable('global_step', [], tf.int32, initializer = tf.constant_initializer(0, dtype = tf.int32))",
"'images1': hdf5.require_dataset('images1', shape = (N, height, width, 3), dtype = np.uint8), 'action' :",
"visualize = False): batch = {} for i, dp in enumerate(self.data_provider): provider_batch =",
"updater_params['map_draw_timestep_indices'] #self.map_draw_freq = updater_params['map_draw_freq'] def update(self, sess, visualize = False): if self.um.just_random: print('Selecting",
"updater_params['state_desc'] #checking that we don't have repeat names def start(self, sess): self.data_provider.start_runner(sess) sess.run(tf.global_variables_initializer())",
"because action sampling is the 'batch.' self.action_sampler = action_sampler assert self.map_draw_mode == 'specified_indices'",
"action, entropy, estimated_world_loss = self.um.act(sess, action_samples, obs_for_actor) # to_add = {'example_id' : idx,",
"= { self.wm.states : batch[self.state_desc], self.wm.action : batch['action'], self.wm.action_post : batch['action_post'] } res",
"class DamianWMUncertaintyUpdater: def __init__(self, world_model, uncertainty_model, data_provider, optimizer_params, learning_rate_params, postprocessor): self.data_provider = data_provider",
"[] if len(action_msg): idx = int(action_msg[0]['id']) else: idx = -10000#just something that's not",
": self.um.uncertainty_loss, 'learning_rate' : um_learning_rate, 'optimizer' : um_opt, 'global_step' : self.global_step} self.postprocessor =",
": self.um.estimated_world_loss, 'ans' : self.um.ans, 'oh_my_god' : self.um.oh_my_god, 'model_parameters' : self.um.var_list} def update(self,",
"= np.uint8), 'images1': hdf5.require_dataset('images1', shape = (N, height, width, 3), dtype = np.uint8),",
"map_draw_res res = self.postprocessor.postprocess(res, batch) return res, global_step class FreezeUpdater: def __init__(self, models,",
"list) else [data_provider] self.wm = models['world_model'] self.um = models['uncertainty_model'] freeze_wm = updater_params['freeze_wm'] freeze_um",
"um_opt, 'global_step' : self.global_step, 'loss_per_example' : self.um.true_loss, 'estimated_world_loss' : self.um.estimated_world_loss } self.state_desc =",
"in ['depths1', 'objects1']: # prepped[desc] = np.array([[timepoint if timepoint is not None else",
"= self.data_provider.dequeue_batch() depths, objects, actions, action_ids, next_depth = postprocess_batch_for_actionmap(batch) wm_feed_dict = { self.world_model.s_i",
"feed dict') feed_dict[self.um.obj_there] = batch['obj_there'] res = sess.run(self.targets, feed_dict = feed_dict) res =",
"um_learning_rate, 'optimizer' : um_opt, 'global_step' : self.global_step} self.postprocessor = postprocessor def start(self, sess):",
"in self.map_draw_example_indices: # obs_for_actor = [batch[self.state_desc][idx][t] for t in self.map_draw_timestep_indices] # action_samples =",
"* self.adv) vf_loss = .5 * tf.reduce_sum(tf.square(rl_model.vf - self.r)) entropy = -tf.reduce_sum(prob_tf *",
"self.wm.encode_var_list) um_opt_params, um_opt = get_optimizer(um_lr, self.um.uncertainty_loss, self.global_step, optimizer_params['uncertainty_model'], var_list = self.um.var_list) self.global_step =",
"data_provider): self.dp = data_provider self.wm = model['world_model'] self.um = model['uncertainty_model'] self.targets = {}",
"um_increment = tf.assign_add(self.um.step, 1) self.targets.update({'global_increment' : global_increment, 'um_increment' : um_increment}) self.targets.update(self.wm.readouts) self.targets.update(self.um.readouts) assert",
"class LatentFreezeUpdater: def __init__(self, models, data_provider, optimizer_params, learning_rate_params, postprocessor, updater_params): self.data_provider = data_provider\\",
"batch['depths1'], 'act' : batch['action'], 'act_post' : batch['action_post'], 'est_loss' : est_losses, 'action_sample' : action_sample}",
"False): if self.um.just_random: print('Selecting action at random') batch = {} for i, dp",
"self.state_desc = updater_params.get('state_desc', 'depths1') self.map_draw_mode = updater_params['map_draw_mode'] #this specification specifices batch example indices",
"'encoding_f' : self.wm.encoding_f, 'fut_pred' : self.wm.fut_pred, 'act_pred' : self.wm.act_pred, 'act_optimizer' : act_opt, 'fut_optimizer'",
"# if self.map_draw_mode == 'specified_indices': # map_draw_res = [] # for idx in",
"= postprocessor self.global_step = tf.get_variable('global_step', [], tf.int32, initializer = tf.constant_initializer(0,dtype = tf.int32)) self.act_lr_params,",
"else: idx = -10000#just something that's not an id seen action_ids_list.append(idx) action_ids =",
"= 0) feed_dict[self.wm.obj_there_via_msg] = batch['obj_there'] print('state desc! ' + self.state_desc) res = sess.run(self.targets,",
"ActionUncertaintyValidatorWithReadouts: def __init__(self, model, data_provider): self.dp = data_provider self.wm = model['world_model'] self.um =",
"batch['action'], 'act_post' : batch['action_post'], 'est_loss' : est_losses, 'action_sample' : action_sample} res['msg'] = batch['recent']['msg']",
"= entropies if 'msg' in batch['recent']: looking_at_obj = [1 if msg is not",
": action_samples, 'depths1' : batch[self.state_desc][idx], # 'action' : batch['action'][idx], 'action_post' : batch['action_post'][idx]} #",
"= hdf5 = h5py.File(fn, mode = 'a') dt = h5py.special_dtype(vlen = str) self.handles",
"postprocessor def start(self, sess): self.data_provider.start_runner(sess) sess.run(tf.global_variables_initializer()) def update(self, sess, visualize = False): batch",
"self.targets.update({k : v for k, v in self.um.readouts.items() if k not in self.um.save_to_gfs})",
"assert set(self.wm.readouts.keys()) != set(self.um.readouts.keys()) def update(self, sess, visualize = False): if self.um.just_random: print('Selecting",
"= dp.dequeue_batch() for k in provider_batch: if k in batch: batch[k].append(provider_batch[k]) else: batch[k]",
"= tf.constant_initializer(0,dtype = tf.int32)) self.act_lr_params, act_lr = get_learning_rate(self.global_step, ** learning_rate_params['world_model']['act_model']) self.fut_lr_params, fut_lr =",
"est_losses = [other[1] for other in batch['recent']['other']] action_sample = [other[2] for other in",
"RawDepthDiscreteActionUpdater: ''' Provides the training step. This is probably where we can put",
"if timepoint is None else timepoint for timepoint in batch.next_state['action']]]) # print('actions shape')",
"[1 if msg is not None and msg['msg']['action_type'] == 'OBJ_ACT' else 0 for",
"= eta self.global_step = tf.get_variable('global_step', [], tf.int32, initializer = tf.constant_initializer(0,dtype = tf.int32)) self.action",
"in batch['recent']: looking_at_obj = [1 if msg is not None and msg['msg']['action_type'] ==",
"nothing self.map_draw_mode = 'specified_indices' #relies on there being just one obs type self.state_desc",
"= get_optimizer(learning_rate, self.rl_loss, ) def replace_the_nones(my_list): ''' Assumes my_list[-1] is np array '''",
"um_opt} assert set(self.wm.readouts.keys()) != set(self.um.readouts.keys()) self.targets.update(self.wm.readouts) self.targets.update(self.um.readouts) #self.targets = { # 'fut_pred' :",
": batch['action'], self.wm.action_post : batch['action_post'] } res = sess.run(self.targets, feed_dict = feed_dict) res['batch']",
"class ActionUncertaintyValidatorWithReadouts: def __init__(self, model, data_provider): self.dp = data_provider self.wm = model['world_model'] self.um",
": batch[state_desc], self.wm.action : batch['action'], self.wm.action_post : batch['action_post'] } res = sess.run(self.targets, feed_dict",
"self.targets['global_step'] = self.global_step self.targets['increment'] = tf.assign_add(self.global_step, 1) else: self.global_step = self.global_step / num_not_frozen",
"return res class LatentFreezeUpdater: def __init__(self, models, data_provider, optimizer_params, learning_rate_params, postprocessor, updater_params): self.data_provider",
"glstep = res['global_step'] res = self.postprocessor.postprocess(res, batch) return res, glstep class LatentUncertaintyUpdater: def",
"batch) return res, global_step class ActionUncertaintyUpdater: def __init__(self, models, data_provider, optimizer_params, learning_rate_params, postprocessor,",
"val[:, -1] res['recent'] = batch['recent'] class ObjectThereValidater: def __init__(self, models, data_provider): self.um =",
"self.map_draw_freq == 0: if self.map_draw_mode == 'specified_indices': map_draw_res = [] for idx in",
"res = sess.run(self.targets, feed_dict = feed_dict) global_step = res['global_step'] if self.map_draw_mode is not",
"visualize = False): batch = self.dp.dequeue_batch() state_desc = self.state_desc feed_dict = { self.wm.states",
"= feed_dict) res['batch'] = batch return res class ActionUncertaintyValidatorWithReadouts: def __init__(self, model, data_provider):",
"is the 'batch.' #self.action_sampler = action_sampler #assert self.map_draw_mode == 'specified_indices' and self.action_sampler is",
": self.um.true_loss} self.dp = data_provider def run(self, sess): batch = self.dp.dequeue_batch() feed_dict =",
"depths, self.world_model.s_f : next_depth, self.world_model.action : actions, self.world_model.action_id : action_ids, self.world_model.objects : objects",
"'global_step' : self.global_step, 'loss_per_example' : self.um.true_loss, 'estimated_world_loss' : self.um.estimated_world_loss } self.state_desc = updater_params['state_desc']",
"in batch.states]) # actions = np.array([[np.zeros(batch.next_state['action'][-1].shape, batch.next_state['action'][-1].dtype) if timepoint is None else timepoint",
"var_list = self.um.var_list) self.targets = {'um_loss' : self.um.uncertainty_loss, 'um_lr' : um_lr, 'um_optimizer' :",
"tf.get_variable('global_step', [], tf.int32, initializer = tf.constant_initializer(0,dtype = tf.int32)) self.wm_lr_params, wm_learning_rate = get_learning_rate(self.global_step, **",
"act = batch prepped = {} depths = replace_the_nones(obs[state_desc]) depths_past = np.array([depths[:-1]]) depths_fut",
"provider_recent['msg']] mean_per_provider.append(np.mean(looking_at_obj)) res['obj_freq'] = np.mean(mean_per_provider) res['obj_freq_per_provider_noprint'] = mean_per_provider return res class UncertaintyPostprocessor: def",
"= {'encoding_i' : self.wm.encoding_i, 'encoding_f' : self.wm.encoding_f, 'fut_pred' : self.wm.fut_pred, 'act_pred' : self.wm.act_pred,",
"'act' : batch['action'], 'act_post' : batch['action_post'], 'est_loss' : est_losses, 'action_sample' : action_sample} res['msg']",
"# to_add = {'example_id' : idx, 'action_sample' : action, 'estimated_world_loss' : estimated_world_loss, #",
"save_keys = self.big_save_keys #est_losses = [other[1] for other in batch['other']] #action_sample = [other[2]",
"sampling is the 'batch.' self.action_sampler = action_sampler assert self.map_draw_mode == 'specified_indices' and self.action_sampler",
"self.insert_objthere: feed_dict[self.wm.obj_there_via_msg] = batch['obj_there'] res = sess.run(self.targets, feed_dict = feed_dict) #TODO case it",
"batch.states]) # actions = np.array([[np.zeros(batch.next_state['action'][-1].shape, batch.next_state['action'][-1].dtype) if timepoint is None else timepoint for",
"tf.int32)) self.um_step = tf.get_variable('ext_uncertainty_step', [], tf.int32, initializer = tf.constant_initializer(0,dtype = tf.int32)) self.targets =",
"= self.world_model.action.get_shape().as_list()[1] def start(self, sess): self.data_provider.start_runner(sess) sess.run(tf.global_variables_initializer()) def update(self, sess, visualize = False):",
"return res class DamianWMUncertaintyUpdater: def __init__(self, world_model, uncertainty_model, data_provider, optimizer_params, learning_rate_params, postprocessor): self.data_provider",
"training step. This is probably where we can put parallelization. Not finished! '''",
"'um_optimizer' : um_opt} assert set(self.wm.readouts.keys()) != set(self.um.readouts.keys()) self.targets.update(self.wm.readouts) self.targets.update(self.um.readouts) #self.targets = { #",
"self.world_model.pred, 'tv' : self.world_model.tv} self.inc_step = self.global_step.assign_add(1) self.um_lr_params, um_learning_rate = get_learning_rate(self.global_step, **learning_rate_params['uncertainty_model']) self.um_lr_params,",
"data_provider): self.um = models['uncertainty_model'] self.wm = models['world_model'] self.targets = {'um_loss' : self.um.uncertainty_loss, 'loss_per_example'",
"batch = self.dp.dequeue_batch() feed_dict = { self.wm.states : batch['depths1'], self.wm.action : batch['action'], self.wm.action_post",
"self.targets = {'global_step' : self.global_step, 'um_optimizer' : um_opt} assert set(self.wm.readouts.keys()) != set(self.um.readouts.keys()) self.targets.update(self.wm.readouts)",
"'loss_per_example' : self.um.true_loss, 'estimated_world_loss' : self.um.estimated_world_loss} self.dp = data_provider def run(self, sess): batch",
"= { self.world_model.s_i : depths, self.world_model.s_f : next_depth, self.world_model.action : actions, self.world_model.action_id :",
"feed_dict = { self.wm.states : batch['depths1'], self.wm.action : batch['action'], self.wm.obj_there : batch['obj_there'] }",
"= self.state_desc feed_dict = { self.wm.states : batch[state_desc], self.wm.action : batch['action'], self.wm.action_post :",
"tf.int32)) self.action = tf.placeholder = tf.placeholder(tf.float32, [None] + world_model.action_one_hot.get_shape().as_list()[1:]) self.adv = tf.placeholder(tf.float32, [None])",
"#Map drawing. Meant to have options, but for now just assuming one sort",
": um_opt, 'global_step' : self.global_step, 'loss_per_example' : self.um.true_loss, 'estimated_world_loss' : self.um.estimated_world_loss, 'ans' :",
"self.world_model.action_id : action_ids, self.world_model.objects : objects } world_model_res = sess.run(self.world_model_targets, feed_dict = wm_feed_dict)",
"timepoint is not None else np.zeros(obs[desc][-1].shape, dtype = obs[desc][-1].dtype) for timepoint in obs[desc]]",
"obs_fut # def postprocess_batch_depth(batch): # depths = np.array([[timepoint if timepoint is not None",
"feed_dict = { self.wm.states : batch[state_desc], self.wm.action : batch['action'], self.wm.obj_there : batch['obj_there'] }",
"{ self.wm.states : batch[self.state_desc], self.wm.action : batch['action'], self.wm.action_post : batch['action_post'] } if self.obj_there_supervision:",
"axis=0) feed_dict = { self.wm.states : batch[self.state_desc], self.wm.action : batch['action'], self.wm.action_post : batch['action_post']",
"self.map_draw_mode = None #Map drawing. Meant to have options, but for now just",
"height, width = updater_params['image_shape'] act_dim = updater_params['act_dim'] print('setting up save loc') self.hdf5 =",
"{'example_id' : idx, 'action_sample' : action, 'estimated_world_loss' : estimated_world_loss, # 'action_samples' : action_samples,",
"class ObjectThereUpdater: def __init__(self, world_model, uncertainty_model, data_provider, optimizer_params, learning_rate_params, postprocessor, updater_params): self.data_provider =",
"self.wm.readouts.items() if k not in self.wm.save_to_gfs}) self.targets.update({k : v for k, v in",
"= tf.int32)) self.targets = {} self.state_desc = updater_params.get('state_desc', 'depths1') if not freeze_wm: act_lr_params,",
"var_list = self.um.var_list) self.targets = {'global_step' : self.global_step, 'um_optimizer' : um_opt} assert set(self.wm.readouts.keys())",
"self.state_desc = updater_params.get('state_desc', 'depths1') if not freeze_wm: act_lr_params, act_lr = get_learning_rate(self.act_step, **learning_rate_params['world_model']['act_model']) fut_lr_params,",
"= um_lr self.targets['global_step'] = self.global_step global_increment = tf.assign_add(self.global_step, 1) um_increment = tf.assign_add(self.um.step, 1)",
"res, global_step class ActionUncertaintyUpdater: def __init__(self, models, data_provider, optimizer_params, learning_rate_params, postprocessor, updater_params): self.data_provider",
"self.wm.fut_loss, self.global_step, optimizer_params['world_model']['fut_model'], var_list = self.wm.fut_var_list) um_opt_params, um_opt = get_optimizer(um_lr, self.um.uncertainty_loss, self.global_step, optimizer_params['uncertainty_model'],",
"um_opt = get_optimizer(um_lr, self.um.uncertainty_loss, self.global_step, optimizer_params['uncertainty_model']) self.targets = {'um_loss' : self.um.uncertainty_loss, 'um_optimizer' :",
"obs, msg, act = batch prepped = {} depths = replace_the_nones(obs[state_desc]) depths_past =",
"'obj_there': res['batch'][desc] = val elif desc != 'recent': res['batch'][desc] = val[:, -1] res['recent']",
"1) self.targets.update({'global_increment' : global_increment, 'um_increment' : um_increment}) self.targets.update(self.wm.readouts) self.targets.update(self.um.readouts) assert set(self.wm.readouts.keys()) != set(self.um.readouts.keys())",
"# return prepped['depths1'], prepped['objects1'], actions, action_ids, next_depths class ExperienceReplayPostprocessor: def __init__(self, big_save_keys =",
"self.map_draw_mode == 'specified_indices' and self.action_sampler is not None, (self.map_draw_mode, action_sampler) #self.map_draw_example_indices = updater_params['map_draw_example_indices']",
"act_dim), dtype = np.float32), 'action_post' : hdf5.require_dataset('action_post', shape = (N, act_dim), dtype =",
"'prediction' : self.world_model.pred, 'tv' : self.world_model.tv} self.inc_step = self.global_step.assign_add(1) self.um_lr_params, um_learning_rate = get_learning_rate(self.global_step,",
"mean_per_provider return res class UncertaintyPostprocessor: def __init__(self, big_save_keys = None, little_save_keys = None,",
"self.wm.act_var_list + self.wm.encode_var_list) fut_opt_params, fut_opt = get_optimizer(fut_lr, self.wm.fut_loss, self.global_step, optimizer_params['world_model']['fut_model'], var_list = self.wm.fut_var_list)",
"{'encoding_i' : self.wm.encoding_i, 'encoding_f' : self.wm.encoding_f, 'fut_pred' : self.wm.fut_pred, 'act_pred' : self.wm.act_pred, 'act_optimizer'",
"tf.int32, initializer = tf.constant_initializer(0, dtype = tf.int32)) print(learning_rate_params.keys()) um_lr_params, um_lr = get_learning_rate(self.global_step, **learning_rate_params['uncertainty_model'])",
"if not freeze_wm: num_not_frozen += 1 act_opt_params, act_opt = get_optimizer(act_lr, self.wm.act_loss, self.global_step, optimizer_params['world_model']['act_model'],",
"get_learning_rate(self.fut_step, **learning_rate_params['world_model']['fut_model']) act_opt_params, act_opt = get_optimizer(act_lr, self.wm.act_loss, self.act_step, optimizer_params['world_model']['act_model'], var_list = self.wm.act_var_list +",
"== 0: # if self.map_draw_mode == 'specified_indices': # map_draw_res = [] # for",
"to have options, but for now just assuming one sort of specification #self.state_desc",
"glstep class LatentUncertaintyUpdater: def __init__(self, world_model, uncertainty_model, data_provider, optimizer_params, learning_rate_params, postprocessor, updater_params =",
"np.mean(looking_at_obj) elif type(batch['recent']) == list and len(batch['recent'][0]) > 0: mean_per_provider = [] for",
"batch ['action_post'] } if self.insert_objthere: feed_dict[self.wm.obj_there_via_msg] = batch['obj_there'] res = sess.run(self.targets, feed_dict =",
"world_model_res['given'][0, 1] / 4.) cv2.waitKey(1) print('wm loss: ' + str(world_model_res['loss'])) um_feed_dict = {",
"is not None else np.zeros(obs[desc][-1].shape, dtype = obs[desc][-1].dtype) for timepoint in obs[desc]] for",
"batch['other']] #action_sample = [other[2] for other in batch['other']] res['batch'] = {} for desc,",
"'oh_my_god' : self.um.oh_my_god, 'model_parameters' : self.um.var_list} def update(self, sess): batch = self.dp.dequeue_batch() feed_dict",
"self.targets = {} self.state_desc = updater_params.get('state_desc', 'depths1') if not freeze_wm: num_not_frozen += 1",
"!= set(self.um.readouts.keys()) self.targets.update(self.wm.readouts) self.targets.update(self.um.readouts) um_increment = tf.assign_add(self.um.step, 1) assert 'um_increment' not in self.targets",
"updater_params, action_sampler = None): self.data_provider = data_provider \\ if isinstance(data_provider, list) else [data_provider]",
": um_lr, 'um_optimizer' : um_opt, 'global_step' : self.global_step, 'loss_per_example' : self.um.true_loss, 'estimated_world_loss' :",
"action_samples = self.action_sampler.sample_actions() # action, entropy, estimated_world_loss = self.um.act(sess, action_samples, obs_for_actor) # to_add",
"self.targets = {} self.targets.update({k : v for k, v in self.wm.readouts.items() if k",
"batch[k] = np.concatenate(batch[k], axis=0) feed_dict = { self.wm.states : batch[self.state_desc], self.wm.action : batch['action'],",
"feed_dict) res = self.postprocessor.postprocess(res, batch) return res class DebuggingForceMagUpdater: def __init__(self, models, data_provider,",
"world_model self.um = uncertainty_model self.global_step = tf.get_variable('global_step', [], tf.int32, initializer = tf.constant_initializer(0,dtype =",
"self.wm.action : batch['action'], self.wm.action_post : batch['action_post'] } if self.obj_there_supervision: batch['obj_there'] = np.concatenate(batch['obj_there'], axis",
": self.wm.fut_pred, 'act_pred' : self.wm.act_pred, # 'fut_loss' : self.wm.fut_loss, 'act_loss' : self.wm.act_loss, #",
"dtype = np.uint8), 'action' : hdf5.require_dataset('action', shape = (N, act_dim), dtype = np.float32),",
": self.um.true_loss}) self.map_draw_mode = None #Map drawing. Meant to have options, but for",
"start(self, sess): self.data_provider.start_runner(sess) sess.run(tf.global_variables_initializer()) def update(self, sess, visualize = False): batch = self.data_provider.dequeue_batch()",
"feed_dict = feed_dict) res = self.postprocessor.postprocess(res, batch) return res class UncertaintyUpdater: def __init__(self,",
"postprocessor): self.data_provider = data_provider self.world_model = world_model self.um = uncertainty_model self.global_step = tf.get_variable('global_step',",
"um = models['uncertainty_model'] self.wm = wm = models['world_model'] self.targets = {'act_pred' : self.wm.act_pred,",
"self.data_provider = data_provider fn = updater_params['hdf5_filename'] N = updater_params['N_save'] height, width = updater_params['image_shape']",
"where we can put parallelization. Not finished! ''' def __init__(world_model, rl_model, data_provider, eta):",
"= data_provider def run(self, sess): batch = self.dp.dequeue_batch() feed_dict = { self.wm.states :",
"res.update(dict((k, v) for (k, v) in training_results.iteritems() if k in save_keys)) #res['msg'] =",
"= tf.int32)) self.act_step = tf.get_variable('act_step', [], tf.int32, initializer = tf.constant_initializer(0,dtype = tf.int32)) self.fut_step",
"action_sampler) self.map_draw_example_indices = updater_params['map_draw_example_indices'] self.map_draw_timestep_indices = updater_params['map_draw_timestep_indices'] self.map_draw_freq = updater_params['map_draw_freq'] def update(self, sess,",
"__init__(self, world_model, uncertainty_model, data_provider, optimizer_params, learning_rate_params, postprocessor): self.data_provider = data_provider self.world_model = world_model",
"self.wm.encode_var_list) fut_opt_params, fut_opt = get_optimizer(fut_lr, self.wm.fut_loss, self.global_step, optimizer_params['world_model']['fut_model'], var_list = self.wm.fut_var_list) um_opt_params, um_opt",
"state_desc = 'depths1' #depths, actions, actions_post, next_depth = postprocess_batch_depth(batch, state_desc) feed_dict = {",
"4.)#TODO clean up w colors cv2.imshow('tv', world_model_res['tv'][0] / 4.) cv2.imshow('processed0', world_model_res['given'][0, 0] /",
"sess): batch = self.dp.dequeue_batch() feed_dict = { self.wm.states : batch['depths1'], self.wm.action : batch['action'],",
"= self.little_save_keys res.update(dict(pair for pair in training_results.iteritems() if pair[0] in save_keys)) #if 'other'",
"0 for msg in batch['recent']['msg']] res['obj_freq'] = np.mean(looking_at_obj) elif type(batch['recent']) == list and",
"self.um.uncertainty_loss, 'estimated_world_loss' : self.um.estimated_world_loss, 'loss_per_example' : self.um.true_loss, 'act_loss_per_example' : self.wm.act_loss_per_example } self.dp =",
"self.world_model.action.get_shape().as_list()[1] def start(self, sess): self.data_provider.start_runner(sess) sess.run(tf.global_variables_initializer()) def update(self, sess, visualize = False): batch",
": self.wm.act_pred, 'act_loss' : self.wm.act_loss, 'estimated_world_loss' : self.um.estimated_world_loss, 'um_loss' : self.um.uncertainty_loss, 'loss_per_example' :",
"[other[2] for other in batch['recent']['other']] res['batch'] = {'obs' : batch['depths1'], 'act' : batch['action'],",
"tf.get_variable('act_step', [], tf.int32, initializer = tf.constant_initializer(0,dtype = tf.int32)) self.fut_step = tf.get_variable('fut_step', [], tf.int32,",
"um_lr = get_learning_rate(self.global_step, ** learning_rate_params['uncertainty_model']) um_opt_params, um_opt = get_optimizer(um_lr, self.um.uncertainty_loss, self.global_step, optimizer_params['uncertainty_model'], var_list",
"} um_res = sess.run(self.um_targets, feed_dict = um_feed_dict) wm_res_new = dict(('wm_' + k, v)",
"entropy = -tf.reduce_sum(prob_tf * log_prob_tf) self.rl_loss = pi_loss + 0.5 * vf_loss -",
": depths, self.world_model.s_f : next_depth, self.world_model.action : actions, self.world_model.action_id : action_ids, self.world_model.objects :",
"'act_loss' : self.wm.act_loss, 'estimated_world_loss' : self.um.estimated_world_loss } self.targets.update({'um_loss' : self.um.uncertainty_loss, 'um_lr' : um_lr,",
"self.fut_step, optimizer_params['world_model']['fut_model'], var_list = self.wm.fut_var_list) self.targets['act_opt'] = act_opt self.targets['fut_opt'] = fut_opt self.targets['act_lr'] =",
": self.global_step, 'loss_per_example' : self.um.true_loss, 'estimated_world_loss' : self.um.estimated_world_loss } self.state_desc = updater_params['state_desc'] def",
": idx, 'action_sample' : action, 'estimated_world_loss' : estimated_world_loss, # 'action_samples' : action_samples, 'depths1'",
"= get_optimizer(act_lr, self.wm.act_loss, self.act_step, optimizer_params['world_model']['act_model'], var_list = self.wm.act_var_list + self.wm.encode_var_list) fut_opt_params, fut_opt =",
"um_opt_params, um_opt = get_optimizer(um_lr, self.um.uncertainty_loss, self.global_step, optimizer_params['uncertainty_model'], var_list = self.um.var_list) self.targets['um_opt'] = um_opt",
"batch.iteritems(): if desc not in ['recent', 'depths1', 'objects1', 'images1']: res['batch'][desc] = val res['recent']",
"log_prob_tf) self.rl_loss = pi_loss + 0.5 * vf_loss - entropy * 0.01 rl_opt_params,",
"self.targets['um_opt'] = um_opt self.targets['um_lr'] = um_lr self.targets['global_step'] = self.global_step global_increment = tf.assign_add(self.global_step, 1)",
"val elif desc != 'recent': res['batch'][desc] = val[:, -1] res['recent'] = batch['recent'] class",
"res class ObjectThereUpdater: def __init__(self, world_model, uncertainty_model, data_provider, optimizer_params, learning_rate_params, postprocessor, updater_params): self.data_provider",
"self.state_desc = updater_params['state_desc'] def update(self, sess, visualize = False): batch = self.data_provider.dequeue_batch() state_desc",
"dt = h5py.special_dtype(vlen = str) self.handles = {'msg' : hdf5.require_dataset('msg', shape = (N,),",
": batch['action_post'] } if self.obj_there_supervision: batch['obj_there'] = np.concatenate(batch['obj_there'], axis = 0) feed_dict[self.wm.obj_there_via_msg] =",
"shape = (N, height, width, 3), dtype = np.uint8), 'objects1' : hdf5.require_dataset('objects1', shape",
"idx = -10000#just something that's not an id seen action_ids_list.append(idx) action_ids = np.array([action_ids_list])",
"tf.int32, initializer = tf.constant_initializer(0,dtype = tf.int32)) self.act_lr_params, act_lr = get_learning_rate(self.global_step, ** learning_rate_params['world_model']['act_model']) self.fut_lr_params,",
"= sess.run(self.targets, feed_dict = feed_dict) res.pop('um_increment') global_step = res['global_step'] #if self.map_draw_mode is not",
"res = sess.run(self.targets, feed_dict = feed_dict) glstep = res['global_step'] res = self.postprocessor.postprocess(res, batch)",
"np.array([depths[:-1]]) depths_fut = np.array([depths[:1]]) objects = np.array([replace_the_nones(obs[state_desc])[:-1]]) actions = np.array([replace_the_nones(act)]) action_ids_list = []",
": um_lr, 'um_optimizer' : um_opt, # 'global_step' : self.global_step, 'loss_per_example' : self.um.true_loss}) self.map_draw_mode",
"len(action_msg): idx = int(action_msg[0]['id']) else: idx = -10000#just something that's not an id",
"act_lr, 'fut_lr' : fut_lr, 'fut_loss' : self.wm.fut_loss, 'act_loss' : self.wm.act_loss, 'estimated_world_loss' : self.um.estimated_world_loss",
"tf.get_variable('global_step', [], tf.int32, initializer = tf.constant_initializer(0,dtype = tf.int32)) self.act_lr_params, act_lr = get_learning_rate(self.global_step, **",
"= data_provider \\ if isinstance(data_provider, list) else [data_provider] self.wm = models['world_model'] self.um =",
"batch['action_post'] } if self.um.insert_obj_there: print('adding obj_there to feed dict') feed_dict[self.um.obj_there] = batch['obj_there'] res",
"self.targets['act_opt'] = act_opt self.targets['fut_opt'] = fut_opt self.targets['act_lr'] = act_lr self.targets['fut_lr'] = fut_lr if",
"ActionUncertaintyUpdater: def __init__(self, models, data_provider, optimizer_params, learning_rate_params, postprocessor, updater_params): self.data_provider = data_provider \\",
"= mean_per_provider return res class UncertaintyPostprocessor: def __init__(self, big_save_keys = None, little_save_keys =",
"on there being just one obs type self.state_desc = data_provider.data_lengths['obs'].keys()[0] self.insert_objthere = False",
"action_msg = batch.next_state['msg'][i]['msg']['actions'] if batch.next_state['msg'][i] is not None else [] # if len(action_msg):",
"SquareForceMagUpdater: def __init__(self, models, data_provider, optimizer_params, learning_rate_params, postprocessor, updater_params): self.dp = data_provider self.wm",
"i in range(2): action_msg = msg[i]['msg']['actions'] if msg[i] is not None else []",
"um_lr = get_learning_rate(self.um_step, **learning_rate_params['uncertainty_model']) um_opt_params, um_opt = get_optimizer(um_lr, self.um.uncertainty_loss, self.um_step, optimizer_params['uncertainty_model'], var_list =",
"self.um.true_loss, 'global_step' : self.global_step} def update(self, sess, visualize = False): batch = {}",
"self.targets['act_lr'] = act_lr self.targets['fut_lr'] = fut_lr if not freeze_um: um_lr_params, um_lr = get_learning_rate(self.um_step,",
"'um_increment' : um_increment}) self.targets.update(self.wm.readouts) self.targets.update(self.um.readouts) assert set(self.wm.readouts.keys()) != set(self.um.readouts.keys()) def update(self, sess, visualize",
"width, 3), dtype = np.uint8), 'images1': hdf5.require_dataset('images1', shape = (N, height, width, 3),",
"res class LatentFreezeUpdater: def __init__(self, models, data_provider, optimizer_params, learning_rate_params, postprocessor, updater_params): self.data_provider =",
"self.wm.act_pred, 'act_optimizer' : act_opt, 'fut_optimizer' : fut_opt, 'act_lr' : act_lr, 'fut_lr' : fut_lr,",
"um_res_new = dict(('um_' + k, v) for k, v in um_res.iteritems()) wm_res_new.update(um_res_new) res",
"} res = sess.run(self.targets, feed_dict = feed_dict) res['batch'] = batch return res class",
": batch[self.state_desc], self.wm.action : batch['action'], self.wm.action_post : batch['action_post'] } if self.obj_there_supervision: batch['obj_there'] =",
"'um_lr' : um_lr}) assert set(self.wm.readouts.keys()) != set(self.um.readouts.keys()) self.targets.update(self.wm.readouts) self.targets.update(self.um.readouts) um_increment = tf.assign_add(self.um.step, 1)",
": v for k, v in self.um.readouts.items() if k not in self.um.save_to_gfs}) #this",
"tf.nn.softmax(rl_model.logits) pi_loss = -tf.reduce_sum(tf.reduce_sum(log_prob_tf * self.ac, [1]) * self.adv) vf_loss = .5 *",
"['action', 'action_post', 'depths1']: batch[k] = np.concatenate(batch[k], axis=0) state_desc = 'depths1' #depths, actions, actions_post,",
"json class RawDepthDiscreteActionUpdater: ''' Provides the training step. This is probably where we",
"[], tf.int32, initializer = tf.constant_initializer(0,dtype = tf.int32)) self.act_lr_params, act_lr = get_learning_rate(self.global_step, ** learning_rate_params['world_model']['act_model'])",
"self.wm.act_pred, 'act_loss' : self.wm.act_loss, 'act_optimizer' : act_opt, 'um_optimizer' : um_opt, 'estimated_world_loss' : self.um.estimated_world_loss,",
"self.postprocessor.postprocess(res, batch) return res class SquareForceMagUpdater: def __init__(self, models, data_provider, optimizer_params, learning_rate_params, postprocessor,",
"i, dp in enumerate(self.data_provider): provider_batch = dp.dequeue_batch() for k in provider_batch: if k",
"get_optimizer(um_lr, self.um.uncertainty_loss, self.global_step, optimizer_params['uncertainty_model'], var_list = self.um.var_list) self.global_step = self.global_step / 2 self.targets",
"= sess.run(self.world_model_targets, feed_dict = wm_feed_dict) um_feed_dict = { self.um.s_i : batch[state_desc][:, :-1], self.um.action_sample",
"batch[k].append(provider_batch[k]) else: batch[k] = [provider_batch[k]] for k in ['action', 'action_post', self.state_desc]: batch[k] =",
"um_lr = get_learning_rate(self.global_step, **learning_rate_params['uncertainty_model']) um_opt_params, um_opt = get_optimizer(um_lr, self.um.uncertainty_loss, self.global_step, optimizer_params['uncertainty_model']) self.targets =",
"estimated_world_loss = self.um.act(sess, action_samples, obs_for_actor) to_add = {'example_id' : idx, 'action_sample' : action,",
"def update(self, sess, visualize = False): batch = self.dp.dequeue_batch() state_desc = self.state_desc feed_dict",
"visualize: cv2.imshow('pred', world_model_res['prediction'][0] / 4.)#TODO clean up w colors cv2.imshow('tv', world_model_res['tv'][0] / 4.)",
"other in batch['recent']['other']] res['batch'] = {'obs' : batch['depths1'], 'act' : batch['action'], 'act_post' :",
"= np.array([batch.next_state['depths1']]) # return depths, actions, next_depth def postprocess_batch_for_actionmap(batch, state_desc): obs, msg, act",
"v) for k, v in world_model_res.iteritems()) um_res_new = dict(('um_' + k, v) for",
"self.world_model.pred, 'tv' : self.world_model.tv} self.inc_step = self.global_step.assign_add(1) self.wm_lr_params, um_learning_rate = get_learning_rate(self.global_step, **learning_rate_params['uncertainty_model']) self.wm_lr_params,",
"= np.concatenate(batch[k], axis=0) feed_dict = { self.wm.states : batch[self.state_desc], self.wm.action : batch['action'], self.wm.action_post",
"set(self.um.readouts.keys()) self.targets.update(self.wm.readouts) self.targets.update(self.um.readouts) #self.targets = { # 'fut_pred' : self.wm.fut_pred, 'act_pred' : self.wm.act_pred,",
"loc') self.hdf5 = hdf5 = h5py.File(fn, mode = 'a') dt = h5py.special_dtype(vlen =",
"3), dtype = np.uint8), 'action' : hdf5.require_dataset('action', shape = (N, act_dim), dtype =",
": self.wm.act_loss, 'act_optimizer' : act_opt, 'um_optimizer' : um_opt, 'estimated_world_loss' : self.um.estimated_world_loss, 'um_loss' :",
"world_model_res = sess.run(self.world_model_targets, feed_dict = wm_feed_dict) um_feed_dict = { self.um.s_i : batch[state_desc][:, :-1],",
"0] / 4.) cv2.imshow('processed1', world_model_res['given'][0, 1] / 4.) cv2.waitKey(1) print('wm loss: ' +",
"'objects1', 'images1']: res['batch'][desc] = val res['recent'] = batch['recent'] else: save_keys = self.little_save_keys res.update(dict(pair",
"not None else np.zeros(obs['depths1'][-1].shape, dtype = obs['depths1'][-1].dtype) for timepoint in obs['depths1']] for obs",
"else 0 for msg in provider_recent['msg']] mean_per_provider.append(np.mean(looking_at_obj)) res['obj_freq'] = np.mean(mean_per_provider) res['obj_freq_per_provider_noprint'] = mean_per_provider",
"dtype = obs['depths1'][-1].dtype) for timepoint in obs['depths1']] for obs in batch.states]) # actions",
": fut_opt, 'act_lr' : act_lr, 'fut_lr' : fut_lr, 'fut_loss' : self.wm.fut_loss, 'act_loss' :",
"{'given' : self.world_model.processed_input, 'loss' : self.world_model.loss, 'loss_per_example' : self.world_model.loss_per_example, 'learning_rate' : wm_learning_rate, 'optimizer'",
"rl_model self.eta = eta self.global_step = tf.get_variable('global_step', [], tf.int32, initializer = tf.constant_initializer(0,dtype =",
"''' return [np.zeros(my_list[-1].shape, dtype = my_list[-1].dtype) if elt is None else elt for",
"my_list[-1].dtype) if elt is None else elt for elt in my_list] def postprocess_batch_depth(batch,",
"vf_loss - entropy * 0.01 rl_opt_params, rl_opt = get_optimizer(learning_rate, self.rl_loss, ) def replace_the_nones(my_list):",
"self.world_action_time = self.world_model.action.get_shape().as_list()[1] def start(self, sess): self.data_provider.start_runner(sess) sess.run(tf.global_variables_initializer()) def update(self, sess, visualize =",
"= [other[0] for other in batch['recent']['other']] entropies = np.mean(entropies) res['entropy'] = entropies looking_at_obj",
": self.world_model.pred, 'tv' : self.world_model.tv} self.inc_step = self.global_step.assign_add(1) self.um_lr_params, um_learning_rate = get_learning_rate(self.global_step, **learning_rate_params['uncertainty_model'])",
"feed_dict = feed_dict) res.pop('um_increment') global_step = res['global_step'] #if self.map_draw_mode is not None and",
"self.action = tf.placeholder = tf.placeholder(tf.float32, [None] + world_model.action_one_hot.get_shape().as_list()[1:]) self.adv = tf.placeholder(tf.float32, [None]) self.r",
"batch['recent']['other']] # entropies = np.mean(entropies) # res['entropy'] = entropies if 'msg' in batch['recent']:",
"sess): batch = self.dp.dequeue_batch() feed_dict = { self.wm.states : batch[self.state_desc], self.wm.action : batch['action'],",
"for msg in batch['recent']['msg']] res['obj_freq'] = np.mean(looking_at_obj) return res class DataWriteUpdater: def __init__(self,",
": self.global_step, 'um_optimizer' : um_opt} assert set(self.wm.readouts.keys()) != set(self.um.readouts.keys()) self.targets.update(self.wm.readouts) self.targets.update(self.um.readouts) #self.targets =",
"= self.dp.dequeue_batch() feed_dict = { self.wm.states : batch[self.state_desc], self.wm.action : batch['action'], self.wm.action_post :",
"ExperienceReplayPostprocessor: def __init__(self, big_save_keys = None, little_save_keys = None, big_save_len = None, big_save_freq",
"# 'action_samples' : action_samples, 'depths1' : batch[self.state_desc][idx], # 'action' : batch['action'][idx], 'action_post' :",
"def update(self, sess, visualize = False): batch = {} for i, dp in",
"wm_feed_dict) um_feed_dict = { self.um.s_i : batch[state_desc][:, :-1], self.um.action_sample : batch['action'][:, -1], self.um.true_loss",
"um_lr self.targets['global_step'] = self.global_step global_increment = tf.assign_add(self.global_step, 1) um_increment = tf.assign_add(self.um.step, 1) self.targets.update({'global_increment'",
"that we don't have repeat names def start(self, sess): self.data_provider.start_runner(sess) sess.run(tf.global_variables_initializer()) def update(self,",
"postprocess(self, training_results, batch): global_step = training_results['global_step'] res = {} if (global_step) % self.big_save_freq",
"self.wm.encoding_i, 'encoding_f' : self.wm.encoding_f, 'fut_pred' : self.wm.fut_pred, 'act_pred' : self.wm.act_pred, 'act_optimizer' : act_opt,",
"freeze_um: um_lr_params, um_lr = get_learning_rate(self.um_step, **learning_rate_params['uncertainty_model']) um_opt_params, um_opt = get_optimizer(um_lr, self.um.uncertainty_loss, self.um_step, optimizer_params['uncertainty_model'],",
"self.global_step = tf.get_variable('global_step', [], tf.int32, initializer = tf.constant_initializer(0,dtype = tf.int32)) self.action = tf.placeholder",
"'loss_per_example' : self.world_model.loss_per_example, 'learning_rate' : wm_learning_rate, 'optimizer' : wm_opt, 'prediction' : self.world_model.pred, 'tv'",
"update(self, sess): batch = self.dp.dequeue_batch() feed_dict = { self.wm.action : batch['action'], self.wm.action_post :",
"map_draw_res.append(to_add) #res['map_draw'] = map_draw_res return res class ObjectThereUpdater: def __init__(self, world_model, uncertainty_model, data_provider,",
"for now just assuming one sort of specification #self.state_desc = updater_params.get('state_desc', 'depths1') #self.map_draw_mode",
"to have options, but for now just assuming one sort of specification self.state_desc",
"'um_optimizer' : um_opt, 'global_step' : self.global_step, 'loss_per_example' : self.um.true_loss}) self.state_desc = updater_params['state_desc'] #checking",
"batch['action'][idx], 'action_post' : batch['action_post'][idx]} # map_draw_res.append(to_add) #res['map_draw'] = map_draw_res return res class ObjectThereUpdater:",
": self.global_step} def update(self, sess, visualize = False): batch = {} for i,",
"print('little time') save_keys = self.little_save_keys res.update(dict((k, v) for (k, v) in training_results.iteritems() if",
"= data_provider self.world_model = world_model self.um = uncertainty_model self.global_step = tf.get_variable('global_step', [], tf.int32,",
"tf.constant_initializer(0,dtype = tf.int32)) self.wm_lr_params, wm_learning_rate = get_learning_rate(self.global_step, ** learning_rate_params['world_model']) self.wm_opt_params, wm_opt = get_optimizer(wm_learning_rate,",
"[], tf.int32, initializer = tf.constant_initializer(0,dtype = tf.int32)) self.act_step = tf.get_variable('act_step', [], tf.int32, initializer",
"list and len(batch['recent'][0]) > 0: mean_per_provider = [] for provider_recent in batch['recent']: looking_at_obj",
"other in batch['recent']['other']] entropies = np.mean(entropies) res['entropy'] = entropies looking_at_obj = [1 if",
"batch['action'], self.wm.action_post : batch['action_post'] } if self.um.insert_obj_there: print('adding obj_there to feed dict') feed_dict[self.um.obj_there]",
"np.uint8), 'action' : hdf5.require_dataset('action', shape = (N, act_dim), dtype = np.float32), 'action_post' :",
"get_learning_rate(self.act_step, **learning_rate_params['world_model']['act_model']) fut_lr_params, fut_lr = get_learning_rate(self.fut_step, **learning_rate_params['world_model']['fut_model']) act_opt_params, act_opt = get_optimizer(act_lr, self.wm.act_loss, self.act_step,",
"['action', 'action_post', self.state_desc]: batch[k] = np.concatenate(batch[k], axis=0) feed_dict = { self.wm.states : batch[self.state_desc],",
"= map_draw_res res = self.postprocessor.postprocess(res, batch) return res, global_step class ActionUncertaintyUpdater: def __init__(self,",
"self.postprocessor = postprocessor self.global_step = tf.get_variable('global_step', [], tf.int32, initializer = tf.constant_initializer(0, dtype =",
"learning_rate_params, postprocessor, updater_params): self.data_provider = data_provider \\ if isinstance(data_provider, list) else [data_provider] self.wm",
"def postprocess(self, training_results, batch): global_step = training_results['global_step'] res = {} print('postprocessor deets') print(global_step)",
"if 'msg' in batch['recent']: looking_at_obj = [1 if msg is not None and",
"= updater_params['act_dim'] print('setting up save loc') self.hdf5 = hdf5 = h5py.File(fn, mode =",
"timepoint for timepoint in batch.next_state['action']]]) # print('actions shape') # print(actions.shape) # print(len(batch.next_state['action'])) #",
"self.world_model_targets = {'given' : self.world_model.processed_input, 'loss' : self.world_model.loss, 'learning_rate' : wm_learning_rate, 'optimizer' :",
"if self.map_draw_mode == 'specified_indices': # map_draw_res = [] # for idx in self.map_draw_example_indices:",
"not None else [] if len(action_msg): idx = int(action_msg[0]['id']) else: idx = -10000#just",
"= self.wm.act_var_list + self.wm.encode_var_list) fut_opt_params, fut_opt = get_optimizer(fut_lr, self.wm.fut_loss, self.fut_step, optimizer_params['world_model']['fut_model'], var_list =",
"#res['msg'] = batch['msg'][-1] entropies = [other[0] for other in batch['recent']['other']] entropies = np.mean(entropies)",
"'specified_indices' and self.action_sampler is not None, (self.map_draw_mode, action_sampler) self.map_draw_example_indices = updater_params['map_draw_example_indices'] self.map_draw_timestep_indices =",
"feed_dict) glstep = res['global_step'] res = self.postprocessor.postprocess(res, batch) return res, glstep class LatentUncertaintyUpdater:",
"obs_for_actor) # to_add = {'example_id' : idx, 'action_sample' : action, 'estimated_world_loss' : estimated_world_loss,",
"cv2.imshow('processed1', world_model_res['given'][0, 1] / 4.) cv2.waitKey(1) print('wm loss: ' + str(world_model_res['loss'])) um_feed_dict =",
"self.targets['fut_opt'] = fut_opt self.targets['act_lr'] = act_lr self.targets['fut_lr'] = fut_lr if not freeze_um: um_lr_params,",
"um_opt = get_optimizer(um_lr, self.um.uncertainty_loss, self.um_step, optimizer_params['uncertainty_model'], var_list = self.um.var_list) self.targets['um_opt'] = um_opt self.targets['um_lr']",
"self.global_step, optimizer_params['world_model']['act_model'], var_list = self.wm.act_var_list + self.wm.encode_var_list) fut_opt_params, fut_opt = get_optimizer(fut_lr, self.wm.fut_loss, self.global_step,",
"self.um.action_sample : actions[:, -1], self.um.true_loss : np.array([world_model_res['loss']]) } um_res = sess.run(self.um_targets, feed_dict =",
"tf.constant_initializer(0,dtype = tf.int32)) self.um_lr_params, um_lr = get_learning_rate(self.global_step, ** learning_rate_params['uncertainty_model']) um_opt_params, um_opt = get_optimizer(um_lr,",
"if elt is None else elt for elt in my_list] def postprocess_batch_depth(batch, state_desc):",
"obs[desc]] for obs in batch.states]) # actions = np.array([[np.zeros(batch.next_state['action'][-1].shape, batch.next_state['action'][-1].dtype) if timepoint is",
"self.targets.update({'um_loss' : self.um.uncertainty_loss, 'um_lr' : um_lr, 'um_optimizer' : um_opt, 'global_step' : self.global_step, 'loss_per_example'",
"each index because action sampling is the 'batch.' #self.action_sampler = action_sampler #assert self.map_draw_mode",
"mean_per_provider.append(np.mean(looking_at_obj)) res['obj_freq'] = np.mean(mean_per_provider) res['obj_freq_per_provider_noprint'] = mean_per_provider return res class UncertaintyPostprocessor: def __init__(self,",
"get_optimizer(um_lr, self.um.uncertainty_loss, self.global_step, optimizer_params['uncertainty_model'], var_list = self.um.var_list) self.targets = {'global_step' : self.global_step, 'um_optimizer'",
"self.world_model.loss, 'loss_per_example' : self.world_model.loss_per_example, 'learning_rate' : wm_learning_rate, 'optimizer' : wm_opt, 'prediction' : self.world_model.pred,",
"wm_res_new.update(um_res_new) res = wm_res_new res['global_step'] = res.pop('um_global_step') res = self.postprocessor.postprocess(wm_res_new, batch) return res",
"sess.run(self.targets, feed_dict = feed_dict) res = self.postprocessor.postprocess(res, batch) return res class UncertaintyUpdater: def",
"return res, global_step class FreezeUpdater: def __init__(self, models, data_provider, optimizer_params, learning_rate_params, postprocessor, updater_params):",
"[None]) self.r = tf.placeholder(tf.float32, [None]) log_prob_tf = tf.nn.log_softmax(rl_model.logits) prob_tf = tf.nn.softmax(rl_model.logits) pi_loss =",
": wm_opt, 'prediction' : self.world_model.pred, 'tv' : self.world_model.tv} self.inc_step = self.global_step.assign_add(1) self.um_lr_params, um_learning_rate",
"+ self.wm.encode_var_list) fut_opt_params, fut_opt = get_optimizer(fut_lr, self.wm.fut_loss, self.global_step, optimizer_params['world_model']['fut_model'], var_list = self.wm.fut_var_list) um_opt_params,",
"= self.postprocessor.postprocess(res, batch) return res class LatentFreezeUpdater: def __init__(self, models, data_provider, optimizer_params, learning_rate_params,",
"feed_dict) global_step = res['global_step'] if self.map_draw_mode is not None and global_step % self.map_draw_freq",
"'depths1' : batch[self.state_desc][idx], # 'action' : batch['action'][idx], 'action_post' : batch['action_post'][idx]} # map_draw_res.append(to_add) #res['map_draw']",
"example indices for which we do a forward pass. #need to do one",
"# } #self.targets.update({'um_loss' : self.um.uncertainty_loss, 'um_lr' : um_lr, 'um_optimizer' : um_opt, # 'global_step'",
"curiosity.interaction import models import h5py import json class RawDepthDiscreteActionUpdater: ''' Provides the training",
"just one obs type self.state_desc = data_provider.data_lengths['obs'].keys()[0] self.insert_objthere = False if data_provider.num_objthere is",
"print(desc) if desc == 'obj_there': res['batch'][desc] = val elif desc != 'recent': res['batch'][desc]",
"self.targets.update(self.um.readouts) um_increment = tf.assign_add(self.um.step, 1) assert 'um_increment' not in self.targets self.targets['um_increment'] = um_increment",
"= tf.int32)) self.um_lr_params, um_lr = get_learning_rate(self.global_step, ** learning_rate_params['uncertainty_model']) um_opt_params, um_opt = get_optimizer(um_lr, self.um.uncertainty_loss,",
"'fut_lr' : fut_lr, 'fut_loss' : self.wm.fut_loss, 'act_loss' : self.wm.act_loss, 'estimated_world_loss' : self.um.estimated_world_loss }",
"= len(batch['recent']['msg']) end = self.start + bs for k in ['depths1', 'objects1', 'images1',",
"for i in range(2): # action_msg = batch.next_state['msg'][i]['msg']['actions'] if batch.next_state['msg'][i] is not None",
"self.global_step, 'loss_per_example' : self.um.true_loss, 'estimated_world_loss' : self.um.estimated_world_loss, 'ans' : self.um.ans, 'oh_my_god' : self.um.oh_my_god,",
"self.um.uncertainty_loss, self.global_step, optimizer_params['uncertainty_model'], var_list = self.um.var_list) self.targets['um_opt'] = um_opt if num_not_frozen == 0:",
"clean up w colors cv2.imshow('tv', world_model_res['tv'][0] / 4.) cv2.imshow('processed0', world_model_res['given'][0, 0] / 4.)",
"batch['action_post'] } self.targets['global_step'] = self.global_step res = sess.run(self.targets, feed_dict = feed_dict) glstep =",
"desc == 'obj_there': res['batch'][desc] = val elif desc != 'recent': res['batch'][desc] = val[:,",
": est_losses, 'action_sample' : action_sample} res['msg'] = batch['recent']['msg'] else: print('little time') save_keys =",
"to_add = {'example_id' : idx, 'action_sample' : action, 'estimated_world_loss' : estimated_world_loss, # 'action_samples'",
"self.um.oh_my_god self.state_desc = updater_params['state_desc'] def update(self, sess, visualize = False): batch = self.dp.dequeue_batch()",
"== 'OBJ_ACT' else 0 for msg in provider_recent['msg']] mean_per_provider.append(np.mean(looking_at_obj)) res['obj_freq'] = np.mean(mean_per_provider) res['obj_freq_per_provider_noprint']",
"str) self.handles = {'msg' : hdf5.require_dataset('msg', shape = (N,), dtype = dt), 'depths1'",
"self.wm.act_loss, self.global_step, optimizer_params['world_model']['act_model'], var_list = self.wm.act_var_list + self.wm.encode_var_list) um_opt_params, um_opt = get_optimizer(um_lr, self.um.uncertainty_loss,",
"res['msg'] = batch['recent']['msg'] else: print('little time') save_keys = self.little_save_keys res.update(dict((k, v) for (k,",
"one sort of specification #self.state_desc = updater_params.get('state_desc', 'depths1') #self.map_draw_mode = updater_params['map_draw_mode'] #this specification",
"self.targets = {'um_loss' : self.um.uncertainty_loss, 'um_optimizer' : um_opt, 'global_step' : self.global_step, 'loss_per_example' :",
"tf.constant_initializer(0,dtype = tf.int32)) self.um_step = tf.get_variable('ext_uncertainty_step', [], tf.int32, initializer = tf.constant_initializer(0,dtype = tf.int32))",
"entropies = np.mean(entropies) # res['entropy'] = entropies if 'msg' in batch['recent']: looking_at_obj =",
"actions = np.array([replace_the_nones(act)]) action_ids_list = [] for i in range(2): action_msg = msg[i]['msg']['actions']",
"entropies = [other[0] for other in batch['recent']['other']] entropies = np.mean(entropies) res['entropy'] = entropies",
"batch: batch[k].append(provider_batch[k]) else: batch[k] = [provider_batch[k]] for k in ['action', 'action_post', 'depths1']: batch[k]",
"because action sampling is the 'batch.' #self.action_sampler = action_sampler #assert self.map_draw_mode == 'specified_indices'",
"= wm = models['world_model'] self.targets = {'act_pred' : self.wm.act_pred, 'act_loss' : self.wm.act_loss, 'estimated_world_loss'",
"{ self.wm.states : batch['depths1'], self.wm.action : batch['action'], self.wm.action_post : batch['action_post'] } res =",
"= np.array([action_ids_list]) # next_depths = np.array([batch.next_state['depths1']]) # return prepped['depths1'], prepped['objects1'], actions, action_ids, next_depths",
"} res = sess.run(self.targets, feed_dict = feed_dict) res.pop('um_increment') res.pop('global_increment') global_step = res['global_step'] #if",
"if self.um.just_random: print('Selecting action at random') batch = {} for i, dp in",
": batch['action_post'], self.wm.obj_there : batch['obj_there'] } res = sess.run(self.targets, feed_dict = feed_dict) res['batch']",
": next_depth, self.world_model.action : actions, self.world_model.action_id : action_ids, self.world_model.objects : objects } world_model_res",
"timepoint is not None else np.zeros(obs['depths1'][-1].shape, dtype = obs['depths1'][-1].dtype) for timepoint in obs['depths1']]",
"% self.map_draw_freq == 0: if self.map_draw_mode == 'specified_indices': map_draw_res = [] for idx",
"/ 4.) cv2.waitKey(1) print('wm loss: ' + str(world_model_res['loss'])) um_feed_dict = { self.um.s_i :",
"= None, state_descriptor = None): self.big_save_keys = big_save_keys self.little_save_keys = little_save_keys self.big_save_len =",
"self.handles[k][self.start : end] = batch['recent'][k] self.handles['msg'][self.start : end] = [json.dumps(msg) for msg in",
"res['global_step'] if self.map_draw_mode is not None and global_step % self.map_draw_freq == 0: if",
"np.concatenate(batch[k], axis=0) state_desc = 'depths1' #depths, actions, actions_post, next_depth = postprocess_batch_depth(batch, state_desc) feed_dict",
"fut_opt_params, fut_opt = get_optimizer(fut_lr, self.wm.fut_loss, self.global_step, optimizer_params['world_model']['fut_model'], var_list = self.wm.fut_var_list) um_opt_params, um_opt =",
": self.wm.act_loss_per_example } self.dp = data_provider def run(self, sess): batch = self.dp.dequeue_batch() feed_dict",
"= get_learning_rate(self.global_step, ** learning_rate_params['uncertainty_model']) act_opt_params, act_opt = get_optimizer(act_lr, self.wm.act_loss, self.global_step, optimizer_params['world_model']['act_model'], var_list =",
"3), dtype = np.uint8), 'objects1' : hdf5.require_dataset('objects1', shape = (N, height, width, 3),",
"freeze_wm: act_lr_params, act_lr = get_learning_rate(self.act_step, **learning_rate_params['world_model']['act_model']) fut_lr_params, fut_lr = get_learning_rate(self.fut_step, **learning_rate_params['world_model']['fut_model']) act_opt_params, act_opt",
"= self.um.act(sess, action_samples, obs_for_actor) # to_add = {'example_id' : idx, 'action_sample' : action,",
"** learning_rate_params['world_model']['fut_model']) self.um_lr_params, um_lr = get_learning_rate(self.global_step, ** learning_rate_params['uncertainty_model']) act_opt_params, act_opt = get_optimizer(act_lr, self.wm.act_loss,",
"obs in batch.states]) # actions = np.array([[np.zeros(batch.next_state['action'][-1].shape, batch.next_state['action'][-1].dtype) if timepoint is None else",
"# res['map_draw'] = map_draw_res res = self.postprocessor.postprocess(res, batch) return res, global_step class JustUncertaintyUpdater:",
"def __init__(self, model, data_provider): self.dp = data_provider self.wm = model['world_model'] self.um = model['uncertainty_model']",
"tf.int32, initializer = tf.constant_initializer(0,dtype = tf.int32)) self.act_step = tf.get_variable('act_step', [], tf.int32, initializer =",
"self.postprocessor.postprocess(res, batch) return res class UncertaintyUpdater: def __init__(self, world_model, uncertainty_model, data_provider, optimizer_params, learning_rate_params,",
"feed_dict = { self.wm.states : batch[state_desc], self.wm.action : batch['action'], self.wm.action_post : batch['action_post'] }",
"data_provider self.wm = models['world_model'] self.um = models['uncertainty_model'] self.postprocessor = postprocessor self.global_step = tf.get_variable('global_step',",
"res = sess.run(self.targets, feed_dict = feed_dict) res.pop('um_increment') global_step = res['global_step'] #if self.map_draw_mode is",
"{'um_loss' : self.um.uncertainty_loss, 'um_optimizer' : um_opt, 'global_step' : self.global_step, 'loss_per_example' : self.um.true_loss, 'estimated_world_loss'",
"'OBJ_ACT' else 0 for msg in batch['recent']['msg']] res['obj_freq'] = np.mean(looking_at_obj) elif type(batch['recent']) ==",
"optimizer_params, learning_rate_params, postprocessor, updater_params): self.data_provider = data_provider \\ if isinstance(data_provider, list) else [data_provider]",
"an online data provider, set to do nothing self.map_draw_mode = 'specified_indices' #relies on",
"fut_lr_params, fut_lr = get_learning_rate(self.fut_step, **learning_rate_params['world_model']['fut_model']) act_opt_params, act_opt = get_optimizer(act_lr, self.wm.act_loss, self.act_step, optimizer_params['world_model']['act_model'], var_list",
"get_learning_rate(self.global_step, ** learning_rate_params['uncertainty_model']) act_opt_params, act_opt = get_optimizer(act_lr, self.wm.act_loss, self.global_step, optimizer_params['world_model']['act_model'], var_list = self.wm.act_var_list",
"tf.placeholder = tf.placeholder(tf.float32, [None] + world_model.action_one_hot.get_shape().as_list()[1:]) self.adv = tf.placeholder(tf.float32, [None]) self.r = tf.placeholder(tf.float32,",
"= self.data_provider.dequeue_batch() state_desc = self.state_desc feed_dict = { self.wm.states : batch[state_desc], self.wm.action :",
"# 'global_step' : self.global_step, 'loss_per_example' : self.um.true_loss}) self.map_draw_mode = None #Map drawing. Meant",
"return depths_past, objects, actions, action_ids, depths_fut # def postprocess_batch_for_actionmap(batch): # prepped = {}",
"'act_post' : batch['action_post'], 'est_loss' : est_losses, 'action_sample' : action_sample} res['msg'] = batch['recent']['msg'] else:",
"big_save_freq = None, state_descriptor = None): self.big_save_keys = big_save_keys self.little_save_keys = little_save_keys self.big_save_len",
"self.targets['oh_my_god'] = self.um.oh_my_god self.state_desc = updater_params['state_desc'] def update(self, sess, visualize = False): batch",
"if len(action_msg): # idx = int(action_msg[0]['id']) # action_ids_list.append(idx) # action_ids = np.array([action_ids_list]) #",
"numpy as np import cv2 from curiosity.interaction import models import h5py import json",
"one sort of specification self.state_desc = updater_params.get('state_desc', 'depths1') self.map_draw_mode = updater_params['map_draw_mode'] #this specification",
"model['world_model'] self.um = model['uncertainty_model'] self.targets = {} self.targets.update({k : v for k, v",
"self.um.estimated_world_loss, 'loss_per_example' : self.um.true_loss, 'act_loss_per_example' : self.wm.act_loss_per_example } self.dp = data_provider def run(self,",
"np.zeros(obs['depths1'][-1].shape, dtype = obs['depths1'][-1].dtype) for timepoint in obs['depths1']] for obs in batch.states]) #",
"DebuggingForceMagUpdater: def __init__(self, models, data_provider, optimizer_params, learning_rate_params, postprocessor, updater_params): self.dp = data_provider self.wm",
": batch['depths1'], 'act' : batch['action'], 'act_post' : batch['action_post'], 'est_loss' : est_losses, 'action_sample' :",
"timepoint in batch.next_state['action']]]) # print('actions shape') # print(actions.shape) # print(len(batch.next_state['action'])) # action_ids_list =",
": self.um.true_loss, 'estimated_world_loss' : self.um.estimated_world_loss } self.state_desc = updater_params['state_desc'] def update(self, sess, visualize",
": self.um.uncertainty_loss, 'loss_per_example' : self.um.true_loss, 'global_step' : self.global_step} def update(self, sess, visualize =",
"'action_post', 'depths1']: batch[k] = np.concatenate(batch[k], axis=0) state_desc = 'depths1' #depths, actions, actions_post, next_depth",
"= models['world_model'] self.um = models['uncertainty_model'] self.postprocessor = postprocessor self.global_step = tf.get_variable('global_step', [], tf.int32,",
"for k in ['action', 'action_post', 'depths1']: batch[k] = np.concatenate(batch[k], axis=0) state_desc = 'depths1'",
": self.um.uncertainty_loss, 'um_lr' : um_lr, 'um_optimizer' : um_opt, 'global_step' : self.global_step, 'loss_per_example' :",
"self.um.uncertainty_loss, self.global_step, optimizer_params['uncertainty_model'], var_list = self.um.var_list) self.targets = {'global_step' : self.global_step, 'um_optimizer' :",
"self.wm.action_post : batch['action_post'], self.wm.obj_there : batch['obj_there'] } res = sess.run(self.targets, feed_dict = feed_dict)",
"self.wm.action_post : batch['action_post'] } res = sess.run(self.targets, feed_dict = feed_dict) res.pop('um_increment') res.pop('global_increment') global_step",
"res['recent'] = batch['recent'] class ObjectThereValidater: def __init__(self, models, data_provider): self.um = models['uncertainty_model'] self.wm",
"changed for an online data provider, set to do nothing self.map_draw_mode = 'specified_indices'",
"'estimated_world_loss' : self.um.estimated_world_loss } self.state_desc = updater_params['state_desc'] def update(self, sess, visualize = False):",
"0 for msg in batch['recent']['msg']] res['obj_freq'] = np.mean(looking_at_obj) return res class DataWriteUpdater: def",
"def update(self, sess, visualize = False): batch = self.data_provider.dequeue_batch() state_desc = self.state_desc feed_dict",
"__init__(self, models, data_provider, optimizer_params, learning_rate_params, postprocessor, updater_params, action_sampler = None): self.data_provider = data_provider",
"= updater_params['map_draw_example_indices'] self.map_draw_timestep_indices = updater_params['map_draw_timestep_indices'] self.map_draw_freq = updater_params['map_draw_freq'] def update(self, sess, visualize =",
"] } world_model_res = sess.run(self.world_model_targets, feed_dict = wm_feed_dict) um_feed_dict = { self.um.s_i :",
"def postprocess_batch_depth(batch): # depths = np.array([[timepoint if timepoint is not None else np.zeros(obs['depths1'][-1].shape,",
"= h5py.File(fn, mode = 'a') dt = h5py.special_dtype(vlen = str) self.handles = {'msg'",
"} world_model_res = sess.run(self.world_model_targets, feed_dict = wm_feed_dict) um_feed_dict = { self.um.s_i : batch[state_desc][:,",
"= {'given' : self.world_model.processed_input, 'loss' : self.world_model.loss, 'loss_per_example' : self.world_model.loss_per_example, 'learning_rate' : wm_learning_rate,",
"= np.mean(entropies) # res['entropy'] = entropies if 'msg' in batch['recent']: looking_at_obj = [1",
"= updater_params['map_draw_mode'] #this specification specifices batch example indices for which we do a",
"#if 'other' in batch['recent']: # entropies = [other[0] for other in batch['recent']['other']] #",
"obs['depths1']] for obs in batch.states]) # actions = np.array(batch.actions) # next_depth = np.array([batch.next_state['depths1']])",
"pass each index because action sampling is the 'batch.' self.action_sampler = action_sampler assert",
"feed_dict) res.pop('um_increment') res.pop('global_increment') global_step = res['global_step'] #if self.map_draw_mode is not None and global_step",
"action_ids = np.array([action_ids_list]) return depths_past, objects, actions, action_ids, depths_fut # def postprocess_batch_for_actionmap(batch): #",
"for t in self.map_draw_timestep_indices] action_samples = self.action_sampler.sample_actions() action, entropy, estimated_world_loss = self.um.act(sess, action_samples,",
"(N, act_dim), dtype = np.float32), 'action_post' : hdf5.require_dataset('action_post', shape = (N, act_dim), dtype",
"[], tf.int32, initializer = tf.constant_initializer(0,dtype = tf.int32)) self.action = tf.placeholder = tf.placeholder(tf.float32, [None]",
"#self.map_draw_example_indices = updater_params['map_draw_example_indices'] #self.map_draw_timestep_indices = updater_params['map_draw_timestep_indices'] #self.map_draw_freq = updater_params['map_draw_freq'] def update(self, sess, visualize",
"not None and msg['msg']['action_type']['OBJ_ACT'] else 0 for msg in batch['recent']['msg']] res['obj_freq'] = np.mean(looking_at_obj)",
"which we do a forward pass. #need to do one forward pass each",
"optimizer_params['uncertainty_model']) self.global_step = self.global_step / 2 self.um_targets = {'loss' : self.um.uncertainty_loss, 'learning_rate' :",
"self.um.true_loss, 'act_loss_per_example' : self.wm.act_loss_per_example } self.dp = data_provider def run(self, sess): batch =",
"model, data_provider): self.dp = data_provider self.wm = model['world_model'] self.um = model['uncertainty_model'] self.targets =",
": act_lr, 'fut_lr' : fut_lr, 'fut_loss' : self.wm.fut_loss, 'act_loss' : self.wm.act_loss, 'estimated_world_loss' :",
"= model['world_model'] self.um = model['uncertainty_model'] self.targets = {} self.targets.update({k : v for k,",
"sess, visualize = False): batch = self.dp.dequeue_batch() state_desc = self.state_desc feed_dict = {",
"0 self.targets = {} self.state_desc = updater_params.get('state_desc', 'depths1') if not freeze_wm: num_not_frozen +=",
"pi_loss = -tf.reduce_sum(tf.reduce_sum(log_prob_tf * self.ac, [1]) * self.adv) vf_loss = .5 * tf.reduce_sum(tf.square(rl_model.vf",
"'action_sample' : action, 'estimated_world_loss' : estimated_world_loss, # 'action_samples' : action_samples, 'depths1' : batch[self.state_desc][idx],",
"models['world_model'] self.targets = { 'act_pred' : self.wm.act_pred, 'fut_loss' : self.wm.fut_loss, 'act_loss' : self.wm.act_loss,",
"# print('actions shape') # print(actions.shape) # print(len(batch.next_state['action'])) # action_ids_list = [] # for",
"um_opt if num_not_frozen == 0: self.targets['global_step'] = self.global_step self.targets['increment'] = tf.assign_add(self.global_step, 1) else:",
"= sess.run(self.targets, feed_dict = feed_dict) global_step = res['global_step'] if self.map_draw_mode is not None",
"self.act_step, optimizer_params['world_model']['act_model'], var_list = self.wm.act_var_list + self.wm.encode_var_list) fut_opt_params, fut_opt = get_optimizer(fut_lr, self.wm.fut_loss, self.fut_step,",
"['action_post'] } if self.insert_objthere: feed_dict[self.wm.obj_there_via_msg] = batch['obj_there'] res = sess.run(self.targets, feed_dict = feed_dict)",
"batch['recent']['msg'] else: print('little time') save_keys = self.little_save_keys res.update(dict((k, v) for (k, v) in",
"self.wm.act_loss, self.global_step, optimizer_params['world_model']['act_model'], var_list = self.wm.act_var_list + self.wm.encode_var_list) fut_opt_params, fut_opt = get_optimizer(fut_lr, self.wm.fut_loss,",
"} if self.um.exactly_whats_needed: self.targets['oh_my_god'] = self.um.oh_my_god self.state_desc = updater_params['state_desc'] def update(self, sess, visualize",
"else [data_provider] self.wm = models['world_model'] self.um = models['uncertainty_model'] freeze_wm = updater_params['freeze_wm'] freeze_um =",
"np.uint8), 'objects1' : hdf5.require_dataset('objects1', shape = (N, height, width, 3), dtype = np.uint8),",
"= tf.placeholder = tf.placeholder(tf.float32, [None] + world_model.action_one_hot.get_shape().as_list()[1:]) self.adv = tf.placeholder(tf.float32, [None]) self.r =",
"um_increment = tf.assign_add(self.um.step, 1) assert 'um_increment' not in self.targets self.targets['um_increment'] = um_increment self.obj_there_supervision",
"{ self.wm.states : batch['depths1'], self.wm.action : batch['action'], self.wm.obj_there : batch['obj_there'] } return sess.run(self.targets,",
"batch[self.state_desc], self.wm.action : batch['action'], self.wm.action_post : batch['action_post'] } self.targets['global_step'] = self.global_step res =",
"= None, little_save_keys = None, big_save_len = None, big_save_freq = None, state_descriptor =",
"self.big_save_keys est_losses = [other[1] for other in batch['recent']['other']] action_sample = [other[2] for other",
"res = sess.run(self.targets, feed_dict = feed_dict) res.pop('um_increment') res.pop('global_increment') global_step = res['global_step'] #if self.map_draw_mode",
"tf.constant_initializer(0,dtype = tf.int32)) self.act_lr_params, act_lr = get_learning_rate(self.global_step, ** learning_rate_params['world_model']['act_model']) self.um_lr_params, um_lr = get_learning_rate(self.global_step,",
"Defines the training step. ''' import sys sys.path.append('tfutils') import tensorflow as tf from",
": um_opt, # 'global_step' : self.global_step, 'loss_per_example' : self.um.true_loss}) self.map_draw_mode = None #Map",
"= {} self.state_desc = updater_params.get('state_desc', 'depths1') if not freeze_wm: num_not_frozen += 1 act_opt_params,",
"'depths1']: batch[k] = np.concatenate(batch[k], axis=0) state_desc = 'depths1' #depths, actions, actions_post, next_depth =",
"self.um.uncertainty_loss, self.global_step, optimizer_params['uncertainty_model'], var_list = self.um.var_list) self.global_step = self.global_step / 2 self.targets =",
"= updater_params['hdf5_filename'] N = updater_params['N_save'] height, width = updater_params['image_shape'] act_dim = updater_params['act_dim'] print('setting",
"initializer = tf.constant_initializer(0,dtype = tf.int32)) self.act_lr_params, act_lr = get_learning_rate(self.global_step, ** learning_rate_params['world_model']['act_model']) self.fut_lr_params, fut_lr",
"= tf.constant_initializer(0,dtype = tf.int32)) self.wm_lr_params, wm_learning_rate = get_learning_rate(self.global_step, ** learning_rate_params['world_model']) self.wm_opt_params, wm_opt =",
"sess.run(tf.global_variables_initializer()) def update(self, sess, visualize = False): batch = self.data_provider.dequeue_batch() depths, objects, actions,",
"{} print('postprocessor deets') print(global_step) print(self.big_save_freq) print(self.big_save_len) if (global_step) % self.big_save_freq < self.big_save_len: print('big",
"assert set(self.wm.readouts.keys()) != set(self.um.readouts.keys()) self.targets.update(self.wm.readouts) self.targets.update(self.um.readouts) um_increment = tf.assign_add(self.um.step, 1) assert 'um_increment' not",
"should be changed for an online data provider, set to do nothing self.map_draw_mode",
"self.r = tf.placeholder(tf.float32, [None]) log_prob_tf = tf.nn.log_softmax(rl_model.logits) prob_tf = tf.nn.softmax(rl_model.logits) pi_loss = -tf.reduce_sum(tf.reduce_sum(log_prob_tf",
"self.map_draw_mode = updater_params['map_draw_mode'] #this specification specifices batch example indices for which we do",
"self.big_save_keys.append('map_draw') self.little_save_keys.append('map_draw') self.big_save_keys.extend(['act_lr', 'um_lr']) self.little_save_keys.extend(['act_lr', 'um_lr']) def postprocess(self, training_results, batch): global_step = training_results['global_step']",
"set up') self.start = 0 def update(self): batch = self.data_provider.dequeue_batch() bs = len(batch['recent']['msg'])",
"+ 0.5 * vf_loss - entropy * 0.01 rl_opt_params, rl_opt = get_optimizer(learning_rate, self.rl_loss,",
"batch['obj_there'] = np.concatenate(batch['obj_there'], axis = 0) feed_dict[self.wm.obj_there_via_msg] = batch['obj_there'] print('state desc! ' +",
"obs[desc][-1].dtype) for timepoint in obs[desc]] for obs in batch.states]) # actions = np.array([[np.zeros(batch.next_state['action'][-1].shape,",
"wm_learning_rate, 'optimizer' : wm_opt, 'prediction' : self.world_model.pred, 'tv' : self.world_model.tv} self.inc_step = self.global_step.assign_add(1)",
"k, v in self.wm.readouts.items() if k not in self.wm.save_to_gfs}) self.targets.update({k : v for",
"self.wm.action : batch['action'], self.wm.action_post : batch['action_post'] } res = sess.run(self.targets, feed_dict = feed_dict)",
"= self.start + bs for k in ['depths1', 'objects1', 'images1', 'action', 'action_post']: tosave",
"postprocess_batch_depth(batch, state_desc) feed_dict = { self.wm.states : batch[state_desc], self.wm.action : batch['action'], self.wm.action_post :",
"self.wm.act_loss, self.global_step, optimizer_params['world_model']['act_model'], var_list = self.wm.act_var_list + self.wm.encode_var_list) self.targets['act_opt'] = act_opt if not",
"= .5 * tf.reduce_sum(tf.square(rl_model.vf - self.r)) entropy = -tf.reduce_sum(prob_tf * log_prob_tf) self.rl_loss =",
": batch['action_post'] } self.targets['global_step'] = self.global_step res = sess.run(self.targets, feed_dict = feed_dict) glstep",
"self.global_step, optimizer_params['world_model']['act_model'], var_list = self.wm.act_var_list + self.wm.encode_var_list) um_opt_params, um_opt = get_optimizer(um_lr, self.um.uncertainty_loss, self.global_step,",
"loss: ' + str(world_model_res['loss'])) um_feed_dict = { self.um.s_i : depths, self.um.action_sample : actions[:,",
"prepped = {} depths = replace_the_nones(obs[state_desc]) depths_past = np.array([depths[:-1]]) depths_fut = np.array([depths[:1]]) objects",
"just assuming one sort of specification self.state_desc = updater_params.get('state_desc', 'depths1') self.map_draw_mode = updater_params['map_draw_mode']",
"actions, action_ids, next_depth = postprocess_batch_for_actionmap(batch) wm_feed_dict = { self.world_model.s_i : depths, self.world_model.s_f :",
"width, 3), dtype = np.uint8), 'objects1' : hdf5.require_dataset('objects1', shape = (N, height, width,",
"self.global_step, optimizer_params['uncertainty_model'], var_list = self.um.var_list) self.targets['um_opt'] = um_opt if num_not_frozen == 0: self.targets['global_step']",
"act_post = batch depths = replace_the_nones(obs[state_desc]) obs_past = np.array([depths[:-1]]) obs_fut = np.array([depths[1:]]) actions",
"action at random') batch = {} for i, dp in enumerate(self.data_provider): provider_batch =",
": self.wm.act_loss, 'estimated_world_loss' : self.um.estimated_world_loss } self.targets.update({'um_loss' : self.um.uncertainty_loss, 'um_lr' : um_lr, 'um_optimizer'",
"res = {} print('postprocessor deets') print(global_step) print(self.big_save_freq) print(self.big_save_len) if (global_step) % self.big_save_freq <",
"for t in self.map_draw_timestep_indices] # action_samples = self.action_sampler.sample_actions() # action, entropy, estimated_world_loss =",
"act_lr_params, act_lr = get_learning_rate(self.act_step, **learning_rate_params['world_model']['act_model']) fut_lr_params, fut_lr = get_learning_rate(self.fut_step, **learning_rate_params['world_model']['fut_model']) act_opt_params, act_opt =",
"= self.dp.dequeue_batch() feed_dict = { self.wm.action : batch['action'], self.wm.action_post : batch['action_post'], self.um.obj_there :",
"tf.int32)) self.act_lr_params, act_lr = get_learning_rate(self.global_step, ** learning_rate_params['world_model']['act_model']) self.um_lr_params, um_lr = get_learning_rate(self.global_step, ** learning_rate_params['uncertainty_model'])",
"batch) return res, glstep class LatentUncertaintyUpdater: def __init__(self, world_model, uncertainty_model, data_provider, optimizer_params, learning_rate_params,",
"not in self.wm.save_to_gfs}) self.targets.update({k : v for k, v in self.um.readouts.items() if k",
"training_results['global_step'] res = {} if (global_step) % self.big_save_freq < self.big_save_len: save_keys = self.big_save_keys",
"timepoint in obs['depths1']] for obs in batch.states]) # actions = np.array(batch.actions) # next_depth",
"= map_draw_res res = self.postprocessor.postprocess(res, batch) return res, global_step class FreezeUpdater: def __init__(self,",
"= feed_dict) res = self.postprocessor.postprocess(res, batch) return res class DebuggingForceMagUpdater: def __init__(self, models,",
"obs in batch.states]) # actions = np.array(batch.actions) # next_depth = np.array([batch.next_state['depths1']]) # return",
"#need to do one forward pass each index because action sampling is the",
"Provides the training step. This is probably where we can put parallelization. Not",
"= {'um_loss' : self.um.uncertainty_loss, 'loss_per_example' : self.um.true_loss, 'estimated_world_loss' : self.um.estimated_world_loss} self.dp = data_provider",
"= np.mean(looking_at_obj) elif type(batch['recent']) == list and len(batch['recent'][0]) > 0: mean_per_provider = []",
"self.fut_step = tf.get_variable('fut_step', [], tf.int32, initializer = tf.constant_initializer(0,dtype = tf.int32)) self.um_step = tf.get_variable('ext_uncertainty_step',",
"= get_learning_rate(self.global_step, ** learning_rate_params['world_model']['fut_model']) self.um_lr_params, um_lr = get_learning_rate(self.global_step, ** learning_rate_params['uncertainty_model']) act_opt_params, act_opt =",
"} res = sess.run(self.targets, feed_dict = feed_dict) res['batch'] = {} for desc, val",
"self.um_lr_params, um_learning_rate = get_learning_rate(self.global_step, **learning_rate_params['uncertainty_model']) self.um_lr_params, um_opt = get_optimizer(um_learning_rate, self.um.uncertainty_loss, self.global_step, optimizer_params['uncertainty_model']) self.global_step",
"is probably where we can put parallelization. Not finished! ''' def __init__(world_model, rl_model,",
"None #Map drawing. Meant to have options, but for now just assuming one",
"in range(2): action_msg = msg[i]['msg']['actions'] if msg[i] is not None else [] if",
"big_save_keys = None, little_save_keys = None, big_save_len = None, big_save_freq = None, state_descriptor",
"= feed_dict) #TODO case it for online res['recent'] = {} #if self.map_draw_mode ==",
"wm_feed_dict) if visualize: cv2.imshow('pred', world_model_res['prediction'][0] / 4.)#TODO clean up w colors cv2.imshow('tv', world_model_res['tv'][0]",
"batch[k] = [provider_batch[k]] for k in ['action', 'action_post', 'depths1']: batch[k] = np.concatenate(batch[k], axis=0)",
"res = {} if (global_step) % self.big_save_freq < self.big_save_len: save_keys = self.big_save_keys #est_losses",
"res class DataWriteUpdater: def __init__(self, data_provider, updater_params): self.data_provider = data_provider fn = updater_params['hdf5_filename']",
"if self.insert_objthere: feed_dict[self.wm.obj_there_via_msg] = batch['obj_there'] res = sess.run(self.targets, feed_dict = feed_dict) #TODO case",
"assuming one sort of specification #self.state_desc = updater_params.get('state_desc', 'depths1') #self.map_draw_mode = updater_params['map_draw_mode'] #this",
"0: # if self.map_draw_mode == 'specified_indices': # map_draw_res = [] # for idx",
"= entropies looking_at_obj = [1 if msg is not None and msg['msg']['action_type']['OBJ_ACT'] else",
"batch['recent']['msg']] res['obj_freq'] = np.mean(looking_at_obj) elif type(batch['recent']) == list and len(batch['recent'][0]) > 0: mean_per_provider",
"False): batch = self.data_provider.dequeue_batch() depths, objects, actions, action_ids, next_depth = postprocess_batch_for_actionmap(batch) wm_feed_dict =",
"= models['world_model'] self.targets = {'act_pred' : self.wm.act_pred, 'act_loss' : self.wm.act_loss, 'estimated_world_loss' : self.um.estimated_world_loss,",
"get_learning_rate(self.global_step, ** learning_rate_params['uncertainty_model']) num_not_frozen = 0 self.targets = {} self.state_desc = updater_params.get('state_desc', 'depths1')",
": batch[state_desc][:, :-1], self.um.action_sample : batch['action'][:, -1], self.um.true_loss : world_model_res['loss_per_example'] } um_res =",
"{ self.wm.states : batch[self.state_desc], self.wm.action : batch['action'], self.wm.action_post : batch['action_post'] } res =",
"updater_params): self.dp = data_provider self.wm = models['world_model'] self.um = models['uncertainty_model'] self.postprocessor = postprocessor",
"global_step % self.map_draw_freq == 0: if self.map_draw_mode == 'specified_indices': map_draw_res = [] for",
"of specification self.state_desc = updater_params.get('state_desc', 'depths1') self.map_draw_mode = updater_params['map_draw_mode'] #this specification specifices batch",
"specifices batch example indices for which we do a forward pass. #need to",
"self.big_save_freq = big_save_freq self.state_descriptor = state_descriptor self.big_save_keys.append('map_draw') self.little_save_keys.append('map_draw') self.big_save_keys.extend(['act_lr', 'um_lr']) self.little_save_keys.extend(['act_lr', 'um_lr']) def",
"' + self.state_desc) res = sess.run(self.targets, feed_dict = feed_dict) res.pop('um_increment') global_step = res['global_step']",
"not None else [] # if len(action_msg): # idx = int(action_msg[0]['id']) # action_ids_list.append(idx)",
"dict(('um_' + k, v) for k, v in um_res.iteritems()) wm_res_new.update(um_res_new) res = wm_res_new",
"self.global_step.assign_add(1) self.um_lr_params, um_learning_rate = get_learning_rate(self.global_step, **learning_rate_params['uncertainty_model']) self.um_lr_params, um_opt = get_optimizer(um_learning_rate, self.um.uncertainty_loss, self.global_step, optimizer_params['uncertainty_model'])",
"self.inc_step = self.global_step.assign_add(1) self.um_lr_params, um_learning_rate = get_learning_rate(self.global_step, **learning_rate_params['uncertainty_model']) self.um_lr_params, um_opt = get_optimizer(um_learning_rate, self.um.uncertainty_loss,",
"dp in enumerate(self.data_provider): provider_batch = dp.dequeue_batch() for k in provider_batch: if k in",
"um_opt, 'global_step' : self.global_step, 'loss_per_example' : self.um.true_loss, 'estimated_world_loss' : self.um.estimated_world_loss } if self.um.exactly_whats_needed:",
"# prepped = {} # for desc in ['depths1', 'objects1']: # prepped[desc] =",
"= batch['recent'][k] if k in ['action', 'action_post']: tosave = tosave.astype(np.float32) self.handles[k][self.start : end]",
"= my_list[-1].dtype) if elt is None else elt for elt in my_list] def",
"updater_params['freeze_wm'] freeze_um = updater_params['freeze_um'] self.postprocessor = postprocessor self.global_step = tf.get_variable('global_step', [], tf.int32, initializer",
"= self.global_step self.targets.update({'act_lr' : act_lr, 'um_lr' : um_lr}) assert set(self.wm.readouts.keys()) != set(self.um.readouts.keys()) self.targets.update(self.wm.readouts)",
"'fut_optimizer' : fut_opt, 'act_lr' : act_lr, 'fut_lr' : fut_lr, 'fut_loss' : self.wm.fut_loss, 'act_loss'",
"um_learning_rate = get_learning_rate(self.global_step, **learning_rate_params['uncertainty_model']) self.um_lr_params, um_opt = get_optimizer(um_learning_rate, self.um.uncertainty_loss, self.global_step, optimizer_params['uncertainty_model']) self.global_step =",
"'act_pred' : self.wm.act_pred, 'act_optimizer' : act_opt, 'fut_optimizer' : fut_opt, 'act_lr' : act_lr, 'fut_lr'",
": self.um.true_loss}) self.state_desc = updater_params['state_desc'] #checking that we don't have repeat names def",
"estimated_world_loss, 'action_samples' : action_samples, 'depths1' : batch[self.state_desc][idx], 'action' : batch['action'][idx], 'action_post' : batch['action_post'][idx]}",
"= {'given' : self.world_model.processed_input, 'loss' : self.world_model.loss, 'learning_rate' : wm_learning_rate, 'optimizer' : wm_opt,",
"tf.int32)) print(learning_rate_params.keys()) um_lr_params, um_lr = get_learning_rate(self.global_step, **learning_rate_params['uncertainty_model']) um_opt_params, um_opt = get_optimizer(um_lr, self.um.uncertainty_loss, self.global_step,",
"res.pop('um_increment') global_step = res['global_step'] #if self.map_draw_mode is not None and global_step % self.map_draw_freq",
"= { self.wm.states : batch[state_desc], self.wm.action : batch['action'], self.wm.action_post : batch['action_post'] } self.targets['global_step']",
"tf.assign_add(self.um.step, 1) self.targets.update({'global_increment' : global_increment, 'um_increment' : um_increment}) self.targets.update(self.wm.readouts) self.targets.update(self.um.readouts) assert set(self.wm.readouts.keys()) !=",
"updater_params['act_dim'] print('setting up save loc') self.hdf5 = hdf5 = h5py.File(fn, mode = 'a')",
": self.um.oh_my_god, 'model_parameters' : self.um.var_list} def update(self, sess): batch = self.dp.dequeue_batch() feed_dict =",
"res['recent'] = {} #if self.map_draw_mode == 'specified_indices': # map_draw_res = [] # for",
"height, width, 3), dtype = np.uint8), 'action' : hdf5.require_dataset('action', shape = (N, act_dim),",
"= big_save_len self.big_save_freq = big_save_freq self.state_descriptor = state_descriptor self.big_save_keys.append('map_draw') self.little_save_keys.append('map_draw') self.big_save_keys.extend(['act_lr', 'um_lr']) self.little_save_keys.extend(['act_lr',",
"'estimated_world_loss' : self.um.estimated_world_loss} self.dp = data_provider def run(self, sess): batch = self.dp.dequeue_batch() feed_dict",
"res class SquareForceMagUpdater: def __init__(self, models, data_provider, optimizer_params, learning_rate_params, postprocessor, updater_params): self.dp =",
"res, glstep class LatentUncertaintyUpdater: def __init__(self, world_model, uncertainty_model, data_provider, optimizer_params, learning_rate_params, postprocessor, updater_params",
"not in self.um.save_to_gfs}) #this should be changed for an online data provider, set",
"updater_params.get('state_desc', 'depths1') if not freeze_wm: num_not_frozen += 1 act_opt_params, act_opt = get_optimizer(act_lr, self.wm.act_loss,",
"tf.int32)) self.wm_lr_params, wm_learning_rate = get_learning_rate(self.global_step, ** learning_rate_params['world_model']) self.wm_opt_params, wm_opt = get_optimizer(wm_learning_rate, self.world_model.loss, self.global_step,",
"np.float32)} print('save loc set up') self.start = 0 def update(self): batch = self.data_provider.dequeue_batch()",
"self.wm.action_post : batch['action_post'], self.um.obj_there : batch['obj_there'] } res = sess.run(self.targets, feed_dict = feed_dict)",
"self.map_draw_mode is not None and global_step % self.map_draw_freq == 0: if self.map_draw_mode ==",
"= (N, height, width, 3), dtype = np.uint8), 'objects1' : hdf5.require_dataset('objects1', shape =",
"self.wm = models['world_model'] self.um = models['uncertainty_model'] freeze_wm = updater_params['freeze_wm'] freeze_um = updater_params['freeze_um'] self.postprocessor",
"if len(action_msg): idx = int(action_msg[0]['id']) else: idx = -10000#just something that's not an",
"/ num_not_frozen self.targets['global_step'] = self.global_step self.targets.update({'act_lr' : act_lr, 'um_lr' : um_lr}) assert set(self.wm.readouts.keys())",
"self.map_draw_example_indices: # obs_for_actor = [batch[self.state_desc][idx][t] for t in self.map_draw_timestep_indices] # action_samples = self.action_sampler.sample_actions()",
"'tv' : self.world_model.tv} self.inc_step = self.global_step.assign_add(1) self.wm_lr_params, um_learning_rate = get_learning_rate(self.global_step, **learning_rate_params['uncertainty_model']) self.wm_lr_params, um_opt",
"res = self.postprocessor.postprocess(res, batch) return res, global_step class FreezeUpdater: def __init__(self, models, data_provider,",
"world_model, uncertainty_model, data_provider, optimizer_params, learning_rate_params, postprocessor, updater_params = None): self.data_provider = data_provider self.wm",
"def update(self, sess, visualize = False): batch = self.data_provider.dequeue_batch() state_desc = self.state_desc #depths,",
"np.concatenate(batch[k], axis=0) feed_dict = { self.wm.states : batch[self.state_desc], self.wm.action : batch['action'], self.wm.action_post :",
"if num_not_frozen == 0: self.targets['global_step'] = self.global_step self.targets['increment'] = tf.assign_add(self.global_step, 1) else: self.global_step",
"self.map_draw_freq == 0: # if self.map_draw_mode == 'specified_indices': # map_draw_res = [] #",
"None else elt for elt in my_list] def postprocess_batch_depth(batch, state_desc): obs, msg, act,",
"in self.map_draw_example_indices: obs_for_actor = [batch[self.state_desc][idx][t] for t in self.map_draw_timestep_indices] action_samples = self.action_sampler.sample_actions() action,",
"for k in ['depths1', 'objects1', 'images1', 'action', 'action_post']: tosave = batch['recent'][k] if k",
"= {} depths = replace_the_nones(obs[state_desc]) depths_past = np.array([depths[:-1]]) depths_fut = np.array([depths[:1]]) objects =",
"get_optimizer(wm_learning_rate, self.world_model.loss, self.global_step, optimizer_params['world_model']) self.world_model_targets = {'given' : self.world_model.processed_input, 'loss' : self.world_model.loss, 'loss_per_example'",
"actions, actions_post, next_depth = postprocess_batch_depth(batch, state_desc) feed_dict = { self.wm.states : batch[state_desc], self.wm.action",
"False): batch = self.data_provider.dequeue_batch() state_desc = self.um.state_descriptor wm_feed_dict = { self.world_model.states : batch[state_desc],",
"eta self.global_step = tf.get_variable('global_step', [], tf.int32, initializer = tf.constant_initializer(0,dtype = tf.int32)) self.action =",
"k, v in um_res.iteritems()) wm_res_new.update(um_res_new) res['global_step'] = res.pop('um_global_step') res = self.postprocessor.postprocess(wm_res_new, batch) return",
"self.adv = tf.placeholder(tf.float32, [None]) self.r = tf.placeholder(tf.float32, [None]) log_prob_tf = tf.nn.log_softmax(rl_model.logits) prob_tf =",
"None and msg['msg']['action_type'] == 'OBJ_ACT' else 0 for msg in batch['recent']['msg']] res['obj_freq'] =",
"'specified_indices': # map_draw_res = [] # for idx in self.map_draw_example_indices: # obs_for_actor =",
"self.wm.action : batch['action'], self.wm.action_post : batch ['action_post'] } if self.insert_objthere: feed_dict[self.wm.obj_there_via_msg] = batch['obj_there']",
"1) assert 'um_increment' not in self.targets self.targets['um_increment'] = um_increment self.obj_there_supervision = updater_params.get('include_obj_there', False)",
"else: save_keys = self.little_save_keys res.update(dict(pair for pair in training_results.iteritems() if pair[0] in save_keys))",
"+ k, v) for k, v in world_model_res.iteritems()) um_res_new = dict(('um_' + k,",
"/ 4.)#TODO clean up w colors cv2.imshow('tv', world_model_res['tv'][0] / 4.) cv2.imshow('processed0', world_model_res['given'][0, 0]",
": action, 'estimated_world_loss' : estimated_world_loss, # 'action_samples' : action_samples, 'depths1' : batch[self.state_desc][idx], #",
"self.world_model.tv} self.inc_step = self.global_step.assign_add(1) self.wm_lr_params, um_learning_rate = get_learning_rate(self.global_step, **learning_rate_params['uncertainty_model']) self.wm_lr_params, um_opt = get_optimizer(um_learning_rate,",
"self.um.true_loss}) self.map_draw_mode = None #Map drawing. Meant to have options, but for now",
"idx in self.map_draw_example_indices: # obs_for_actor = [batch[self.state_desc][idx][t] for t in self.map_draw_timestep_indices] # action_samples",
"is not None and msg['msg']['action_type'] == 'OBJ_ACT' else 0 for msg in provider_recent['msg']]",
": self.wm.fut_loss, 'act_loss' : self.wm.act_loss, 'estimated_world_loss' : self.um.estimated_world_loss } self.targets.update({'um_loss' : self.um.uncertainty_loss, 'um_lr'",
"else np.zeros(obs['depths1'][-1].shape, dtype = obs['depths1'][-1].dtype) for timepoint in obs['depths1']] for obs in batch.states])",
"do nothing self.map_draw_mode = 'specified_indices' #relies on there being just one obs type",
"not an id seen action_ids_list.append(idx) action_ids = np.array([action_ids_list]) return depths_past, objects, actions, action_ids,",
"'action_post', self.state_desc]: batch[k] = np.concatenate(batch[k], axis=0) feed_dict = { self.wm.states : batch[self.state_desc], self.wm.action",
"if self.obj_there_supervision: batch['obj_there'] = np.concatenate(batch['obj_there'], axis = 0) feed_dict[self.wm.obj_there_via_msg] = batch['obj_there'] print('state desc!",
"= batch['recent']['msg'] else: print('little time') save_keys = self.little_save_keys res.update(dict((k, v) for (k, v)",
"um_feed_dict) wm_res_new = dict(('wm_' + k, v) for k, v in world_model_res.iteritems()) um_res_new",
"is not None and global_step % self.map_draw_freq == 0: if self.map_draw_mode == 'specified_indices':",
"state_desc) feed_dict = { self.wm.states : batch[state_desc], self.wm.action : batch['action'], self.wm.action_post : batch['action_post']",
"is np array ''' return [np.zeros(my_list[-1].shape, dtype = my_list[-1].dtype) if elt is None",
"else: print('little time') save_keys = self.little_save_keys res.update(dict((k, v) for (k, v) in training_results.iteritems()",
"self.big_save_len: save_keys = self.big_save_keys #est_losses = [other[1] for other in batch['other']] #action_sample =",
"def __init__(self, data_provider, updater_params): self.data_provider = data_provider fn = updater_params['hdf5_filename'] N = updater_params['N_save']",
"= act_opt self.targets['fut_opt'] = fut_opt self.targets['act_lr'] = act_lr self.targets['fut_lr'] = fut_lr if not",
"self.wm.fut_var_list) um_opt_params, um_opt = get_optimizer(um_lr, self.um.uncertainty_loss, self.global_step, optimizer_params['uncertainty_model'], var_list = self.um.var_list) self.global_step =",
"models, data_provider): self.um = um = models['uncertainty_model'] self.wm = wm = models['world_model'] self.targets",
"{ # 'fut_pred' : self.wm.fut_pred, 'act_pred' : self.wm.act_pred, # 'fut_loss' : self.wm.fut_loss, 'act_loss'",
"for msg in batch['recent']['msg']] res['obj_freq'] = np.mean(looking_at_obj) elif type(batch['recent']) == list and len(batch['recent'][0])",
"self.dp.dequeue_batch() feed_dict = { self.wm.action : batch['action'], self.wm.action_post : batch['action_post'], self.um.obj_there : batch['obj_there']",
"= feed_dict) glstep = res['global_step'] res = self.postprocessor.postprocess(res, batch) return res, glstep class",
"optimizer_params['uncertainty_model']) self.um_targets = {'loss' : self.um.uncertainty_loss, 'learning_rate' : um_learning_rate, 'optimizer' : um_opt, 'global_step'",
"visualize = False): if self.um.just_random: print('Selecting action at random') batch = {} for",
"import models import h5py import json class RawDepthDiscreteActionUpdater: ''' Provides the training step.",
"obs type self.state_desc = data_provider.data_lengths['obs'].keys()[0] self.insert_objthere = False if data_provider.num_objthere is None else",
"= tf.get_variable('act_step', [], tf.int32, initializer = tf.constant_initializer(0,dtype = tf.int32)) self.fut_step = tf.get_variable('fut_step', [],",
"self.targets.update(self.um.readouts) #self.targets = { # 'fut_pred' : self.wm.fut_pred, 'act_pred' : self.wm.act_pred, # 'fut_loss'",
"self.postprocessor.postprocess(res, batch) return res, global_step class ActionUncertaintyUpdater: def __init__(self, models, data_provider, optimizer_params, learning_rate_params,",
"'estimated_world_loss' : self.um.estimated_world_loss, 'um_loss' : self.um.uncertainty_loss, 'loss_per_example' : self.um.true_loss, 'global_step' : self.global_step} def",
"= sess.run(self.targets, feed_dict = feed_dict) res.pop('um_increment') res.pop('global_increment') global_step = res['global_step'] #if self.map_draw_mode is",
"if msg[i] is not None else [] if len(action_msg): idx = int(action_msg[0]['id']) else:",
"res['map_draw'] = map_draw_res res = self.postprocessor.postprocess(res, batch) return res, global_step class ActionUncertaintyUpdater: def",
"batch[self.state_desc], self.wm.action : batch['action'], self.wm.action_post : batch['action_post'] } if self.obj_there_supervision: batch['obj_there'] = np.concatenate(batch['obj_there'],",
"sess, visualize = False): batch = self.data_provider.dequeue_batch() state_desc = self.state_desc feed_dict = {",
"my_list] def postprocess_batch_depth(batch, state_desc): obs, msg, act, act_post = batch depths = replace_the_nones(obs[state_desc])",
"optimizer_params['uncertainty_model'], var_list = self.um.var_list) self.targets['um_opt'] = um_opt self.targets['um_lr'] = um_lr self.targets['global_step'] = self.global_step",
"self.wm_opt_params, wm_opt = get_optimizer(wm_learning_rate, self.world_model.loss, self.global_step, optimizer_params['world_model']) self.world_model_targets = {'given' : self.world_model.processed_input, 'loss'",
"batch[k] = np.concatenate(batch[k], axis=0) state_desc = 'depths1' #depths, actions, actions_post, next_depth = postprocess_batch_depth(batch,",
"def run(self, sess): batch = self.dp.dequeue_batch() feed_dict = { self.wm.states : batch[self.state_desc], self.wm.action",
"= updater_params.get('state_desc', 'depths1') if not freeze_wm: act_lr_params, act_lr = get_learning_rate(self.act_step, **learning_rate_params['world_model']['act_model']) fut_lr_params, fut_lr",
"cv2.waitKey(1) print('wm loss: ' + str(world_model_res['loss'])) um_feed_dict = { self.um.s_i : depths, self.um.action_sample",
"[None]) log_prob_tf = tf.nn.log_softmax(rl_model.logits) prob_tf = tf.nn.softmax(rl_model.logits) pi_loss = -tf.reduce_sum(tf.reduce_sum(log_prob_tf * self.ac, [1])",
"res.pop('um_increment') res.pop('global_increment') global_step = res['global_step'] #if self.map_draw_mode is not None and global_step %",
"self.wm.fut_loss, 'act_loss' : self.wm.act_loss, 'um_loss' : self.um.uncertainty_loss, 'estimated_world_loss' : self.um.estimated_world_loss, 'loss_per_example' : self.um.true_loss,",
"{} depths = replace_the_nones(obs[state_desc]) depths_past = np.array([depths[:-1]]) depths_fut = np.array([depths[:1]]) objects = np.array([replace_the_nones(obs[state_desc])[:-1]])",
"var_list = self.um.var_list) self.global_step = self.global_step / 2 self.targets = {'act_pred' : self.wm.act_pred,",
"for msg in provider_recent['msg']] mean_per_provider.append(np.mean(looking_at_obj)) res['obj_freq'] = np.mean(mean_per_provider) res['obj_freq_per_provider_noprint'] = mean_per_provider return res",
"'um_optimizer' : um_opt, 'global_step' : self.global_step, 'loss_per_example' : self.um.true_loss, 'estimated_world_loss' : self.um.estimated_world_loss, 'ans'",
"= res['global_step'] #if self.map_draw_mode is not None and global_step % self.map_draw_freq == 0:",
"put parallelization. Not finished! ''' def __init__(world_model, rl_model, data_provider, eta): self.data_provider = data_provider",
"feed_dict = feed_dict) res = self.postprocessor.postprocess(res, batch) return res class DebuggingForceMagUpdater: def __init__(self,",
"self.dp = data_provider self.wm = models['world_model'] self.um = models['uncertainty_model'] self.postprocessor = postprocessor self.global_step",
": self.world_model.processed_input, 'loss' : self.world_model.loss, 'loss_per_example' : self.world_model.loss_per_example, 'learning_rate' : wm_learning_rate, 'optimizer' :",
"batch.next_state['action']]]) # print('actions shape') # print(actions.shape) # print(len(batch.next_state['action'])) # action_ids_list = [] #",
"[], tf.int32, initializer = tf.constant_initializer(0, dtype = tf.int32)) print(learning_rate_params.keys()) um_lr_params, um_lr = get_learning_rate(self.global_step,",
"v in um_res.iteritems()) wm_res_new.update(um_res_new) res = wm_res_new res['global_step'] = res.pop('um_global_step') res = self.postprocessor.postprocess(wm_res_new,",
"um_opt = get_optimizer(um_learning_rate, self.um.uncertainty_loss, self.global_step, optimizer_params['uncertainty_model']) self.um_targets = {'loss' : self.um.uncertainty_loss, 'learning_rate' :",
"tf.int32, initializer = tf.constant_initializer(0,dtype = tf.int32)) self.um_step = tf.get_variable('ext_uncertainty_step', [], tf.int32, initializer =",
"self.hdf5.close() class LatentUncertaintyValidator: def __init__(self, models, data_provider): self.um = models['uncertainty_model'] self.wm = models['world_model']",
"<reponame>neuroailab/curiosity_deprecated ''' Defines the training step. ''' import sys sys.path.append('tfutils') import tensorflow as",
"global_step class FreezeUpdater: def __init__(self, models, data_provider, optimizer_params, learning_rate_params, postprocessor, updater_params): self.data_provider =",
": objects } world_model_res = sess.run(self.world_model_targets, feed_dict = wm_feed_dict) if visualize: cv2.imshow('pred', world_model_res['prediction'][0]",
": batch['depths1'], self.wm.action : batch['action'], self.wm.action_post : batch['action_post'] } res = sess.run(self.targets, feed_dict",
"self.um.estimated_world_loss } self.state_desc = updater_params['state_desc'] def update(self, sess, visualize = False): batch =",
"self.wm.states : batch[self.state_desc], self.wm.action : batch['action'], self.wm.action_post : batch['action_post'] } if self.obj_there_supervision: batch['obj_there']",
"if msg is not None and msg['msg']['action_type']['OBJ_ACT'] else 0 for msg in batch['recent']['msg']]",
"batch['recent']['msg']] res['obj_freq'] = np.mean(looking_at_obj) return res class DataWriteUpdater: def __init__(self, data_provider, updater_params): self.data_provider",
"training_results, batch): global_step = training_results['global_step'] res = {} if (global_step) % self.big_save_freq <",
"if self.map_draw_mode is not None and global_step % self.map_draw_freq == 0: if self.map_draw_mode",
"= get_optimizer(fut_lr, self.wm.fut_loss, self.fut_step, optimizer_params['world_model']['fut_model'], var_list = self.wm.fut_var_list) self.targets['act_opt'] = act_opt self.targets['fut_opt'] =",
"training_results, batch): global_step = training_results['global_step'] res = {} print('postprocessor deets') print(global_step) print(self.big_save_freq) print(self.big_save_len)",
"batch): global_step = training_results['global_step'] res = {} print('postprocessor deets') print(global_step) print(self.big_save_freq) print(self.big_save_len) if",
"'estimated_world_loss' : self.um.estimated_world_loss } if self.um.exactly_whats_needed: self.targets['oh_my_god'] = self.um.oh_my_god self.state_desc = updater_params['state_desc'] def",
"sys sys.path.append('tfutils') import tensorflow as tf from tfutils.base import get_optimizer, get_learning_rate import numpy",
"batch['action'][idx], 'action_post' : batch['action_post'][idx]} # map_draw_res.append(to_add) # res['map_draw'] = map_draw_res res = self.postprocessor.postprocess(res,",
"if k not in self.wm.save_to_gfs}) self.targets.update({k : v for k, v in self.um.readouts.items()",
"world_model self.rl_model = rl_model self.eta = eta self.global_step = tf.get_variable('global_step', [], tf.int32, initializer",
"'learning_rate' : um_learning_rate, 'optimizer' : um_opt, 'global_step' : self.global_step} self.postprocessor = postprocessor self.world_action_time",
"#depths, actions, actions_post, next_depth = postprocess_batch_depth(batch, state_desc) feed_dict = { self.wm.states : batch[state_desc],",
"batch['action'], self.wm.action_post : batch['action_post'] } res = sess.run(self.targets, feed_dict = feed_dict) res =",
"= get_learning_rate(self.global_step, ** learning_rate_params['world_model']['act_model']) self.um_lr_params, um_lr = get_learning_rate(self.global_step, ** learning_rate_params['uncertainty_model']) act_opt_params, act_opt =",
"2 self.targets = {'act_pred' : self.wm.act_pred, 'act_loss' : self.wm.act_loss, 'act_optimizer' : act_opt, 'um_optimizer'",
"self.um.var_list) self.targets = {'global_step' : self.global_step, 'um_optimizer' : um_opt} assert set(self.wm.readouts.keys()) != set(self.um.readouts.keys())",
"dtype = np.uint8), 'images1': hdf5.require_dataset('images1', shape = (N, height, width, 3), dtype =",
"= {} for desc, val in batch.iteritems(): print(desc) if desc == 'obj_there': res['batch'][desc]",
"self.targets['fut_lr'] = fut_lr if not freeze_um: um_lr_params, um_lr = get_learning_rate(self.um_step, **learning_rate_params['uncertainty_model']) um_opt_params, um_opt",
"repeat names def start(self, sess): self.data_provider.start_runner(sess) sess.run(tf.global_variables_initializer()) def update(self, sess, visualize = False):",
"self.dp.dequeue_batch() state_desc = self.state_desc feed_dict = { self.wm.states : batch[state_desc], self.wm.action : batch['action'],",
"res = self.postprocessor.postprocess(res, batch) return res class SquareForceMagUpdater: def __init__(self, models, data_provider, optimizer_params,",
"in ['action', 'action_post', 'depths1']: batch[k] = np.concatenate(batch[k], axis=0) feed_dict = { self.wm.states :",
"hdf5.require_dataset('action_post', shape = (N, act_dim), dtype = np.float32)} print('save loc set up') self.start",
"self.targets.update({'global_increment' : global_increment, 'um_increment' : um_increment}) self.targets.update(self.wm.readouts) self.targets.update(self.um.readouts) assert set(self.wm.readouts.keys()) != set(self.um.readouts.keys()) def",
"batch[self.state_desc][idx], # 'action' : batch['action'][idx], 'action_post' : batch['action_post'][idx]} # map_draw_res.append(to_add) # res['map_draw'] =",
"# action_ids = np.array([action_ids_list]) # next_depths = np.array([batch.next_state['depths1']]) # return prepped['depths1'], prepped['objects1'], actions,",
"not in ['recent', 'depths1', 'objects1', 'images1']: res['batch'][desc] = val res['recent'] = batch['recent'] else:",
"= tf.constant_initializer(0, dtype = tf.int32)) print(learning_rate_params.keys()) um_lr_params, um_lr = get_learning_rate(self.global_step, **learning_rate_params['uncertainty_model']) um_opt_params, um_opt",
"* self.ac, [1]) * self.adv) vf_loss = .5 * tf.reduce_sum(tf.square(rl_model.vf - self.r)) entropy",
"self.wm.action_post : batch['action_post'] } if self.obj_there_supervision: batch['obj_there'] = np.concatenate(batch['obj_there'], axis = 0) feed_dict[self.wm.obj_there_via_msg]",
"'batch.' #self.action_sampler = action_sampler #assert self.map_draw_mode == 'specified_indices' and self.action_sampler is not None,",
"#est_losses = [other[1] for other in batch['other']] #action_sample = [other[2] for other in",
"= tf.assign_add(self.global_step, 1) um_increment = tf.assign_add(self.um.step, 1) self.targets.update({'global_increment' : global_increment, 'um_increment' : um_increment})",
"wm_opt, 'prediction' : self.world_model.pred, 'tv' : self.world_model.tv} self.inc_step = self.global_step.assign_add(1) self.um_lr_params, um_learning_rate =",
"= {'example_id' : idx, 'action_sample' : action, 'estimated_world_loss' : estimated_world_loss, 'action_samples' : action_samples,",
": batch['action_post'] } res = sess.run(self.targets, feed_dict = feed_dict) res = self.postprocessor.postprocess(res, batch)",
"class LatentUncertaintyUpdater: def __init__(self, world_model, uncertainty_model, data_provider, optimizer_params, learning_rate_params, postprocessor, updater_params = None):",
"{} # for desc in ['depths1', 'objects1']: # prepped[desc] = np.array([[timepoint if timepoint",
"v in self.um.readouts.items() if k not in self.um.save_to_gfs}) #this should be changed for",
"} self.dp = data_provider def run(self, sess): batch = self.dp.dequeue_batch() feed_dict = {",
"end] = batch['recent'][k] self.handles['msg'][self.start : end] = [json.dumps(msg) for msg in batch['recent']['msg']] self.start",
"up w colors cv2.imshow('tv', world_model_res['tv'][0] / 4.) cv2.imshow('processed0', world_model_res['given'][0, 0] / 4.) cv2.imshow('processed1',",
"training_results.iteritems() if k in save_keys)) #res['msg'] = batch['msg'][-1] entropies = [other[0] for other",
"postprocessor self.global_step = tf.get_variable('global_step', [], tf.int32, initializer = tf.constant_initializer(0, dtype = tf.int32)) print(learning_rate_params.keys())",
"= np.array([[np.zeros(batch.next_state['action'][-1].shape, batch.next_state['action'][-1].dtype) if timepoint is None else timepoint for timepoint in batch.next_state['action']]])",
"and self.action_sampler is not None, (self.map_draw_mode, action_sampler) self.map_draw_example_indices = updater_params['map_draw_example_indices'] self.map_draw_timestep_indices = updater_params['map_draw_timestep_indices']",
"self.global_step, optimizer_params['world_model']) self.world_model_targets = {'given' : self.world_model.processed_input, 'loss' : self.world_model.loss, 'learning_rate' : wm_learning_rate,",
"um_increment self.obj_there_supervision = updater_params.get('include_obj_there', False) #self.map_draw_mode = None #Map drawing. Meant to have",
"# for desc in ['depths1', 'objects1']: # prepped[desc] = np.array([[timepoint if timepoint is",
"= action_sampler #assert self.map_draw_mode == 'specified_indices' and self.action_sampler is not None, (self.map_draw_mode, action_sampler)",
"= self.global_step.assign_add(1) self.wm_lr_params, um_learning_rate = get_learning_rate(self.global_step, **learning_rate_params['uncertainty_model']) self.wm_lr_params, um_opt = get_optimizer(um_learning_rate, self.um.uncertainty_loss, self.global_step,",
"self.handles['msg'][self.start : end] = [json.dumps(msg) for msg in batch['recent']['msg']] self.start = end def",
"there being just one obs type self.state_desc = data_provider.data_lengths['obs'].keys()[0] self.insert_objthere = False if",
"def __init__(self, big_save_keys = None, little_save_keys = None, big_save_len = None, big_save_freq =",
"wm_opt = get_optimizer(wm_learning_rate, self.world_model.loss, self.global_step, optimizer_params['world_model']) self.world_model_targets = {'given' : self.world_model.processed_input, 'loss' :",
"postprocessor, updater_params): self.data_provider = data_provider self.wm = world_model self.um = uncertainty_model self.postprocessor =",
"-tf.reduce_sum(prob_tf * log_prob_tf) self.rl_loss = pi_loss + 0.5 * vf_loss - entropy *",
"in um_res.iteritems()) wm_res_new.update(um_res_new) res = wm_res_new res['global_step'] = res.pop('um_global_step') res = self.postprocessor.postprocess(wm_res_new, batch)",
"self.um.true_loss : np.array([world_model_res['loss']]) } um_res = sess.run(self.um_targets, feed_dict = um_feed_dict) wm_res_new = dict(('wm_'",
"that's not an id seen action_ids_list.append(idx) action_ids = np.array([action_ids_list]) return depths_past, objects, actions,",
"act_lr = get_learning_rate(self.global_step, ** learning_rate_params['world_model']['act_model']) self.um_lr_params, um_lr = get_learning_rate(self.global_step, ** learning_rate_params['uncertainty_model']) num_not_frozen =",
"**learning_rate_params['uncertainty_model']) um_opt_params, um_opt = get_optimizer(um_lr, self.um.uncertainty_loss, self.global_step, optimizer_params['uncertainty_model']) self.targets = {'um_loss' : self.um.uncertainty_loss,",
"'specified_indices' and self.action_sampler is not None, (self.map_draw_mode, action_sampler) #self.map_draw_example_indices = updater_params['map_draw_example_indices'] #self.map_draw_timestep_indices =",
"self.wm.fut_loss, 'act_loss' : self.wm.act_loss, 'estimated_world_loss' : self.um.estimated_world_loss } self.targets.update({'um_loss' : self.um.uncertainty_loss, 'um_lr' :",
"self.um.obj_there : batch['obj_there'] } res = sess.run(self.targets, feed_dict = feed_dict) res = self.postprocessor.postprocess(res,",
"self.world_model_targets = {'given' : self.world_model.processed_input, 'loss' : self.world_model.loss, 'loss_per_example' : self.world_model.loss_per_example, 'learning_rate' :",
": batch['action'][idx], 'action_post' : batch['action_post'][idx]} # map_draw_res.append(to_add) #res['map_draw'] = map_draw_res return res class",
"batch['depths1'], self.wm.action : batch['action'], self.wm.action_post : batch['action_post'], self.wm.obj_there : batch['obj_there'] } res =",
"= wm_res_new res['global_step'] = res.pop('um_global_step') res = self.postprocessor.postprocess(wm_res_new, batch) return res class DamianWMUncertaintyUpdater:",
"save_keys = self.little_save_keys res.update(dict((k, v) for (k, v) in training_results.iteritems() if k in",
"tf.get_variable('global_step', [], tf.int32, initializer = tf.constant_initializer(0,dtype = tf.int32)) self.act_step = tf.get_variable('act_step', [], tf.int32,",
"= { # 'fut_pred' : self.wm.fut_pred, 'act_pred' : self.wm.act_pred, # 'fut_loss' : self.wm.fut_loss,",
"'global_step' : self.global_step, 'loss_per_example' : self.um.true_loss, 'estimated_world_loss' : self.um.estimated_world_loss } if self.um.exactly_whats_needed: self.targets['oh_my_god']",
"my_list[-1] is np array ''' return [np.zeros(my_list[-1].shape, dtype = my_list[-1].dtype) if elt is",
"self.inc_step = self.global_step.assign_add(1) self.wm_lr_params, um_learning_rate = get_learning_rate(self.global_step, **learning_rate_params['uncertainty_model']) self.wm_lr_params, um_opt = get_optimizer(um_learning_rate, self.um.uncertainty_loss,",
"= world_model self.um = uncertainty_model self.postprocessor = postprocessor self.global_step = tf.get_variable('global_step', [], tf.int32,",
"sess.run(self.targets, feed_dict = feed_dict) res = self.postprocessor.postprocess(res, batch) return res class DebuggingForceMagUpdater: def",
"array ''' return [np.zeros(my_list[-1].shape, dtype = my_list[-1].dtype) if elt is None else elt",
"pair in training_results.iteritems() if pair[0] in save_keys)) #if 'other' in batch['recent']: # entropies",
"obs_past = np.array([depths[:-1]]) obs_fut = np.array([depths[1:]]) actions = np.array([replace_the_nones(act)]) actions_post = np.array([replace_the_nones(act_post)]) return",
"ObjectThereUpdater: def __init__(self, world_model, uncertainty_model, data_provider, optimizer_params, learning_rate_params, postprocessor, updater_params): self.data_provider = data_provider",
": batch[self.state_desc][idx], # 'action' : batch['action'][idx], 'action_post' : batch['action_post'][idx]} # map_draw_res.append(to_add) #res['map_draw'] =",
"updater_params.get('state_desc', 'depths1') #self.map_draw_mode = updater_params['map_draw_mode'] #this specification specifices batch example indices for which",
"probably where we can put parallelization. Not finished! ''' def __init__(world_model, rl_model, data_provider,",
"get_learning_rate(self.global_step, **learning_rate_params['uncertainty_model']) um_opt_params, um_opt = get_optimizer(um_lr, self.um.uncertainty_loss, self.global_step, optimizer_params['uncertainty_model']) self.targets = {'um_loss' :",
"'depths1') if not freeze_wm: num_not_frozen += 1 act_opt_params, act_opt = get_optimizer(act_lr, self.wm.act_loss, self.global_step,",
"= [] for i in range(2): action_msg = msg[i]['msg']['actions'] if msg[i] is not",
"batch) return res class LatentFreezeUpdater: def __init__(self, models, data_provider, optimizer_params, learning_rate_params, postprocessor, updater_params):",
"map_draw_res.append(to_add) # res['map_draw'] = map_draw_res res = self.postprocessor.postprocess(res, batch) return res, global_step class",
"names def start(self, sess): self.data_provider.start_runner(sess) sess.run(tf.global_variables_initializer()) def update(self, sess, visualize = False): batch",
"self.action_sampler is not None, (self.map_draw_mode, action_sampler) #self.map_draw_example_indices = updater_params['map_draw_example_indices'] #self.map_draw_timestep_indices = updater_params['map_draw_timestep_indices'] #self.map_draw_freq",
"= self.data_provider.dequeue_batch() state_desc = self.um.state_descriptor wm_feed_dict = { self.world_model.states : batch[state_desc], self.world_model.action :",
": self.wm.act_pred, # 'fut_loss' : self.wm.fut_loss, 'act_loss' : self.wm.act_loss, # 'estimated_world_loss' : self.um.estimated_world_loss,",
"UncertaintyUpdater: def __init__(self, world_model, uncertainty_model, data_provider, optimizer_params, learning_rate_params, postprocessor): self.data_provider = data_provider self.world_model",
": batch['action_post'][idx]} # map_draw_res.append(to_add) #res['map_draw'] = map_draw_res return res class ObjectThereUpdater: def __init__(self,",
"= False if data_provider.num_objthere is None else True def run(self, sess): batch =",
"batch['action_post'] } self.targets['global_step'] = self.global_step res = sess.run(self.targets, feed_dict = feed_dict) global_step =",
"update(self, sess, visualize = False): batch = self.data_provider.dequeue_batch() depths, objects, actions, action_ids, next_depth",
"'estimated_world_loss' : estimated_world_loss, # 'action_samples' : action_samples, 'depths1' : batch[self.state_desc][idx], # 'action' :",
"= updater_params['map_draw_timestep_indices'] self.map_draw_freq = updater_params['map_draw_freq'] def update(self, sess, visualize = False): batch =",
"** learning_rate_params['world_model']['act_model']) self.um_lr_params, um_lr = get_learning_rate(self.global_step, ** learning_rate_params['uncertainty_model']) num_not_frozen = 0 self.targets =",
"timepoint in obs[desc]] for obs in batch.states]) # actions = np.array([[np.zeros(batch.next_state['action'][-1].shape, batch.next_state['action'][-1].dtype) if",
"update(self, sess, visualize = False): if self.um.just_random: print('Selecting action at random') batch =",
"v in um_res.iteritems()) wm_res_new.update(um_res_new) res['global_step'] = res.pop('um_global_step') res = self.postprocessor.postprocess(wm_res_new, batch) return res",
"= updater_params['freeze_wm'] freeze_um = updater_params['freeze_um'] self.postprocessor = postprocessor self.global_step = tf.get_variable('global_step', [], tf.int32,",
"batch['action'], self.wm.action_post : batch['action_post'] } self.targets['global_step'] = self.global_step res = sess.run(self.targets, feed_dict =",
"self.targets = {'act_pred' : self.wm.act_pred, 'act_loss' : self.wm.act_loss, 'estimated_world_loss' : self.um.estimated_world_loss, 'um_loss' :",
"do a forward pass. #need to do one forward pass each index because",
"self.targets = {'um_loss' : self.um.uncertainty_loss, 'loss_per_example' : self.um.true_loss, 'estimated_world_loss' : self.um.estimated_world_loss} self.dp =",
"fut_opt_params, fut_opt = get_optimizer(fut_lr, self.wm.fut_loss, self.fut_step, optimizer_params['world_model']['fut_model'], var_list = self.wm.fut_var_list) self.targets['act_opt'] = act_opt",
"data_provider self.world_model = world_model self.um = uncertainty_model self.global_step = tf.get_variable('global_step', [], tf.int32, initializer",
"specification specifices batch example indices for which we do a forward pass. #need",
"res = self.postprocessor.postprocess(res, batch) return res, glstep class LatentUncertaintyUpdater: def __init__(self, world_model, uncertainty_model,",
"um_res_new = dict(('um_' + k, v) for k, v in um_res.iteritems()) wm_res_new.update(um_res_new) res['global_step']",
"replace_the_nones(my_list): ''' Assumes my_list[-1] is np array ''' return [np.zeros(my_list[-1].shape, dtype = my_list[-1].dtype)",
"in self.wm.readouts.items() if k not in self.wm.save_to_gfs}) self.targets.update({k : v for k, v",
"= str) self.handles = {'msg' : hdf5.require_dataset('msg', shape = (N,), dtype = dt),",
"#relies on there being just one obs type self.state_desc = data_provider.data_lengths['obs'].keys()[0] self.insert_objthere =",
"self.state_desc = updater_params['state_desc'] #checking that we don't have repeat names def start(self, sess):",
"= {} self.targets.update({k : v for k, v in self.wm.readouts.items() if k not",
"'um_lr' : um_lr, 'um_optimizer' : um_opt, # 'global_step' : self.global_step, 'loss_per_example' : self.um.true_loss})",
"tosave.astype(np.float32) self.handles[k][self.start : end] = batch['recent'][k] self.handles['msg'][self.start : end] = [json.dumps(msg) for msg",
"= val elif desc != 'recent': res['batch'][desc] = val[:, -1] res['recent'] = batch['recent']",
"for timepoint in obs['depths1']] for obs in batch.states]) # actions = np.array(batch.actions) #",
"batch[state_desc], self.world_model.action : batch['action'][:, -self.world_action_time : ] } world_model_res = sess.run(self.world_model_targets, feed_dict =",
"if timepoint is not None else np.zeros(obs['depths1'][-1].shape, dtype = obs['depths1'][-1].dtype) for timepoint in",
"optimizer_params, learning_rate_params, postprocessor, updater_params, action_sampler = None): self.data_provider = data_provider \\ if isinstance(data_provider,",
"(global_step) % self.big_save_freq < self.big_save_len: save_keys = self.big_save_keys #est_losses = [other[1] for other",
"self.map_draw_timestep_indices] action_samples = self.action_sampler.sample_actions() action, entropy, estimated_world_loss = self.um.act(sess, action_samples, obs_for_actor) to_add =",
"feed_dict) res = self.postprocessor.postprocess(res, batch) return res class LatentFreezeUpdater: def __init__(self, models, data_provider,",
"learning_rate_params['world_model']['act_model']) self.um_lr_params, um_lr = get_learning_rate(self.global_step, ** learning_rate_params['uncertainty_model']) act_opt_params, act_opt = get_optimizer(act_lr, self.wm.act_loss, self.global_step,",
"models['world_model'] self.targets = {'act_pred' : self.wm.act_pred, 'act_loss' : self.wm.act_loss, 'estimated_world_loss' : self.um.estimated_world_loss, 'um_loss'",
"= tf.int32)) self.wm_lr_params, wm_learning_rate = get_learning_rate(self.global_step, ** learning_rate_params['world_model']) self.wm_opt_params, wm_opt = get_optimizer(wm_learning_rate, self.world_model.loss,",
"cv2 from curiosity.interaction import models import h5py import json class RawDepthDiscreteActionUpdater: ''' Provides",
"= models['uncertainty_model'] self.postprocessor = postprocessor self.global_step = tf.get_variable('global_step', [], tf.int32, initializer = tf.constant_initializer(0,",
"'other' in batch['recent']: # entropies = [other[0] for other in batch['recent']['other']] # entropies",
"def start(self, sess): self.data_provider.start_runner(sess) sess.run(tf.global_variables_initializer()) def update(self, sess, visualize = False): batch =",
"batch = self.data_provider.dequeue_batch() bs = len(batch['recent']['msg']) end = self.start + bs for k",
"feed_dict = um_feed_dict) wm_res_new = dict(('wm_' + k, v) for k, v in",
"idx, 'action_sample' : action, 'estimated_world_loss' : estimated_world_loss, # 'action_samples' : action_samples, 'depths1' :",
"self.wm.action_post : batch['action_post'] } self.targets['global_step'] = self.global_step res = sess.run(self.targets, feed_dict = feed_dict)",
"actions = np.array([[np.zeros(batch.next_state['action'][-1].shape, batch.next_state['action'][-1].dtype) if timepoint is None else timepoint for timepoint in",
"msg, act = batch prepped = {} depths = replace_the_nones(obs[state_desc]) depths_past = np.array([depths[:-1]])",
"= models['uncertainty_model'] self.wm = models['world_model'] self.targets = {'um_loss' : self.um.uncertainty_loss, 'loss_per_example' : self.um.true_loss,",
"act_opt_params, act_opt = get_optimizer(act_lr, self.wm.act_loss, self.act_step, optimizer_params['world_model']['act_model'], var_list = self.wm.act_var_list + self.wm.encode_var_list) fut_opt_params,",
"an id seen action_ids_list.append(idx) action_ids = np.array([action_ids_list]) return depths_past, objects, actions, action_ids, depths_fut",
"= sess.run(self.targets, feed_dict = feed_dict) res = self.postprocessor.postprocess(res, batch) return res class DebuggingForceMagUpdater:",
"set(self.wm.readouts.keys()) != set(self.um.readouts.keys()) self.targets.update(self.wm.readouts) self.targets.update(self.um.readouts) #self.targets = { # 'fut_pred' : self.wm.fut_pred, 'act_pred'",
"elt for elt in my_list] def postprocess_batch_depth(batch, state_desc): obs, msg, act, act_post =",
"''' def __init__(world_model, rl_model, data_provider, eta): self.data_provider = data_provider self.world_model = world_model self.rl_model",
": batch[state_desc], self.wm.action : batch['action'], self.wm.action_post : batch['action_post'] } self.targets['global_step'] = self.global_step res",
"for desc, val in batch.iteritems(): print(desc) if desc == 'obj_there': res['batch'][desc] = val",
"= sess.run(self.um_targets, feed_dict = um_feed_dict) wm_res_new = dict(('wm_' + k, v) for k,",
"enumerate(self.data_provider): provider_batch = dp.dequeue_batch() for k in provider_batch: if k in batch: batch[k].append(provider_batch[k])",
"global_step class ActionUncertaintyUpdater: def __init__(self, models, data_provider, optimizer_params, learning_rate_params, postprocessor, updater_params): self.data_provider =",
"is None else timepoint for timepoint in batch.next_state['action']]]) # print('actions shape') # print(actions.shape)",
"JustUncertaintyUpdater: def __init__(self, models, data_provider, optimizer_params, learning_rate_params, postprocessor, updater_params, action_sampler = None): self.data_provider",
"'um_increment' not in self.targets self.targets['um_increment'] = um_increment self.obj_there_supervision = updater_params.get('include_obj_there', False) #self.map_draw_mode =",
"data_provider, eta): self.data_provider = data_provider self.world_model = world_model self.rl_model = rl_model self.eta =",
"'estimated_world_loss' : self.um.estimated_world_loss, 'loss_per_example' : self.um.true_loss, 'act_loss_per_example' : self.wm.act_loss_per_example } self.dp = data_provider",
"self.global_step = tf.get_variable('global_step', [], tf.int32, initializer = tf.constant_initializer(0, dtype = tf.int32)) print(learning_rate_params.keys()) um_lr_params,",
"= dict(('um_' + k, v) for k, v in um_res.iteritems()) wm_res_new.update(um_res_new) res =",
": hdf5.require_dataset('action_post', shape = (N, act_dim), dtype = np.float32)} print('save loc set up')",
"to_add = {'example_id' : idx, 'action_sample' : action, 'estimated_world_loss' : estimated_world_loss, 'action_samples' :",
"self.targets = {'act_pred' : self.wm.act_pred, 'act_loss' : self.wm.act_loss, 'act_optimizer' : act_opt, 'um_optimizer' :",
"None, (self.map_draw_mode, action_sampler) self.map_draw_example_indices = updater_params['map_draw_example_indices'] self.map_draw_timestep_indices = updater_params['map_draw_timestep_indices'] self.map_draw_freq = updater_params['map_draw_freq'] def",
": self.um.true_loss, 'act_loss_per_example' : self.wm.act_loss_per_example } self.dp = data_provider def run(self, sess): batch",
"= act_opt if not freeze_um: num_not_frozen += 1 um_opt_params, um_opt = get_optimizer(um_lr, self.um.uncertainty_loss,",
"self.world_model.loss_per_example, 'learning_rate' : wm_learning_rate, 'optimizer' : wm_opt, 'prediction' : self.world_model.pred, 'tv' : self.world_model.tv}",
"[data_provider] self.wm = models['world_model'] self.um = models['uncertainty_model'] freeze_wm = updater_params['freeze_wm'] freeze_um = updater_params['freeze_um']",
"provider_batch = dp.dequeue_batch() for k in provider_batch: if k in batch: batch[k].append(provider_batch[k]) else:",
"np.concatenate(batch['obj_there'], axis = 0) feed_dict[self.wm.obj_there_via_msg] = batch['obj_there'] print('state desc! ' + self.state_desc) res",
"learning_rate_params, postprocessor): self.data_provider = data_provider self.world_model = world_model self.um = uncertainty_model self.global_step =",
"DataWriteUpdater: def __init__(self, data_provider, updater_params): self.data_provider = data_provider fn = updater_params['hdf5_filename'] N =",
"(N, act_dim), dtype = np.float32)} print('save loc set up') self.start = 0 def",
"um_res = sess.run(self.um_targets, feed_dict = um_feed_dict) wm_res_new = dict(('wm_' + k, v) for",
"optimizer_params['uncertainty_model'], var_list = self.um.var_list) self.global_step = self.global_step / 2 self.targets = {'act_pred' :",
"self.um = models['uncertainty_model'] self.postprocessor = postprocessor self.global_step = tf.get_variable('global_step', [], tf.int32, initializer =",
"= { 'act_pred' : self.wm.act_pred, 'fut_loss' : self.wm.fut_loss, 'act_loss' : self.wm.act_loss, 'um_loss' :",
"depths_past = np.array([depths[:-1]]) depths_fut = np.array([depths[:1]]) objects = np.array([replace_the_nones(obs[state_desc])[:-1]]) actions = np.array([replace_the_nones(act)]) action_ids_list",
": batch[self.state_desc], self.wm.action : batch['action'], self.wm.action_post : batch['action_post'] } res = sess.run(self.targets, feed_dict",
"= { self.wm.states : batch[state_desc], self.wm.action : batch['action'], self.wm.obj_there : batch['obj_there'] } res",
"self.dp.dequeue_batch() feed_dict = { self.wm.states : batch['depths1'], self.wm.action : batch['action'], self.wm.action_post : batch['action_post'],",
"shape = (N, height, width, 3), dtype = np.uint8), 'images1': hdf5.require_dataset('images1', shape =",
"+ self.state_desc) res = sess.run(self.targets, feed_dict = feed_dict) res.pop('um_increment') global_step = res['global_step'] #if",
"'global_step' : self.global_step, 'loss_per_example' : self.um.true_loss}) self.map_draw_mode = None #Map drawing. Meant to",
"self.big_save_len = big_save_len self.big_save_freq = big_save_freq self.state_descriptor = state_descriptor def postprocess(self, training_results, batch):",
"= tf.get_variable('global_step', [], tf.int32, initializer = tf.constant_initializer(0, dtype = tf.int32)) print(learning_rate_params.keys()) um_lr_params, um_lr",
"options, but for now just assuming one sort of specification #self.state_desc = updater_params.get('state_desc',",
"in batch.states]) # actions = np.array(batch.actions) # next_depth = np.array([batch.next_state['depths1']]) # return depths,",
"None, (self.map_draw_mode, action_sampler) #self.map_draw_example_indices = updater_params['map_draw_example_indices'] #self.map_draw_timestep_indices = updater_params['map_draw_timestep_indices'] #self.map_draw_freq = updater_params['map_draw_freq'] def",
"data_provider, optimizer_params, learning_rate_params, postprocessor, updater_params): self.data_provider = data_provider self.wm = world_model self.um =",
"res.pop('global_increment') global_step = res['global_step'] #if self.map_draw_mode is not None and global_step % self.map_draw_freq",
"updater_params['image_shape'] act_dim = updater_params['act_dim'] print('setting up save loc') self.hdf5 = hdf5 = h5py.File(fn,",
"optimizer_params['uncertainty_model'], var_list = self.um.var_list) self.targets = {'um_loss' : self.um.uncertainty_loss, 'um_lr' : um_lr, 'um_optimizer'",
"learning_rate_params, postprocessor, updater_params): self.dp = data_provider self.wm = models['world_model'] self.um = models['uncertainty_model'] self.postprocessor",
"self.global_step, 'loss_per_example' : self.um.true_loss}) self.state_desc = updater_params['state_desc'] #checking that we don't have repeat",
"not None and global_step % self.map_draw_freq == 0: # if self.map_draw_mode == 'specified_indices':",
"'um_lr']) self.little_save_keys.extend(['act_lr', 'um_lr']) def postprocess(self, training_results, batch): global_step = training_results['global_step'] res = {}",
"'loss' : self.world_model.loss, 'learning_rate' : wm_learning_rate, 'optimizer' : wm_opt, 'prediction' : self.world_model.pred, 'tv'",
"next_depth def postprocess_batch_for_actionmap(batch, state_desc): obs, msg, act = batch prepped = {} depths",
"return res class ObjectThereUpdater: def __init__(self, world_model, uncertainty_model, data_provider, optimizer_params, learning_rate_params, postprocessor, updater_params):",
"= -tf.reduce_sum(tf.reduce_sum(log_prob_tf * self.ac, [1]) * self.adv) vf_loss = .5 * tf.reduce_sum(tf.square(rl_model.vf -",
"'action_post', 'depths1']: batch[k] = np.concatenate(batch[k], axis=0) feed_dict = { self.wm.states : batch[self.state_desc], self.wm.action",
"= dict(('um_' + k, v) for k, v in um_res.iteritems()) wm_res_new.update(um_res_new) res['global_step'] =",
"next_depth = postprocess_batch_for_actionmap(batch) wm_feed_dict = { self.world_model.s_i : depths, self.world_model.s_f : next_depth, self.world_model.action",
"= rl_model self.eta = eta self.global_step = tf.get_variable('global_step', [], tf.int32, initializer = tf.constant_initializer(0,dtype",
"def close(self): self.hdf5.close() class LatentUncertaintyValidator: def __init__(self, models, data_provider): self.um = models['uncertainty_model'] self.wm",
": batch['action'][idx], 'action_post' : batch['action_post'][idx]} # map_draw_res.append(to_add) # res['map_draw'] = map_draw_res res =",
"# action_ids_list = [] # for i in range(2): # action_msg = batch.next_state['msg'][i]['msg']['actions']",
"int(action_msg[0]['id']) else: idx = -10000#just something that's not an id seen action_ids_list.append(idx) action_ids",
"self.wm.action : batch['action'], self.wm.action_post : batch['action_post'] } if self.um.insert_obj_there: print('adding obj_there to feed",
"= updater_params.get('include_obj_there', False) #self.map_draw_mode = None #Map drawing. Meant to have options, but",
"self.um.s_i : depths, self.um.action_sample : actions[:, -1], self.um.true_loss : np.array([world_model_res['loss']]) } um_res =",
"for desc in ['depths1', 'objects1']: # prepped[desc] = np.array([[timepoint if timepoint is not",
"step. ''' import sys sys.path.append('tfutils') import tensorflow as tf from tfutils.base import get_optimizer,",
"val res['recent'] = batch['recent'] else: save_keys = self.little_save_keys res.update(dict(pair for pair in training_results.iteritems()",
"self.wm.act_var_list + self.wm.encode_var_list) um_opt_params, um_opt = get_optimizer(um_lr, self.um.uncertainty_loss, self.global_step, optimizer_params['uncertainty_model'], var_list = self.um.var_list)",
"#self.targets.update({'um_loss' : self.um.uncertainty_loss, 'um_lr' : um_lr, 'um_optimizer' : um_opt, # 'global_step' : self.global_step,",
"action_samples = self.action_sampler.sample_actions() action, entropy, estimated_world_loss = self.um.act(sess, action_samples, obs_for_actor) to_add = {'example_id'",
"in batch['recent']['msg']] res['obj_freq'] = np.mean(looking_at_obj) elif type(batch['recent']) == list and len(batch['recent'][0]) > 0:",
"= models['world_model'] self.um = models['uncertainty_model'] freeze_wm = updater_params['freeze_wm'] freeze_um = updater_params['freeze_um'] self.postprocessor =",
"= updater_params.get('state_desc', 'depths1') if not freeze_wm: num_not_frozen += 1 act_opt_params, act_opt = get_optimizer(act_lr,",
"tf.int32, initializer = tf.constant_initializer(0,dtype = tf.int32)) self.targets = {} self.state_desc = updater_params.get('state_desc', 'depths1')",
"entropy * 0.01 rl_opt_params, rl_opt = get_optimizer(learning_rate, self.rl_loss, ) def replace_the_nones(my_list): ''' Assumes",
"freeze_um: num_not_frozen += 1 um_opt_params, um_opt = get_optimizer(um_lr, self.um.uncertainty_loss, self.global_step, optimizer_params['uncertainty_model'], var_list =",
"type self.state_desc = data_provider.data_lengths['obs'].keys()[0] self.insert_objthere = False if data_provider.num_objthere is None else True",
"get_optimizer(um_lr, self.um.uncertainty_loss, self.global_step, optimizer_params['uncertainty_model'], var_list = self.um.var_list) self.targets['um_opt'] = um_opt if num_not_frozen ==",
"self.um.uncertainty_loss, self.global_step, optimizer_params['uncertainty_model'], var_list = self.um.var_list) self.global_step = self.global_step / 3 self.targets =",
"= get_optimizer(um_learning_rate, self.um.uncertainty_loss, self.global_step, optimizer_params['uncertainty_model']) self.um_targets = {'loss' : self.um.uncertainty_loss, 'learning_rate' : um_learning_rate,",
"= { self.wm.states : batch['depths1'], self.wm.action : batch['action'], self.wm.action_post : batch['action_post'], self.wm.obj_there :",
"for k, v in um_res.iteritems()) wm_res_new.update(um_res_new) res = wm_res_new res['global_step'] = res.pop('um_global_step') res",
"'um_lr' : um_lr, 'um_optimizer' : um_opt, 'global_step' : self.global_step, 'loss_per_example' : self.um.true_loss, 'estimated_world_loss'",
"um_opt = get_optimizer(um_lr, self.um.uncertainty_loss, self.global_step, optimizer_params['uncertainty_model'], var_list = self.um.var_list) self.global_step = self.global_step /",
": batch['action'], self.wm.action_post : batch['action_post'], self.wm.obj_there : batch['obj_there'] } res = sess.run(self.targets, feed_dict",
"= self.um.act(sess, action_samples, obs_for_actor) to_add = {'example_id' : idx, 'action_sample' : action, 'estimated_world_loss'",
"batch['action_post'], 'est_loss' : est_losses, 'action_sample' : action_sample} res['msg'] = batch['recent']['msg'] else: print('little time')",
"world_model self.um = uncertainty_model self.postprocessor = postprocessor self.global_step = tf.get_variable('global_step', [], tf.int32, initializer",
"var_list = self.wm.fut_var_list) um_opt_params, um_opt = get_optimizer(um_lr, self.um.uncertainty_loss, self.global_step, optimizer_params['uncertainty_model'], var_list = self.um.var_list)",
"prepped['objects1'], actions, action_ids, next_depths class ExperienceReplayPostprocessor: def __init__(self, big_save_keys = None, little_save_keys =",
": self.global_step, 'loss_per_example' : self.um.true_loss, 'estimated_world_loss' : self.um.estimated_world_loss, 'ans' : self.um.ans, 'oh_my_god' :",
": batch[self.state_desc][idx], 'action' : batch['action'][idx], 'action_post' : batch['action_post'][idx]} map_draw_res.append(to_add) res['map_draw'] = map_draw_res res",
"self.wm.action_post : batch['action_post'] } res = sess.run(self.targets, feed_dict = feed_dict) res = self.postprocessor.postprocess(res,",
"self.targets['global_step'] = self.global_step global_increment = tf.assign_add(self.global_step, 1) um_increment = tf.assign_add(self.um.step, 1) self.targets.update({'global_increment' :",
"self.data_provider = data_provider\\ if isinstance(data_provider, list) else [data_provider] self.wm = models['world_model'] self.um =",
"batch['action_post'] } if self.obj_there_supervision: batch['obj_there'] = np.concatenate(batch['obj_there'], axis = 0) feed_dict[self.wm.obj_there_via_msg] = batch['obj_there']",
"(N,), dtype = dt), 'depths1' : hdf5.require_dataset('depths1', shape = (N, height, width, 3),",
"} self.targets.update({'um_loss' : self.um.uncertainty_loss, 'um_lr' : um_lr, 'um_optimizer' : um_opt, 'global_step' : self.global_step,",
"None else [] # if len(action_msg): # idx = int(action_msg[0]['id']) # action_ids_list.append(idx) #",
"in ['action', 'action_post', self.state_desc]: batch[k] = np.concatenate(batch[k], axis=0) feed_dict = { self.wm.states :",
"= [other[0] for other in batch['recent']['other']] # entropies = np.mean(entropies) # res['entropy'] =",
"run(self, sess): batch = self.dp.dequeue_batch() feed_dict = { self.wm.states : batch[self.state_desc], self.wm.action :",
"end def close(self): self.hdf5.close() class LatentUncertaintyValidator: def __init__(self, models, data_provider): self.um = models['uncertainty_model']",
"{'msg' : hdf5.require_dataset('msg', shape = (N,), dtype = dt), 'depths1' : hdf5.require_dataset('depths1', shape",
"def __init__(self, models, data_provider): self.um = models['uncertainty_model'] self.wm = models['world_model'] self.targets = {'um_loss'",
"'act_pred' : self.wm.act_pred, # 'fut_loss' : self.wm.fut_loss, 'act_loss' : self.wm.act_loss, # 'estimated_world_loss' :",
"k, v) for k, v in um_res.iteritems()) wm_res_new.update(um_res_new) res['global_step'] = res.pop('um_global_step') res =",
"run(self, sess): batch = self.dp.dequeue_batch() feed_dict = { self.wm.states : batch['depths1'], self.wm.action :",
"# print(actions.shape) # print(len(batch.next_state['action'])) # action_ids_list = [] # for i in range(2):",
"== 0: self.targets['global_step'] = self.global_step self.targets['increment'] = tf.assign_add(self.global_step, 1) else: self.global_step = self.global_step",
"% self.big_save_freq < self.big_save_len: save_keys = self.big_save_keys #est_losses = [other[1] for other in",
"k in ['action', 'action_post', 'depths1']: batch[k] = np.concatenate(batch[k], axis=0) feed_dict = { self.wm.states",
"= [other[2] for other in batch['other']] res['batch'] = {} for desc, val in",
"/ 3 self.targets = {'encoding_i' : self.wm.encoding_i, 'encoding_f' : self.wm.encoding_f, 'fut_pred' : self.wm.fut_pred,",
"= uncertainty_model self.postprocessor = postprocessor self.global_step = tf.get_variable('global_step', [], tf.int32, initializer = tf.constant_initializer(0,dtype",
"batch['action_post'] } res = sess.run(self.targets, feed_dict = feed_dict) res['batch'] = batch return res",
"map_draw_res = [] # for idx in self.map_draw_example_indices: # obs_for_actor = [batch[self.state_desc][idx][t] for",
"print('adding obj_there to feed dict') feed_dict[self.um.obj_there] = batch['obj_there'] res = sess.run(self.targets, feed_dict =",
"= { self.wm.states : batch[state_desc], self.wm.action : batch['action'], self.wm.action_post : batch['action_post'] } if",
": self.um.uncertainty_loss, 'um_lr' : um_lr, 'um_optimizer' : um_opt, # 'global_step' : self.global_step, 'loss_per_example'",
"class ActionUncertaintyValidator: def __init__(self, models, data_provider): self.um = um = models['uncertainty_model'] self.wm =",
"idx, 'action_sample' : action, 'estimated_world_loss' : estimated_world_loss, 'action_samples' : action_samples, 'depths1' : batch[self.state_desc][idx],",
": self.um.estimated_world_loss} self.dp = data_provider def run(self, sess): batch = self.dp.dequeue_batch() feed_dict =",
"we don't have repeat names def start(self, sess): self.data_provider.start_runner(sess) sess.run(tf.global_variables_initializer()) def update(self, sess,",
"um_opt_params, um_opt = get_optimizer(um_lr, self.um.uncertainty_loss, self.um_step, optimizer_params['uncertainty_model'], var_list = self.um.var_list) self.targets['um_opt'] = um_opt",
"updater_params.get('include_obj_there', False) #self.map_draw_mode = None #Map drawing. Meant to have options, but for",
"= False): if self.um.just_random: print('Selecting action at random') batch = {} for i,",
"class JustUncertaintyUpdater: def __init__(self, models, data_provider, optimizer_params, learning_rate_params, postprocessor, updater_params, action_sampler = None):",
"end = self.start + bs for k in ['depths1', 'objects1', 'images1', 'action', 'action_post']:",
"< self.big_save_len: save_keys = self.big_save_keys #est_losses = [other[1] for other in batch['other']] #action_sample",
"data_provider\\ if isinstance(data_provider, list) else [data_provider] self.wm = models['world_model'] self.um = models['uncertainty_model'] freeze_wm",
"def postprocess_batch_depth(batch, state_desc): obs, msg, act, act_post = batch depths = replace_the_nones(obs[state_desc]) obs_past",
"= [] # for idx in self.map_draw_example_indices: # obs_for_actor = [batch[self.state_desc][idx][t] for t",
"in training_results.iteritems() if pair[0] in save_keys)) #if 'other' in batch['recent']: # entropies =",
"postprocessor self.global_step = tf.get_variable('global_step', [], tf.int32, initializer = tf.constant_initializer(0,dtype = tf.int32)) self.act_step =",
"each index because action sampling is the 'batch.' self.action_sampler = action_sampler assert self.map_draw_mode",
": batch['action'], self.wm.action_post : batch['action_post'] } res = sess.run(self.targets, feed_dict = feed_dict) res",
"act_opt_params, act_opt = get_optimizer(act_lr, self.wm.act_loss, self.global_step, optimizer_params['world_model']['act_model'], var_list = self.wm.act_var_list + self.wm.encode_var_list) um_opt_params,",
"self.global_step = self.global_step / num_not_frozen self.targets['global_step'] = self.global_step self.targets.update({'act_lr' : act_lr, 'um_lr' :",
"um_opt, 'global_step' : self.global_step, 'loss_per_example' : self.um.true_loss}) self.state_desc = updater_params['state_desc'] #checking that we",
"print('wm loss: ' + str(world_model_res['loss'])) um_feed_dict = { self.um.s_i : depths, self.um.action_sample :",
"'action_samples' : action_samples, 'depths1' : batch[self.state_desc][idx], 'action' : batch['action'][idx], 'action_post' : batch['action_post'][idx]} map_draw_res.append(to_add)",
"self.um.uncertainty_loss, self.um_step, optimizer_params['uncertainty_model'], var_list = self.um.var_list) self.targets['um_opt'] = um_opt self.targets['um_lr'] = um_lr self.targets['global_step']",
"width = updater_params['image_shape'] act_dim = updater_params['act_dim'] print('setting up save loc') self.hdf5 = hdf5",
"v) for k, v in um_res.iteritems()) wm_res_new.update(um_res_new) res = wm_res_new res['global_step'] = res.pop('um_global_step')",
"res['batch'] = {} for desc, val in batch.iteritems(): if desc not in ['recent',",
"and msg['msg']['action_type']['OBJ_ACT'] else 0 for msg in batch['recent']['msg']] res['obj_freq'] = np.mean(looking_at_obj) return res",
"act_opt = get_optimizer(act_lr, self.wm.act_loss, self.act_step, optimizer_params['world_model']['act_model'], var_list = self.wm.act_var_list + self.wm.encode_var_list) fut_opt_params, fut_opt",
": batch['action'], self.wm.action_post : batch['action_post'] } if self.obj_there_supervision: batch['obj_there'] = np.concatenate(batch['obj_there'], axis =",
"'action_post' : batch['action_post'][idx]} # map_draw_res.append(to_add) #res['map_draw'] = map_draw_res return res class ObjectThereUpdater: def",
"depths_past, objects, actions, action_ids, depths_fut # def postprocess_batch_for_actionmap(batch): # prepped = {} #",
"actions = np.array(batch.actions) # next_depth = np.array([batch.next_state['depths1']]) # return depths, actions, next_depth def",
"else [] if len(action_msg): idx = int(action_msg[0]['id']) else: idx = -10000#just something that's",
"!= set(self.um.readouts.keys()) def update(self, sess, visualize = False): if self.um.just_random: print('Selecting action at",
": wm_opt, 'prediction' : self.world_model.pred, 'tv' : self.world_model.tv} self.inc_step = self.global_step.assign_add(1) self.wm_lr_params, um_learning_rate",
"action_sampler #assert self.map_draw_mode == 'specified_indices' and self.action_sampler is not None, (self.map_draw_mode, action_sampler) #self.map_draw_example_indices",
"big_save_freq self.state_descriptor = state_descriptor self.big_save_keys.append('map_draw') self.little_save_keys.append('map_draw') self.big_save_keys.extend(['act_lr', 'um_lr']) self.little_save_keys.extend(['act_lr', 'um_lr']) def postprocess(self, training_results,",
"self.global_step = tf.get_variable('global_step', [], tf.int32, initializer = tf.constant_initializer(0,dtype = tf.int32)) self.act_step = tf.get_variable('act_step',",
"False): batch = self.data_provider.dequeue_batch() state_desc = self.state_desc #depths, actions, actions_post, next_depth = postprocess_batch_depth(batch,",
"dtype = tf.int32)) print(learning_rate_params.keys()) um_lr_params, um_lr = get_learning_rate(self.global_step, **learning_rate_params['uncertainty_model']) um_opt_params, um_opt = get_optimizer(um_lr,",
"'um_optimizer' : um_opt, 'estimated_world_loss' : self.um.estimated_world_loss, 'um_loss' : self.um.uncertainty_loss, 'loss_per_example' : self.um.true_loss, 'global_step'",
"batch['action_post'], self.wm.obj_there : batch['obj_there'] } res = sess.run(self.targets, feed_dict = feed_dict) res['batch'] =",
"learning_rate_params, postprocessor, updater_params = None): self.data_provider = data_provider self.wm = world_model self.um =",
"= self.um.state_descriptor wm_feed_dict = { self.world_model.states : batch[state_desc], self.world_model.action : batch['action'][:, -self.world_action_time :",
"updater_params.get('state_desc', 'depths1') self.map_draw_mode = updater_params['map_draw_mode'] #this specification specifices batch example indices for which",
"shape') # print(actions.shape) # print(len(batch.next_state['action'])) # action_ids_list = [] # for i in",
"def __init__(self, models, data_provider): self.um = um = models['uncertainty_model'] self.wm = wm =",
"self.targets.update(self.wm.readouts) self.targets.update(self.um.readouts) um_increment = tf.assign_add(self.um.step, 1) assert 'um_increment' not in self.targets self.targets['um_increment'] =",
"state_desc): obs, msg, act, act_post = batch depths = replace_the_nones(obs[state_desc]) obs_past = np.array([depths[:-1]])",
"0) feed_dict[self.wm.obj_there_via_msg] = batch['obj_there'] print('state desc! ' + self.state_desc) res = sess.run(self.targets, feed_dict",
"= map_draw_res res = self.postprocessor.postprocess(res, batch) return res, global_step class JustUncertaintyUpdater: def __init__(self,",
"height, width, 3), dtype = np.uint8), 'objects1' : hdf5.require_dataset('objects1', shape = (N, height,",
"= self.global_step res = sess.run(self.targets, feed_dict = feed_dict) glstep = res['global_step'] res =",
"get_optimizer, get_learning_rate import numpy as np import cv2 from curiosity.interaction import models import",
"h5py.File(fn, mode = 'a') dt = h5py.special_dtype(vlen = str) self.handles = {'msg' :",
"in batch['recent']['other']] res['batch'] = {'obs' : batch['depths1'], 'act' : batch['action'], 'act_post' : batch['action_post'],",
"res = self.postprocessor.postprocess(res, batch) return res class LatentFreezeUpdater: def __init__(self, models, data_provider, optimizer_params,",
"# def postprocess_batch_depth(batch): # depths = np.array([[timepoint if timepoint is not None else",
"world_model, uncertainty_model, data_provider, optimizer_params, learning_rate_params, postprocessor, updater_params): self.data_provider = data_provider self.wm = world_model",
"else [data_provider] self.wm = models['world_model'] self.um = models['uncertainty_model'] self.postprocessor = postprocessor self.global_step =",
"initializer = tf.constant_initializer(0,dtype = tf.int32)) self.act_lr_params, act_lr = get_learning_rate(self.global_step, ** learning_rate_params['world_model']['act_model']) self.um_lr_params, um_lr",
"action_sample = [other[2] for other in batch['recent']['other']] res['batch'] = {'obs' : batch['depths1'], 'act'",
"postprocessor, updater_params): self.dp = data_provider self.wm = models['world_model'] self.um = models['uncertainty_model'] self.postprocessor =",
"in batch['recent']['msg']] res['obj_freq'] = np.mean(looking_at_obj) return res class DataWriteUpdater: def __init__(self, data_provider, updater_params):",
"data_provider, optimizer_params, learning_rate_params, postprocessor): self.data_provider = data_provider self.world_model = world_model self.um = uncertainty_model",
"= np.array([replace_the_nones(act)]) actions_post = np.array([replace_the_nones(act_post)]) return obs_past, actions, actions_post, obs_fut # def postprocess_batch_depth(batch):",
"for provider_recent in batch['recent']: looking_at_obj = [1 if msg is not None and",
"bs for k in ['depths1', 'objects1', 'images1', 'action', 'action_post']: tosave = batch['recent'][k] if",
"if k not in self.um.save_to_gfs}) #this should be changed for an online data",
"hdf5.require_dataset('action', shape = (N, act_dim), dtype = np.float32), 'action_post' : hdf5.require_dataset('action_post', shape =",
"feed_dict[self.wm.obj_there_via_msg] = batch['obj_there'] print('state desc! ' + self.state_desc) res = sess.run(self.targets, feed_dict =",
": self.um.true_loss, 'estimated_world_loss' : self.um.estimated_world_loss } if self.um.exactly_whats_needed: self.targets['oh_my_god'] = self.um.oh_my_god self.state_desc =",
"sess.run(self.targets, feed_dict = feed_dict) res = self.postprocessor.postprocess(res, batch) return res class LatentFreezeUpdater: def",
": self.world_model.tv} self.inc_step = self.global_step.assign_add(1) self.um_lr_params, um_learning_rate = get_learning_rate(self.global_step, **learning_rate_params['uncertainty_model']) self.um_lr_params, um_opt =",
"bs = len(batch['recent']['msg']) end = self.start + bs for k in ['depths1', 'objects1',",
"hdf5.require_dataset('objects1', shape = (N, height, width, 3), dtype = np.uint8), 'images1': hdf5.require_dataset('images1', shape",
"self.global_step res = sess.run(self.targets, feed_dict = feed_dict) global_step = res['global_step'] if self.map_draw_mode is",
"parallelization. Not finished! ''' def __init__(world_model, rl_model, data_provider, eta): self.data_provider = data_provider self.world_model",
"[1]) * self.adv) vf_loss = .5 * tf.reduce_sum(tf.square(rl_model.vf - self.r)) entropy = -tf.reduce_sum(prob_tf",
"batch['msg'][-1] entropies = [other[0] for other in batch['recent']['other']] entropies = np.mean(entropies) res['entropy'] =",
"sess): self.data_provider.start_runner(sess) sess.run(tf.global_variables_initializer()) def update(self, sess, visualize = False): batch = self.data_provider.dequeue_batch() state_desc",
": batch[state_desc], self.world_model.action : batch['action'][:, -self.world_action_time : ] } world_model_res = sess.run(self.world_model_targets, feed_dict",
"= np.float32), 'action_post' : hdf5.require_dataset('action_post', shape = (N, act_dim), dtype = np.float32)} print('save",
"wm_learning_rate = get_learning_rate(self.global_step, ** learning_rate_params['world_model']) self.wm_opt_params, wm_opt = get_optimizer(wm_learning_rate, self.world_model.loss, self.global_step, optimizer_params['world_model']) self.world_model_targets",
"k, v) for k, v in um_res.iteritems()) wm_res_new.update(um_res_new) res = wm_res_new res['global_step'] =",
"objects, actions, action_ids, depths_fut # def postprocess_batch_for_actionmap(batch): # prepped = {} # for",
"self.um.true_loss, 'estimated_world_loss' : self.um.estimated_world_loss, 'ans' : self.um.ans, 'oh_my_god' : self.um.oh_my_god, 'model_parameters' : self.um.var_list}",
"self.targets = {'encoding_i' : self.wm.encoding_i, 'encoding_f' : self.wm.encoding_f, 'fut_pred' : self.wm.fut_pred, 'act_pred' :",
"= tf.placeholder(tf.float32, [None]) self.r = tf.placeholder(tf.float32, [None]) log_prob_tf = tf.nn.log_softmax(rl_model.logits) prob_tf = tf.nn.softmax(rl_model.logits)",
"- entropy * 0.01 rl_opt_params, rl_opt = get_optimizer(learning_rate, self.rl_loss, ) def replace_the_nones(my_list): '''",
"#self.map_draw_freq = updater_params['map_draw_freq'] def update(self, sess, visualize = False): if self.um.just_random: print('Selecting action",
"assert self.map_draw_mode == 'specified_indices' and self.action_sampler is not None, (self.map_draw_mode, action_sampler) self.map_draw_example_indices =",
"'action_post' : hdf5.require_dataset('action_post', shape = (N, act_dim), dtype = np.float32)} print('save loc set",
"var_list = self.um.var_list) self.targets['um_opt'] = um_opt self.targets['um_lr'] = um_lr self.targets['global_step'] = self.global_step global_increment",
"wm_res_new = dict(('wm_' + k, v) for k, v in world_model_res.iteritems()) um_res_new =",
"msg, act, act_post = batch depths = replace_the_nones(obs[state_desc]) obs_past = np.array([depths[:-1]]) obs_fut =",
"= tosave.astype(np.float32) self.handles[k][self.start : end] = batch['recent'][k] self.handles['msg'][self.start : end] = [json.dumps(msg) for",
"updater_params['hdf5_filename'] N = updater_params['N_save'] height, width = updater_params['image_shape'] act_dim = updater_params['act_dim'] print('setting up",
"= self.postprocessor.postprocess(res, batch) return res class SquareForceMagUpdater: def __init__(self, models, data_provider, optimizer_params, learning_rate_params,",
"sess, visualize = False): if self.um.just_random: print('Selecting action at random') batch = {}",
"dtype = dt), 'depths1' : hdf5.require_dataset('depths1', shape = (N, height, width, 3), dtype",
"= fut_opt self.targets['act_lr'] = act_lr self.targets['fut_lr'] = fut_lr if not freeze_um: um_lr_params, um_lr",
"= { self.wm.action : batch['action'], self.wm.action_post : batch['action_post'], self.um.obj_there : batch['obj_there'] } res",
"get_optimizer(act_lr, self.wm.act_loss, self.act_step, optimizer_params['world_model']['act_model'], var_list = self.wm.act_var_list + self.wm.encode_var_list) fut_opt_params, fut_opt = get_optimizer(fut_lr,",
"updater_params['map_draw_mode'] #this specification specifices batch example indices for which we do a forward",
"self.um_lr_params, um_opt = get_optimizer(um_learning_rate, self.um.uncertainty_loss, self.global_step, optimizer_params['uncertainty_model']) self.global_step = self.global_step / 2 self.um_targets",
"class FreezeUpdater: def __init__(self, models, data_provider, optimizer_params, learning_rate_params, postprocessor, updater_params): self.data_provider = data_provider",
"in batch: batch[k].append(provider_batch[k]) else: batch[k] = [provider_batch[k]] for k in ['action', 'action_post', self.state_desc]:",
"state_desc = self.um.state_descriptor wm_feed_dict = { self.world_model.states : batch[state_desc], self.world_model.action : batch['action'][:, -self.world_action_time",
"== 'obj_there': res['batch'][desc] = val elif desc != 'recent': res['batch'][desc] = val[:, -1]",
"batch[state_desc], self.wm.action : batch['action'], self.wm.action_post : batch['action_post'] } if self.um.insert_obj_there: print('adding obj_there to",
"batch) return res, global_step class FreezeUpdater: def __init__(self, models, data_provider, optimizer_params, learning_rate_params, postprocessor,",
"+ self.wm.encode_var_list) fut_opt_params, fut_opt = get_optimizer(fut_lr, self.wm.fut_loss, self.fut_step, optimizer_params['world_model']['fut_model'], var_list = self.wm.fut_var_list) self.targets['act_opt']",
"= np.concatenate(batch['obj_there'], axis = 0) feed_dict[self.wm.obj_there_via_msg] = batch['obj_there'] print('state desc! ' + self.state_desc)",
"self.wm.act_pred, # 'fut_loss' : self.wm.fut_loss, 'act_loss' : self.wm.act_loss, # 'estimated_world_loss' : self.um.estimated_world_loss, #",
"self.start + bs for k in ['depths1', 'objects1', 'images1', 'action', 'action_post']: tosave =",
"= self.dp.dequeue_batch() state_desc = self.state_desc feed_dict = { self.wm.states : batch[state_desc], self.wm.action :",
"for other in batch['recent']['other']] # entropies = np.mean(entropies) # res['entropy'] = entropies if",
"models['uncertainty_model'] self.postprocessor = postprocessor self.global_step = tf.get_variable('global_step', [], tf.int32, initializer = tf.constant_initializer(0, dtype",
"tf.constant_initializer(0,dtype = tf.int32)) self.act_lr_params, act_lr = get_learning_rate(self.global_step, ** learning_rate_params['world_model']['act_model']) self.fut_lr_params, fut_lr = get_learning_rate(self.global_step,",
": self.um.estimated_world_loss } if self.um.exactly_whats_needed: self.targets['oh_my_god'] = self.um.oh_my_god self.state_desc = updater_params['state_desc'] def update(self,",
"self.wm.states : batch[self.state_desc], self.wm.action : batch['action'], self.wm.action_post : batch['action_post'] } self.targets['global_step'] = self.global_step",
"np.array([[np.zeros(batch.next_state['action'][-1].shape, batch.next_state['action'][-1].dtype) if timepoint is None else timepoint for timepoint in batch.next_state['action']]]) #",
"pi_loss + 0.5 * vf_loss - entropy * 0.01 rl_opt_params, rl_opt = get_optimizer(learning_rate,",
"= self.action_sampler.sample_actions() action, entropy, estimated_world_loss = self.um.act(sess, action_samples, obs_for_actor) to_add = {'example_id' :",
"var_list = self.wm.fut_var_list) self.targets['act_opt'] = act_opt self.targets['fut_opt'] = fut_opt self.targets['act_lr'] = act_lr self.targets['fut_lr']",
"{'example_id' : idx, 'action_sample' : action, 'estimated_world_loss' : estimated_world_loss, 'action_samples' : action_samples, 'depths1'",
"* vf_loss - entropy * 0.01 rl_opt_params, rl_opt = get_optimizer(learning_rate, self.rl_loss, ) def",
"v for k, v in self.um.readouts.items() if k not in self.um.save_to_gfs}) #this should",
"assuming one sort of specification self.state_desc = updater_params.get('state_desc', 'depths1') self.map_draw_mode = updater_params['map_draw_mode'] #this",
"big_save_len = None, big_save_freq = None, state_descriptor = None): self.big_save_keys = big_save_keys self.little_save_keys",
"act_lr self.targets['fut_lr'] = fut_lr if not freeze_um: um_lr_params, um_lr = get_learning_rate(self.um_step, **learning_rate_params['uncertainty_model']) um_opt_params,",
"LatentFreezeUpdater: def __init__(self, models, data_provider, optimizer_params, learning_rate_params, postprocessor, updater_params): self.data_provider = data_provider\\ if",
": self.um.uncertainty_loss, 'um_optimizer' : um_opt, 'global_step' : self.global_step, 'loss_per_example' : self.um.true_loss, 'estimated_world_loss' :",
"in obs['depths1']] for obs in batch.states]) # actions = np.array(batch.actions) # next_depth =",
"self.um.uncertainty_loss, 'loss_per_example' : self.um.true_loss, 'global_step' : self.global_step} def update(self, sess, visualize = False):",
"None, big_save_len = None, big_save_freq = None, state_descriptor = None): self.big_save_keys = big_save_keys",
"= feed_dict) res = self.postprocessor.postprocess(res, batch) return res class LatentFreezeUpdater: def __init__(self, models,",
"batch['action_post'] } res = sess.run(self.targets, feed_dict = feed_dict) res = self.postprocessor.postprocess(res, batch) return",
"= (N, act_dim), dtype = np.float32), 'action_post' : hdf5.require_dataset('action_post', shape = (N, act_dim),",
"in self.um.save_to_gfs}) #this should be changed for an online data provider, set to",
"not freeze_um: um_lr_params, um_lr = get_learning_rate(self.um_step, **learning_rate_params['uncertainty_model']) um_opt_params, um_opt = get_optimizer(um_lr, self.um.uncertainty_loss, self.um_step,",
"{} for i, dp in enumerate(self.data_provider): provider_batch = dp.dequeue_batch() for k in provider_batch:",
"None, big_save_freq = None, state_descriptor = None): self.big_save_keys = big_save_keys self.little_save_keys = little_save_keys",
"cv2.imshow('tv', world_model_res['tv'][0] / 4.) cv2.imshow('processed0', world_model_res['given'][0, 0] / 4.) cv2.imshow('processed1', world_model_res['given'][0, 1] /",
"1) else: self.global_step = self.global_step / num_not_frozen self.targets['global_step'] = self.global_step self.targets.update({'act_lr' : act_lr,",
"'loss_per_example' : self.um.true_loss, 'estimated_world_loss' : self.um.estimated_world_loss, 'ans' : self.um.ans, 'oh_my_god' : self.um.oh_my_god, 'model_parameters'",
"batch[state_desc], self.wm.action : batch['action'], self.wm.obj_there : batch['obj_there'] } res = sess.run(self.targets, feed_dict =",
"for k in ['action', 'action_post', self.state_desc]: batch[k] = np.concatenate(batch[k], axis=0) feed_dict = {",
"entropies = [other[0] for other in batch['recent']['other']] # entropies = np.mean(entropies) # res['entropy']",
": depths, self.um.action_sample : actions[:, -1], self.um.true_loss : np.array([world_model_res['loss']]) } um_res = sess.run(self.um_targets,",
"= {} for desc, val in batch.iteritems(): if desc not in ['recent', 'depths1',",
"update(self): batch = self.data_provider.dequeue_batch() bs = len(batch['recent']['msg']) end = self.start + bs for",
"= tf.assign_add(self.um.step, 1) assert 'um_increment' not in self.targets self.targets['um_increment'] = um_increment self.obj_there_supervision =",
"v) for (k, v) in training_results.iteritems() if k in save_keys)) #res['msg'] = batch['msg'][-1]",
"np.uint8), 'images1': hdf5.require_dataset('images1', shape = (N, height, width, 3), dtype = np.uint8), 'action'",
"{ self.um.s_i : batch[state_desc][:, :-1], self.um.action_sample : batch['action'][:, -1], self.um.true_loss : world_model_res['loss_per_example'] }",
"self.wm.obj_there : batch['obj_there'] } return sess.run(self.targets, feed_dict = feed_dict) class ActionUncertaintyValidator: def __init__(self,",
"in my_list] def postprocess_batch_depth(batch, state_desc): obs, msg, act, act_post = batch depths =",
"= self.postprocessor.postprocess(res, batch) return res, global_step class ActionUncertaintyUpdater: def __init__(self, models, data_provider, optimizer_params,",
"if k in ['action', 'action_post']: tosave = tosave.astype(np.float32) self.handles[k][self.start : end] = batch['recent'][k]",
"self.postprocessor.postprocess(res, batch) return res class LatentFreezeUpdater: def __init__(self, models, data_provider, optimizer_params, learning_rate_params, postprocessor,",
"batch = {} for i, dp in enumerate(self.data_provider): provider_batch = dp.dequeue_batch() for k",
"forward pass each index because action sampling is the 'batch.' self.action_sampler = action_sampler",
"# entropies = [other[0] for other in batch['recent']['other']] # entropies = np.mean(entropies) #",
"== 0: if self.map_draw_mode == 'specified_indices': map_draw_res = [] for idx in self.map_draw_example_indices:",
"'action_post' : batch['action_post'][idx]} map_draw_res.append(to_add) res['map_draw'] = map_draw_res res = self.postprocessor.postprocess(res, batch) return res,",
"a forward pass. #need to do one forward pass each index because action",
"{} self.state_desc = updater_params.get('state_desc', 'depths1') if not freeze_wm: num_not_frozen += 1 act_opt_params, act_opt",
"batch['depths1'], self.wm.action : batch['action'], self.wm.action_post : batch['action_post'] } res = sess.run(self.targets, feed_dict =",
"um_lr, 'um_optimizer' : um_opt, # 'global_step' : self.global_step, 'loss_per_example' : self.um.true_loss}) self.map_draw_mode =",
"= sess.run(self.targets, feed_dict = feed_dict) glstep = res['global_step'] res = self.postprocessor.postprocess(res, batch) return",
"prepped = {} # for desc in ['depths1', 'objects1']: # prepped[desc] = np.array([[timepoint",
"= um_increment self.obj_there_supervision = updater_params.get('include_obj_there', False) #self.map_draw_mode = None #Map drawing. Meant to",
"depths, self.um.action_sample : actions[:, -1], self.um.true_loss : np.array([world_model_res['loss']]) } um_res = sess.run(self.um_targets, feed_dict",
"''' Provides the training step. This is probably where we can put parallelization.",
"= np.array([depths[1:]]) actions = np.array([replace_the_nones(act)]) actions_post = np.array([replace_the_nones(act_post)]) return obs_past, actions, actions_post, obs_fut",
"= [json.dumps(msg) for msg in batch['recent']['msg']] self.start = end def close(self): self.hdf5.close() class",
"np.array([depths[1:]]) actions = np.array([replace_the_nones(act)]) actions_post = np.array([replace_the_nones(act_post)]) return obs_past, actions, actions_post, obs_fut #",
"= { self.wm.states : batch['depths1'], self.wm.action : batch['action'], self.wm.obj_there : batch['obj_there'] } return",
"[provider_batch[k]] for k in ['action', 'action_post', 'depths1']: batch[k] = np.concatenate(batch[k], axis=0) state_desc =",
"for other in batch['other']] res['batch'] = {} for desc, val in batch.iteritems(): if",
"= batch['obj_there'] print('state desc! ' + self.state_desc) res = sess.run(self.targets, feed_dict = feed_dict)",
"next_depth = postprocess_batch_depth(batch, state_desc) feed_dict = { self.wm.states : batch[state_desc], self.wm.action : batch['action'],",
"actions, action_ids, next_depths class ExperienceReplayPostprocessor: def __init__(self, big_save_keys = None, little_save_keys = None,",
"> 0: mean_per_provider = [] for provider_recent in batch['recent']: looking_at_obj = [1 if",
"= sess.run(self.targets, feed_dict = feed_dict) res = self.postprocessor.postprocess(res, batch) return res class SquareForceMagUpdater:",
"if isinstance(data_provider, list) else [data_provider] self.wm = models['world_model'] self.um = models['uncertainty_model'] self.postprocessor =",
"case it for online res['recent'] = {} #if self.map_draw_mode == 'specified_indices': # map_draw_res",
"not None, (self.map_draw_mode, action_sampler) self.map_draw_example_indices = updater_params['map_draw_example_indices'] self.map_draw_timestep_indices = updater_params['map_draw_timestep_indices'] self.map_draw_freq = updater_params['map_draw_freq']",
"# res['entropy'] = entropies if 'msg' in batch['recent']: looking_at_obj = [1 if msg",
"elif type(batch['recent']) == list and len(batch['recent'][0]) > 0: mean_per_provider = [] for provider_recent",
"= get_optimizer(um_lr, self.um.uncertainty_loss, self.global_step, optimizer_params['uncertainty_model'], var_list = self.um.var_list) self.targets = {'global_step' : self.global_step,",
"'learning_rate' : um_learning_rate, 'optimizer' : um_opt, 'global_step' : self.global_step} self.postprocessor = postprocessor def",
"[], tf.int32, initializer = tf.constant_initializer(0,dtype = tf.int32)) self.um_step = tf.get_variable('ext_uncertainty_step', [], tf.int32, initializer",
"{ self.wm.states : batch[state_desc], self.wm.action : batch['action'], self.wm.obj_there : batch['obj_there'] } res =",
"in self.map_draw_timestep_indices] action_samples = self.action_sampler.sample_actions() action, entropy, estimated_world_loss = self.um.act(sess, action_samples, obs_for_actor) to_add",
"i in range(2): # action_msg = batch.next_state['msg'][i]['msg']['actions'] if batch.next_state['msg'][i] is not None else",
"self.um_lr_params, um_lr = get_learning_rate(self.global_step, ** learning_rate_params['uncertainty_model']) act_opt_params, act_opt = get_optimizer(act_lr, self.wm.act_loss, self.global_step, optimizer_params['world_model']['act_model'],",
"self.um_step = tf.get_variable('ext_uncertainty_step', [], tf.int32, initializer = tf.constant_initializer(0,dtype = tf.int32)) self.targets = {}",
"self.rl_model = rl_model self.eta = eta self.global_step = tf.get_variable('global_step', [], tf.int32, initializer =",
"= val res['recent'] = batch['recent'] else: save_keys = self.little_save_keys res.update(dict(pair for pair in",
"shape = (N, act_dim), dtype = np.float32), 'action_post' : hdf5.require_dataset('action_post', shape = (N,",
"self.wm.states : batch['depths1'], self.wm.action : batch['action'], self.wm.action_post : batch['action_post'], self.wm.obj_there : batch['obj_there'] }",
"= get_optimizer(um_lr, self.um.uncertainty_loss, self.global_step, optimizer_params['uncertainty_model'], var_list = self.um.var_list) self.global_step = self.global_step / 3",
"= self.wm.act_var_list + self.wm.encode_var_list) um_opt_params, um_opt = get_optimizer(um_lr, self.um.uncertainty_loss, self.global_step, optimizer_params['uncertainty_model'], var_list =",
"= [other[1] for other in batch['other']] #action_sample = [other[2] for other in batch['other']]",
"batch['recent'][k] self.handles['msg'][self.start : end] = [json.dumps(msg) for msg in batch['recent']['msg']] self.start = end",
": wm_learning_rate, 'optimizer' : wm_opt, 'prediction' : self.world_model.pred, 'tv' : self.world_model.tv} self.inc_step =",
"= self.data_provider.dequeue_batch() bs = len(batch['recent']['msg']) end = self.start + bs for k in",
"[], tf.int32, initializer = tf.constant_initializer(0,dtype = tf.int32)) self.um_lr_params, um_lr = get_learning_rate(self.global_step, ** learning_rate_params['uncertainty_model'])",
"'ans' : self.um.ans, 'oh_my_god' : self.um.oh_my_god, 'model_parameters' : self.um.var_list} def update(self, sess): batch",
"set(self.wm.readouts.keys()) != set(self.um.readouts.keys()) self.targets.update(self.wm.readouts) self.targets.update(self.um.readouts) um_increment = tf.assign_add(self.um.step, 1) assert 'um_increment' not in",
"um_res.iteritems()) wm_res_new.update(um_res_new) res = wm_res_new res['global_step'] = res.pop('um_global_step') res = self.postprocessor.postprocess(wm_res_new, batch) return",
"= (N, height, width, 3), dtype = np.uint8), 'images1': hdf5.require_dataset('images1', shape = (N,",
"np.float32), 'action_post' : hdf5.require_dataset('action_post', shape = (N, act_dim), dtype = np.float32)} print('save loc",
"prepped[desc] = np.array([[timepoint if timepoint is not None else np.zeros(obs[desc][-1].shape, dtype = obs[desc][-1].dtype)",
"def update(self, sess, visualize = False): batch = self.data_provider.dequeue_batch() state_desc = self.um.state_descriptor wm_feed_dict",
"from tfutils.base import get_optimizer, get_learning_rate import numpy as np import cv2 from curiosity.interaction",
"% self.big_save_freq < self.big_save_len: print('big time') save_keys = self.big_save_keys est_losses = [other[1] for",
"models['world_model'] self.targets = {'um_loss' : self.um.uncertainty_loss, 'loss_per_example' : self.um.true_loss, 'estimated_world_loss' : self.um.estimated_world_loss} self.dp",
": self.um.uncertainty_loss, 'loss_per_example' : self.um.true_loss} self.dp = data_provider def run(self, sess): batch =",
"self.data_provider = data_provider \\ if isinstance(data_provider, list) else [data_provider] self.wm = models['world_model'] self.um",
"batch) return res, global_step class JustUncertaintyUpdater: def __init__(self, models, data_provider, optimizer_params, learning_rate_params, postprocessor,",
": action, 'estimated_world_loss' : estimated_world_loss, 'action_samples' : action_samples, 'depths1' : batch[self.state_desc][idx], 'action' :",
"self.wm = models['world_model'] self.targets = { 'act_pred' : self.wm.act_pred, 'fut_loss' : self.wm.fut_loss, 'act_loss'",
"None and global_step % self.map_draw_freq == 0: # if self.map_draw_mode == 'specified_indices': #",
"self.um.uncertainty_loss, 'learning_rate' : um_learning_rate, 'optimizer' : um_opt, 'global_step' : self.global_step} self.postprocessor = postprocessor",
"self.wm.act_loss, # 'estimated_world_loss' : self.um.estimated_world_loss, # '' # } #self.targets.update({'um_loss' : self.um.uncertainty_loss, 'um_lr'",
"postprocess_batch_for_actionmap(batch, state_desc): obs, msg, act = batch prepped = {} depths = replace_the_nones(obs[state_desc])",
": um_learning_rate, 'optimizer' : um_opt, 'global_step' : self.global_step} self.postprocessor = postprocessor def start(self,",
"sess.run(self.world_model_targets, feed_dict = wm_feed_dict) if visualize: cv2.imshow('pred', world_model_res['prediction'][0] / 4.)#TODO clean up w",
"fut_lr, 'fut_loss' : self.wm.fut_loss, 'act_loss' : self.wm.act_loss, 'estimated_world_loss' : self.um.estimated_world_loss } self.targets.update({'um_loss' :",
"{ self.world_model.states : batch[state_desc], self.world_model.action : batch['action'][:, -self.world_action_time : ] } world_model_res =",
"= updater_params['map_draw_example_indices'] #self.map_draw_timestep_indices = updater_params['map_draw_timestep_indices'] #self.map_draw_freq = updater_params['map_draw_freq'] def update(self, sess, visualize =",
"global_step = training_results['global_step'] res = {} if (global_step) % self.big_save_freq < self.big_save_len: save_keys",
"batch['action_post'][idx]} map_draw_res.append(to_add) res['map_draw'] = map_draw_res res = self.postprocessor.postprocess(res, batch) return res, global_step class",
"world_model_res['prediction'][0] / 4.)#TODO clean up w colors cv2.imshow('tv', world_model_res['tv'][0] / 4.) cv2.imshow('processed0', world_model_res['given'][0,",
"um_lr = get_learning_rate(self.global_step, ** learning_rate_params['uncertainty_model']) num_not_frozen = 0 self.targets = {} self.state_desc =",
"optimizer_params['world_model']) self.world_model_targets = {'given' : self.world_model.processed_input, 'loss' : self.world_model.loss, 'learning_rate' : wm_learning_rate, 'optimizer'",
"batch['recent'][k] if k in ['action', 'action_post']: tosave = tosave.astype(np.float32) self.handles[k][self.start : end] =",
"self.global_step, optimizer_params['uncertainty_model'], var_list = self.um.var_list) self.targets = {'global_step' : self.global_step, 'um_optimizer' : um_opt}",
"np.mean(looking_at_obj) return res class DataWriteUpdater: def __init__(self, data_provider, updater_params): self.data_provider = data_provider fn",
"self.um.ans, 'oh_my_god' : self.um.oh_my_god, 'model_parameters' : self.um.var_list} def update(self, sess): batch = self.dp.dequeue_batch()",
"batch = self.data_provider.dequeue_batch() state_desc = self.state_desc #depths, actions, actions_post, next_depth = postprocess_batch_depth(batch, state_desc)",
"state_desc): obs, msg, act = batch prepped = {} depths = replace_the_nones(obs[state_desc]) depths_past",
"msg in provider_recent['msg']] mean_per_provider.append(np.mean(looking_at_obj)) res['obj_freq'] = np.mean(mean_per_provider) res['obj_freq_per_provider_noprint'] = mean_per_provider return res class",
"for obs in batch.states]) # actions = np.array(batch.actions) # next_depth = np.array([batch.next_state['depths1']]) #",
"optimizer_params, learning_rate_params, postprocessor, updater_params): self.data_provider = data_provider self.wm = world_model self.um = uncertainty_model",
"' + str(world_model_res['loss'])) um_feed_dict = { self.um.s_i : depths, self.um.action_sample : actions[:, -1],",
"idx in self.map_draw_example_indices: obs_for_actor = [batch[self.state_desc][idx][t] for t in self.map_draw_timestep_indices] action_samples = self.action_sampler.sample_actions()",
"data_provider self.wm = world_model self.um = uncertainty_model self.postprocessor = postprocessor self.global_step = tf.get_variable('global_step',",
"not None else np.zeros(obs[desc][-1].shape, dtype = obs[desc][-1].dtype) for timepoint in obs[desc]] for obs",
"UncertaintyPostprocessor: def __init__(self, big_save_keys = None, little_save_keys = None, big_save_len = None, big_save_freq",
"if k in batch: batch[k].append(provider_batch[k]) else: batch[k] = [provider_batch[k]] for k in ['action',",
"um_opt, 'global_step' : self.global_step} self.postprocessor = postprocessor def start(self, sess): self.data_provider.start_runner(sess) sess.run(tf.global_variables_initializer()) def",
"res class UncertaintyPostprocessor: def __init__(self, big_save_keys = None, little_save_keys = None, big_save_len =",
"updater_params = None): self.data_provider = data_provider self.wm = world_model self.um = uncertainty_model self.postprocessor",
": batch ['action_post'] } if self.insert_objthere: feed_dict[self.wm.obj_there_via_msg] = batch['obj_there'] res = sess.run(self.targets, feed_dict",
"= { self.wm.states : batch[self.state_desc], self.wm.action : batch['action'], self.wm.action_post : batch ['action_post'] }",
"optimizer_params['world_model']) self.world_model_targets = {'given' : self.world_model.processed_input, 'loss' : self.world_model.loss, 'loss_per_example' : self.world_model.loss_per_example, 'learning_rate'",
"= postprocessor self.global_step = tf.get_variable('global_step', [], tf.int32, initializer = tf.constant_initializer(0,dtype = tf.int32)) self.act_step",
"self.um = model['uncertainty_model'] self.targets = {} self.targets.update({k : v for k, v in",
"self.wm.fut_loss, self.fut_step, optimizer_params['world_model']['fut_model'], var_list = self.wm.fut_var_list) self.targets['act_opt'] = act_opt self.targets['fut_opt'] = fut_opt self.targets['act_lr']",
"def __init__(self, world_model, uncertainty_model, data_provider, optimizer_params, learning_rate_params, postprocessor, updater_params): self.data_provider = data_provider self.wm",
"if not freeze_um: um_lr_params, um_lr = get_learning_rate(self.um_step, **learning_rate_params['uncertainty_model']) um_opt_params, um_opt = get_optimizer(um_lr, self.um.uncertainty_loss,",
"self.state_desc feed_dict = { self.wm.states : batch[state_desc], self.wm.action : batch['action'], self.wm.obj_there : batch['obj_there']",
"t in self.map_draw_timestep_indices] action_samples = self.action_sampler.sample_actions() action, entropy, estimated_world_loss = self.um.act(sess, action_samples, obs_for_actor)",
"self.world_model.processed_input, 'loss' : self.world_model.loss, 'loss_per_example' : self.world_model.loss_per_example, 'learning_rate' : wm_learning_rate, 'optimizer' : wm_opt,",
": self.world_model.loss, 'learning_rate' : wm_learning_rate, 'optimizer' : wm_opt, 'prediction' : self.world_model.pred, 'tv' :",
"= 'depths1' #depths, actions, actions_post, next_depth = postprocess_batch_depth(batch, state_desc) feed_dict = { self.wm.states",
"= get_optimizer(um_learning_rate, self.um.uncertainty_loss, self.global_step, optimizer_params['uncertainty_model']) self.global_step = self.global_step / 2 self.um_targets = {'loss'",
": batch['depths1'], self.wm.action : batch['action'], self.wm.action_post : batch['action_post'], self.wm.obj_there : batch['obj_there'] } res",
"we do a forward pass. #need to do one forward pass each index",
"act_opt = get_optimizer(act_lr, self.wm.act_loss, self.global_step, optimizer_params['world_model']['act_model'], var_list = self.wm.act_var_list + self.wm.encode_var_list) fut_opt_params, fut_opt",
"world_model.action_one_hot.get_shape().as_list()[1:]) self.adv = tf.placeholder(tf.float32, [None]) self.r = tf.placeholder(tf.float32, [None]) log_prob_tf = tf.nn.log_softmax(rl_model.logits) prob_tf",
"+ k, v) for k, v in um_res.iteritems()) wm_res_new.update(um_res_new) res = wm_res_new res['global_step']",
"action_ids, next_depths class ExperienceReplayPostprocessor: def __init__(self, big_save_keys = None, little_save_keys = None, big_save_len",
"'loss_per_example' : self.um.true_loss} self.dp = data_provider def run(self, sess): batch = self.dp.dequeue_batch() feed_dict",
"now just assuming one sort of specification #self.state_desc = updater_params.get('state_desc', 'depths1') #self.map_draw_mode =",
"self.insert_objthere = False if data_provider.num_objthere is None else True def run(self, sess): batch",
"action_ids_list = [] # for i in range(2): # action_msg = batch.next_state['msg'][i]['msg']['actions'] if",
"= self.um.var_list) self.targets = {'um_loss' : self.um.uncertainty_loss, 'um_lr' : um_lr, 'um_optimizer' : um_opt,",
"} self.state_desc = updater_params['state_desc'] def update(self, sess, visualize = False): batch = self.data_provider.dequeue_batch()",
"sess): batch = self.dp.dequeue_batch() feed_dict = { self.wm.action : batch['action'], self.wm.action_post : batch['action_post'],",
"= self.global_step self.targets['increment'] = tf.assign_add(self.global_step, 1) else: self.global_step = self.global_step / num_not_frozen self.targets['global_step']",
"feed_dict) res = self.postprocessor.postprocess(res, batch) return res class UncertaintyUpdater: def __init__(self, world_model, uncertainty_model,",
"k, v) for k, v in world_model_res.iteritems()) um_res_new = dict(('um_' + k, v)",
"self.global_step, 'um_optimizer' : um_opt} assert set(self.wm.readouts.keys()) != set(self.um.readouts.keys()) self.targets.update(self.wm.readouts) self.targets.update(self.um.readouts) #self.targets = {",
"dict') feed_dict[self.um.obj_there] = batch['obj_there'] res = sess.run(self.targets, feed_dict = feed_dict) res = self.postprocessor.postprocess(res,",
"= np.array([replace_the_nones(act_post)]) return obs_past, actions, actions_post, obs_fut # def postprocess_batch_depth(batch): # depths =",
"self.wm.states : batch['depths1'], self.wm.action : batch['action'], self.wm.obj_there : batch['obj_there'] } return sess.run(self.targets, feed_dict",
"self.wm = model['world_model'] self.um = model['uncertainty_model'] self.targets = {} self.targets.update({k : v for",
"update(self, sess, visualize = False): batch = self.dp.dequeue_batch() state_desc = self.state_desc feed_dict =",
": batch[state_desc], self.wm.action : batch['action'], self.wm.action_post : batch['action_post'] } if self.um.insert_obj_there: print('adding obj_there",
"'depths1']: batch[k] = np.concatenate(batch[k], axis=0) feed_dict = { self.wm.states : batch[self.state_desc], self.wm.action :",
"self.state_desc #depths, actions, actions_post, next_depth = postprocess_batch_depth(batch, state_desc) feed_dict = { self.wm.states :",
"self.big_save_freq < self.big_save_len: save_keys = self.big_save_keys #est_losses = [other[1] for other in batch['other']]",
"self.wm.action : batch['action'], self.wm.action_post : batch['action_post'], self.wm.obj_there : batch['obj_there'] } res = sess.run(self.targets,",
"'fut_loss' : self.wm.fut_loss, 'act_loss' : self.wm.act_loss, 'estimated_world_loss' : self.um.estimated_world_loss } self.targets.update({'um_loss' : self.um.uncertainty_loss,",
"'optimizer' : wm_opt, 'prediction' : self.world_model.pred, 'tv' : self.world_model.tv} self.inc_step = self.global_step.assign_add(1) self.wm_lr_params,",
": self.wm.fut_loss, 'act_loss' : self.wm.act_loss, # 'estimated_world_loss' : self.um.estimated_world_loss, # '' # }",
"rl_opt_params, rl_opt = get_optimizer(learning_rate, self.rl_loss, ) def replace_the_nones(my_list): ''' Assumes my_list[-1] is np",
"next_depths = np.array([batch.next_state['depths1']]) # return prepped['depths1'], prepped['objects1'], actions, action_ids, next_depths class ExperienceReplayPostprocessor: def",
"random') batch = {} for i, dp in enumerate(self.data_provider): provider_batch = dp.dequeue_batch() for",
"np.array([action_ids_list]) # next_depths = np.array([batch.next_state['depths1']]) # return prepped['depths1'], prepped['objects1'], actions, action_ids, next_depths class",
"= get_learning_rate(self.global_step, **learning_rate_params['uncertainty_model']) self.wm_lr_params, um_opt = get_optimizer(um_learning_rate, self.um.uncertainty_loss, self.global_step, optimizer_params['uncertainty_model']) self.um_targets = {'loss'",
"in provider_recent['msg']] mean_per_provider.append(np.mean(looking_at_obj)) res['obj_freq'] = np.mean(mean_per_provider) res['obj_freq_per_provider_noprint'] = mean_per_provider return res class UncertaintyPostprocessor:",
"get_optimizer(um_lr, self.um.uncertainty_loss, self.global_step, optimizer_params['uncertainty_model'], var_list = self.um.var_list) self.global_step = self.global_step / 3 self.targets",
"sess.run(self.targets, feed_dict = feed_dict) res.pop('um_increment') res.pop('global_increment') global_step = res['global_step'] #if self.map_draw_mode is not",
"self.targets.update({'act_lr' : act_lr, 'um_lr' : um_lr}) assert set(self.wm.readouts.keys()) != set(self.um.readouts.keys()) self.targets.update(self.wm.readouts) self.targets.update(self.um.readouts) um_increment",
"pass. #need to do one forward pass each index because action sampling is",
"from curiosity.interaction import models import h5py import json class RawDepthDiscreteActionUpdater: ''' Provides the",
"data_provider): self.um = models['uncertainty_model'] self.wm = models['world_model'] self.targets = { 'act_pred' : self.wm.act_pred,",
"['depths1', 'objects1', 'images1', 'action', 'action_post']: tosave = batch['recent'][k] if k in ['action', 'action_post']:",
"learning_rate_params['uncertainty_model']) num_not_frozen = 0 self.targets = {} self.state_desc = updater_params.get('state_desc', 'depths1') if not",
"learning_rate_params['world_model']['act_model']) self.fut_lr_params, fut_lr = get_learning_rate(self.global_step, ** learning_rate_params['world_model']['fut_model']) self.um_lr_params, um_lr = get_learning_rate(self.global_step, ** learning_rate_params['uncertainty_model'])",
"print('Selecting action at random') batch = {} for i, dp in enumerate(self.data_provider): provider_batch",
": batch['obj_there'] } res = sess.run(self.targets, feed_dict = feed_dict) res = self.postprocessor.postprocess(res, batch)",
"range(2): action_msg = msg[i]['msg']['actions'] if msg[i] is not None else [] if len(action_msg):",
": self.wm.act_pred, 'act_optimizer' : act_opt, 'fut_optimizer' : fut_opt, 'act_lr' : act_lr, 'fut_lr' :",
"sess, visualize = False): batch = {} for i, dp in enumerate(self.data_provider): provider_batch",
"self.data_provider = data_provider self.world_model = world_model self.um = uncertainty_model self.global_step = tf.get_variable('global_step', [],",
": um_learning_rate, 'optimizer' : um_opt, 'global_step' : self.global_step} self.postprocessor = postprocessor self.world_action_time =",
"= tf.assign_add(self.global_step, 1) else: self.global_step = self.global_step / num_not_frozen self.targets['global_step'] = self.global_step self.targets.update({'act_lr'",
"uncertainty_model, data_provider, optimizer_params, learning_rate_params, postprocessor, updater_params): self.data_provider = data_provider self.wm = world_model self.um",
"= postprocess_batch_depth(batch, state_desc) feed_dict = { self.wm.states : batch[state_desc], self.wm.action : batch['action'], self.wm.action_post",
"for k, v in um_res.iteritems()) wm_res_new.update(um_res_new) res['global_step'] = res.pop('um_global_step') res = self.postprocessor.postprocess(wm_res_new, batch)",
"self.um.uncertainty_loss, 'loss_per_example' : self.um.true_loss} self.dp = data_provider def run(self, sess): batch = self.dp.dequeue_batch()",
"res = sess.run(self.targets, feed_dict = feed_dict) res = self.postprocessor.postprocess(res, batch) return res class",
"= feed_dict) res = self.postprocessor.postprocess(res, batch) return res class SquareForceMagUpdater: def __init__(self, models,",
"optimizer_params, learning_rate_params, postprocessor, updater_params): self.dp = data_provider self.wm = models['world_model'] self.um = models['uncertainty_model']",
"in ['recent', 'depths1', 'objects1', 'images1']: res['batch'][desc] = val res['recent'] = batch['recent'] else: save_keys",
"[provider_batch[k]] for k in ['action', 'action_post', self.state_desc]: batch[k] = np.concatenate(batch[k], axis=0) feed_dict =",
"= get_learning_rate(self.global_step, ** learning_rate_params['uncertainty_model']) num_not_frozen = 0 self.targets = {} self.state_desc = updater_params.get('state_desc',",
"for desc, val in batch.iteritems(): if desc not in ['recent', 'depths1', 'objects1', 'images1']:",
"optimizer_params['uncertainty_model'], var_list = self.um.var_list) self.targets['um_opt'] = um_opt if num_not_frozen == 0: self.targets['global_step'] =",
"# 'action' : batch['action'][idx], 'action_post' : batch['action_post'][idx]} # map_draw_res.append(to_add) # res['map_draw'] = map_draw_res",
"msg in batch['recent']['msg']] self.start = end def close(self): self.hdf5.close() class LatentUncertaintyValidator: def __init__(self,",
"models, data_provider, optimizer_params, learning_rate_params, postprocessor, updater_params): self.dp = data_provider self.wm = models['world_model'] self.um",
"self.state_descriptor = state_descriptor def postprocess(self, training_results, batch): global_step = training_results['global_step'] res = {}",
"= updater_params['state_desc'] def update(self, sess, visualize = False): batch = self.data_provider.dequeue_batch() state_desc =",
"tf.placeholder(tf.float32, [None]) log_prob_tf = tf.nn.log_softmax(rl_model.logits) prob_tf = tf.nn.softmax(rl_model.logits) pi_loss = -tf.reduce_sum(tf.reduce_sum(log_prob_tf * self.ac,",
"''' import sys sys.path.append('tfutils') import tensorflow as tf from tfutils.base import get_optimizer, get_learning_rate",
"class UncertaintyPostprocessor: def __init__(self, big_save_keys = None, little_save_keys = None, big_save_len = None,",
"1 act_opt_params, act_opt = get_optimizer(act_lr, self.wm.act_loss, self.global_step, optimizer_params['world_model']['act_model'], var_list = self.wm.act_var_list + self.wm.encode_var_list)",
": batch['action'][:, -self.world_action_time : ] } world_model_res = sess.run(self.world_model_targets, feed_dict = wm_feed_dict) um_feed_dict",
"= big_save_keys self.little_save_keys = little_save_keys self.big_save_len = big_save_len self.big_save_freq = big_save_freq self.state_descriptor =",
"batch prepped = {} depths = replace_the_nones(obs[state_desc]) depths_past = np.array([depths[:-1]]) depths_fut = np.array([depths[:1]])",
"= np.float32)} print('save loc set up') self.start = 0 def update(self): batch =",
"self.r)) entropy = -tf.reduce_sum(prob_tf * log_prob_tf) self.rl_loss = pi_loss + 0.5 * vf_loss",
"= sess.run(self.targets, feed_dict = feed_dict) res['batch'] = {} for desc, val in batch.iteritems():",
"big_save_keys self.little_save_keys = little_save_keys self.big_save_len = big_save_len self.big_save_freq = big_save_freq self.state_descriptor = state_descriptor",
"get_optimizer(act_lr, self.wm.act_loss, self.global_step, optimizer_params['world_model']['act_model'], var_list = self.wm.act_var_list + self.wm.encode_var_list) um_opt_params, um_opt = get_optimizer(um_lr,",
"feed_dict = feed_dict) res = self.postprocessor.postprocess(res, batch) return res class LatentFreezeUpdater: def __init__(self,",
"= updater_params['map_draw_freq'] def update(self, sess, visualize = False): if self.um.just_random: print('Selecting action at",
"act_opt = get_optimizer(act_lr, self.wm.act_loss, self.global_step, optimizer_params['world_model']['act_model'], var_list = self.wm.act_var_list + self.wm.encode_var_list) um_opt_params, um_opt",
"global_increment = tf.assign_add(self.global_step, 1) um_increment = tf.assign_add(self.um.step, 1) self.targets.update({'global_increment' : global_increment, 'um_increment' :",
"DamianWMUncertaintyUpdater: def __init__(self, world_model, uncertainty_model, data_provider, optimizer_params, learning_rate_params, postprocessor): self.data_provider = data_provider self.world_model",
"= tf.placeholder(tf.float32, [None] + world_model.action_one_hot.get_shape().as_list()[1:]) self.adv = tf.placeholder(tf.float32, [None]) self.r = tf.placeholder(tf.float32, [None])",
"update(self, sess, visualize = False): batch = self.data_provider.dequeue_batch() state_desc = self.um.state_descriptor wm_feed_dict =",
"'depths1' : hdf5.require_dataset('depths1', shape = (N, height, width, 3), dtype = np.uint8), 'objects1'",
"dt), 'depths1' : hdf5.require_dataset('depths1', shape = (N, height, width, 3), dtype = np.uint8),",
"self.fut_lr_params, fut_lr = get_learning_rate(self.global_step, ** learning_rate_params['world_model']['fut_model']) self.um_lr_params, um_lr = get_learning_rate(self.global_step, ** learning_rate_params['uncertainty_model']) act_opt_params,",
"self.wm.states : batch['depths1'], self.wm.action : batch['action'], self.wm.action_post : batch['action_post'] } res = sess.run(self.targets,",
": self.um.estimated_world_loss } self.targets.update({'um_loss' : self.um.uncertainty_loss, 'um_lr' : um_lr, 'um_optimizer' : um_opt, 'global_step'",
"updater_params['map_draw_freq'] def update(self, sess, visualize = False): if self.um.just_random: print('Selecting action at random')",
"provider_recent in batch['recent']: looking_at_obj = [1 if msg is not None and msg['msg']['action_type']",
"self.world_model.s_f : next_depth, self.world_model.action : actions, self.world_model.action_id : action_ids, self.world_model.objects : objects }",
"# action_samples = self.action_sampler.sample_actions() # action, entropy, estimated_world_loss = self.um.act(sess, action_samples, obs_for_actor) #",
"{ self.wm.states : batch[state_desc], self.wm.action : batch['action'], self.wm.action_post : batch['action_post'] } res =",
"self.global_step, optimizer_params['uncertainty_model']) self.um_targets = {'loss' : self.um.uncertainty_loss, 'learning_rate' : um_learning_rate, 'optimizer' : um_opt,",
"feed_dict = { self.wm.action : batch['action'], self.wm.action_post : batch['action_post'], self.um.obj_there : batch['obj_there'] }",
"batch.next_state['action'][-1].dtype) if timepoint is None else timepoint for timepoint in batch.next_state['action']]]) # print('actions",
"action sampling is the 'batch.' self.action_sampler = action_sampler assert self.map_draw_mode == 'specified_indices' and",
"state_desc = self.state_desc feed_dict = { self.wm.states : batch[state_desc], self.wm.action : batch['action'], self.wm.action_post",
"var_list = self.wm.act_var_list + self.wm.encode_var_list) fut_opt_params, fut_opt = get_optimizer(fut_lr, self.wm.fut_loss, self.global_step, optimizer_params['world_model']['fut_model'], var_list",
"w colors cv2.imshow('tv', world_model_res['tv'][0] / 4.) cv2.imshow('processed0', world_model_res['given'][0, 0] / 4.) cv2.imshow('processed1', world_model_res['given'][0,",
"self.big_save_keys #est_losses = [other[1] for other in batch['other']] #action_sample = [other[2] for other",
": batch['action'][:, -1], self.um.true_loss : world_model_res['loss_per_example'] } um_res = sess.run(self.um_targets, feed_dict = um_feed_dict)",
"act_opt = get_optimizer(act_lr, self.wm.act_loss, self.global_step, optimizer_params['world_model']['act_model'], var_list = self.wm.act_var_list + self.wm.encode_var_list) self.targets['act_opt'] =",
"self.wm.save_to_gfs}) self.targets.update({k : v for k, v in self.um.readouts.items() if k not in",
"end] = [json.dumps(msg) for msg in batch['recent']['msg']] self.start = end def close(self): self.hdf5.close()",
"'specified_indices': map_draw_res = [] for idx in self.map_draw_example_indices: obs_for_actor = [batch[self.state_desc][idx][t] for t",
"um_opt, 'global_step' : self.global_step} self.postprocessor = postprocessor self.world_action_time = self.world_model.action.get_shape().as_list()[1] def start(self, sess):",
"print('big time') save_keys = self.big_save_keys est_losses = [other[1] for other in batch['recent']['other']] action_sample",
"= {} if (global_step) % self.big_save_freq < self.big_save_len: save_keys = self.big_save_keys #est_losses =",
"self.hdf5 = hdf5 = h5py.File(fn, mode = 'a') dt = h5py.special_dtype(vlen = str)",
"+= 1 act_opt_params, act_opt = get_optimizer(act_lr, self.wm.act_loss, self.global_step, optimizer_params['world_model']['act_model'], var_list = self.wm.act_var_list +",
"batch['action_post'] } res = sess.run(self.targets, feed_dict = feed_dict) res.pop('um_increment') res.pop('global_increment') global_step = res['global_step']",
"np.array([replace_the_nones(act_post)]) return obs_past, actions, actions_post, obs_fut # def postprocess_batch_depth(batch): # depths = np.array([[timepoint",
"freeze_um = updater_params['freeze_um'] self.postprocessor = postprocessor self.global_step = tf.get_variable('global_step', [], tf.int32, initializer =",
"depths = replace_the_nones(obs[state_desc]) depths_past = np.array([depths[:-1]]) depths_fut = np.array([depths[:1]]) objects = np.array([replace_the_nones(obs[state_desc])[:-1]]) actions",
"map_draw_res res = self.postprocessor.postprocess(res, batch) return res, global_step class ActionUncertaintyUpdater: def __init__(self, models,",
"self.um.uncertainty_loss, 'loss_per_example' : self.um.true_loss, 'estimated_world_loss' : self.um.estimated_world_loss} self.dp = data_provider def run(self, sess):",
"to do nothing self.map_draw_mode = 'specified_indices' #relies on there being just one obs",
"get_learning_rate(self.global_step, ** learning_rate_params['world_model']) self.wm_opt_params, wm_opt = get_optimizer(wm_learning_rate, self.world_model.loss, self.global_step, optimizer_params['world_model']) self.world_model_targets = {'given'",
"k, v in um_res.iteritems()) wm_res_new.update(um_res_new) res = wm_res_new res['global_step'] = res.pop('um_global_step') res =",
"data provider, set to do nothing self.map_draw_mode = 'specified_indices' #relies on there being",
"updater_params): self.data_provider = data_provider \\ if isinstance(data_provider, list) else [data_provider] self.wm = models['world_model']",
": self.um.estimated_world_loss, 'loss_per_example' : self.um.true_loss, 'act_loss_per_example' : self.wm.act_loss_per_example } self.dp = data_provider def",
"__init__(self, model, data_provider): self.dp = data_provider self.wm = model['world_model'] self.um = model['uncertainty_model'] self.targets",
"sess, visualize = False): batch = self.data_provider.dequeue_batch() depths, objects, actions, action_ids, next_depth =",
"= self.postprocessor.postprocess(res, batch) return res class UncertaintyUpdater: def __init__(self, world_model, uncertainty_model, data_provider, optimizer_params,",
"[] # if len(action_msg): # idx = int(action_msg[0]['id']) # action_ids_list.append(idx) # action_ids =",
"__init__(self, world_model, uncertainty_model, data_provider, optimizer_params, learning_rate_params, postprocessor, updater_params): self.data_provider = data_provider self.wm =",
"'objects1' : hdf5.require_dataset('objects1', shape = (N, height, width, 3), dtype = np.uint8), 'images1':",
"objects = np.array([replace_the_nones(obs[state_desc])[:-1]]) actions = np.array([replace_the_nones(act)]) action_ids_list = [] for i in range(2):",
"# action_msg = batch.next_state['msg'][i]['msg']['actions'] if batch.next_state['msg'][i] is not None else [] # if",
"np.mean(entropies) res['entropy'] = entropies looking_at_obj = [1 if msg is not None and",
"world_model_res.iteritems()) um_res_new = dict(('um_' + k, v) for k, v in um_res.iteritems()) wm_res_new.update(um_res_new)",
"postprocessor self.world_action_time = self.world_model.action.get_shape().as_list()[1] def start(self, sess): self.data_provider.start_runner(sess) sess.run(tf.global_variables_initializer()) def update(self, sess, visualize",
"-10000#just something that's not an id seen action_ids_list.append(idx) action_ids = np.array([action_ids_list]) return depths_past,",
"updater_params['freeze_um'] self.postprocessor = postprocessor self.global_step = tf.get_variable('global_step', [], tf.int32, initializer = tf.constant_initializer(0,dtype =",
"self.wm.act_var_list + self.wm.encode_var_list) fut_opt_params, fut_opt = get_optimizer(fut_lr, self.wm.fut_loss, self.fut_step, optimizer_params['world_model']['fut_model'], var_list = self.wm.fut_var_list)",
"self.little_save_keys.extend(['act_lr', 'um_lr']) def postprocess(self, training_results, batch): global_step = training_results['global_step'] res = {} if",
"= np.concatenate(batch[k], axis=0) state_desc = 'depths1' #depths, actions, actions_post, next_depth = postprocess_batch_depth(batch, state_desc)",
"np.array([replace_the_nones(act)]) action_ids_list = [] for i in range(2): action_msg = msg[i]['msg']['actions'] if msg[i]",
"self.um.var_list) self.targets['um_opt'] = um_opt self.targets['um_lr'] = um_lr self.targets['global_step'] = self.global_step global_increment = tf.assign_add(self.global_step,",
"dtype = my_list[-1].dtype) if elt is None else elt for elt in my_list]",
"uncertainty_model self.postprocessor = postprocessor self.global_step = tf.get_variable('global_step', [], tf.int32, initializer = tf.constant_initializer(0,dtype =",
"len(batch['recent']['msg']) end = self.start + bs for k in ['depths1', 'objects1', 'images1', 'action',",
"postprocess_batch_for_actionmap(batch) wm_feed_dict = { self.world_model.s_i : depths, self.world_model.s_f : next_depth, self.world_model.action : actions,",
"dict(('um_' + k, v) for k, v in um_res.iteritems()) wm_res_new.update(um_res_new) res['global_step'] = res.pop('um_global_step')",
"None): self.data_provider = data_provider \\ if isinstance(data_provider, list) else [data_provider] self.wm = models['world_model']",
"training step. ''' import sys sys.path.append('tfutils') import tensorflow as tf from tfutils.base import",
": self.wm.encoding_i, 'encoding_f' : self.wm.encoding_f, 'fut_pred' : self.wm.fut_pred, 'act_pred' : self.wm.act_pred, 'act_optimizer' :",
"um_lr, 'um_optimizer' : um_opt, 'global_step' : self.global_step, 'loss_per_example' : self.um.true_loss}) self.state_desc = updater_params['state_desc']",
"self.postprocessor = postprocessor def start(self, sess): self.data_provider.start_runner(sess) sess.run(tf.global_variables_initializer()) def update(self, sess, visualize =",
"{ self.um.s_i : depths, self.um.action_sample : actions[:, -1], self.um.true_loss : np.array([world_model_res['loss']]) } um_res",
".5 * tf.reduce_sum(tf.square(rl_model.vf - self.r)) entropy = -tf.reduce_sum(prob_tf * log_prob_tf) self.rl_loss = pi_loss",
"= pi_loss + 0.5 * vf_loss - entropy * 0.01 rl_opt_params, rl_opt =",
"= feed_dict) res.pop('um_increment') res.pop('global_increment') global_step = res['global_step'] #if self.map_draw_mode is not None and",
"in batch.iteritems(): if desc not in ['recent', 'depths1', 'objects1', 'images1']: res['batch'][desc] = val",
"LatentUncertaintyValidator: def __init__(self, models, data_provider): self.um = models['uncertainty_model'] self.wm = models['world_model'] self.targets =",
"self.wm.act_pred, 'act_loss' : self.wm.act_loss, 'estimated_world_loss' : self.um.estimated_world_loss, 'um_loss' : self.um.uncertainty_loss, 'loss_per_example' : self.um.true_loss}",
"**learning_rate_params['uncertainty_model']) um_opt_params, um_opt = get_optimizer(um_lr, self.um.uncertainty_loss, self.um_step, optimizer_params['uncertainty_model'], var_list = self.um.var_list) self.targets['um_opt'] =",
"= np.array([action_ids_list]) return depths_past, objects, actions, action_ids, depths_fut # def postprocess_batch_for_actionmap(batch): # prepped",
"= updater_params['freeze_um'] self.postprocessor = postprocessor self.global_step = tf.get_variable('global_step', [], tf.int32, initializer = tf.constant_initializer(0,dtype",
"** learning_rate_params['world_model']['act_model']) self.fut_lr_params, fut_lr = get_learning_rate(self.global_step, ** learning_rate_params['world_model']['fut_model']) self.um_lr_params, um_lr = get_learning_rate(self.global_step, **",
"= batch['recent'] else: save_keys = self.little_save_keys res.update(dict(pair for pair in training_results.iteritems() if pair[0]",
"print(self.big_save_len) if (global_step) % self.big_save_freq < self.big_save_len: print('big time') save_keys = self.big_save_keys est_losses",
") def replace_the_nones(my_list): ''' Assumes my_list[-1] is np array ''' return [np.zeros(my_list[-1].shape, dtype",
"learning_rate_params, postprocessor, updater_params): self.data_provider = data_provider self.wm = world_model self.um = uncertainty_model self.postprocessor",
": self.world_model.processed_input, 'loss' : self.world_model.loss, 'learning_rate' : wm_learning_rate, 'optimizer' : wm_opt, 'prediction' :",
"get_optimizer(um_learning_rate, self.um.uncertainty_loss, self.global_step, optimizer_params['uncertainty_model']) self.global_step = self.global_step / 2 self.um_targets = {'loss' :",
"= tf.int32)) self.um_step = tf.get_variable('ext_uncertainty_step', [], tf.int32, initializer = tf.constant_initializer(0,dtype = tf.int32)) self.targets",
"can put parallelization. Not finished! ''' def __init__(world_model, rl_model, data_provider, eta): self.data_provider =",
"self.wm.states : batch[state_desc], self.wm.action : batch['action'], self.wm.action_post : batch['action_post'] } self.targets['global_step'] = self.global_step",
"'global_step' : self.global_step} self.postprocessor = postprocessor def start(self, sess): self.data_provider.start_runner(sess) sess.run(tf.global_variables_initializer()) def update(self,",
"other in batch['recent']['other']] action_sample = [other[2] for other in batch['recent']['other']] res['batch'] = {'obs'",
"} world_model_res = sess.run(self.world_model_targets, feed_dict = wm_feed_dict) if visualize: cv2.imshow('pred', world_model_res['prediction'][0] / 4.)#TODO",
"self.um.estimated_world_loss } self.targets.update({'um_loss' : self.um.uncertainty_loss, 'um_lr' : um_lr, 'um_optimizer' : um_opt, 'global_step' :",
"self.data_provider.dequeue_batch() state_desc = self.um.state_descriptor wm_feed_dict = { self.world_model.states : batch[state_desc], self.world_model.action : batch['action'][:,",
"get_learning_rate import numpy as np import cv2 from curiosity.interaction import models import h5py",
": batch['action_post'] } res = sess.run(self.targets, feed_dict = feed_dict) res['batch'] = batch return",
"self.data_provider = data_provider self.wm = world_model self.um = uncertainty_model self.postprocessor = postprocessor self.global_step",
"updater_params['map_draw_example_indices'] #self.map_draw_timestep_indices = updater_params['map_draw_timestep_indices'] #self.map_draw_freq = updater_params['map_draw_freq'] def update(self, sess, visualize = False):",
"data_provider.data_lengths['obs'].keys()[0] self.insert_objthere = False if data_provider.num_objthere is None else True def run(self, sess):",
"= self.postprocessor.postprocess(res, batch) return res, glstep class LatentUncertaintyUpdater: def __init__(self, world_model, uncertainty_model, data_provider,",
"['recent', 'depths1', 'objects1', 'images1']: res['batch'][desc] = val res['recent'] = batch['recent'] else: save_keys =",
"msg['msg']['action_type']['OBJ_ACT'] else 0 for msg in batch['recent']['msg']] res['obj_freq'] = np.mean(looking_at_obj) return res class",
"self.um.estimated_world_loss, # '' # } #self.targets.update({'um_loss' : self.um.uncertainty_loss, 'um_lr' : um_lr, 'um_optimizer' :",
"= data_provider self.world_model = world_model self.rl_model = rl_model self.eta = eta self.global_step =",
"in batch['recent']: # entropies = [other[0] for other in batch['recent']['other']] # entropies =",
"= data_provider\\ if isinstance(data_provider, list) else [data_provider] self.wm = models['world_model'] self.um = models['uncertainty_model']",
"self.act_lr_params, act_lr = get_learning_rate(self.global_step, ** learning_rate_params['world_model']['act_model']) self.fut_lr_params, fut_lr = get_learning_rate(self.global_step, ** learning_rate_params['world_model']['fut_model']) self.um_lr_params,",
"next_depth = np.array([batch.next_state['depths1']]) # return depths, actions, next_depth def postprocess_batch_for_actionmap(batch, state_desc): obs, msg,",
"data_provider, optimizer_params, learning_rate_params, postprocessor, updater_params): self.data_provider = data_provider \\ if isinstance(data_provider, list) else",
"one forward pass each index because action sampling is the 'batch.' #self.action_sampler =",
"= postprocessor def start(self, sess): self.data_provider.start_runner(sess) sess.run(tf.global_variables_initializer()) def update(self, sess, visualize = False):",
"None else [] if len(action_msg): idx = int(action_msg[0]['id']) else: idx = -10000#just something",
"estimated_world_loss, # 'action_samples' : action_samples, 'depths1' : batch[self.state_desc][idx], # 'action' : batch['action'][idx], 'action_post'",
"0 for msg in provider_recent['msg']] mean_per_provider.append(np.mean(looking_at_obj)) res['obj_freq'] = np.mean(mean_per_provider) res['obj_freq_per_provider_noprint'] = mean_per_provider return",
"self.global_step, optimizer_params['uncertainty_model']) self.targets = {'um_loss' : self.um.uncertainty_loss, 'um_optimizer' : um_opt, 'global_step' : self.global_step,",
"self.targets['um_increment'] = um_increment self.obj_there_supervision = updater_params.get('include_obj_there', False) #self.map_draw_mode = None #Map drawing. Meant",
"actions_post, obs_fut # def postprocess_batch_depth(batch): # depths = np.array([[timepoint if timepoint is not",
"self.wm.action : batch['action'], self.wm.obj_there : batch['obj_there'] } res = sess.run(self.targets, feed_dict = feed_dict)",
"res = self.postprocessor.postprocess(res, batch) return res class DebuggingForceMagUpdater: def __init__(self, models, data_provider, optimizer_params,",
"optimizer_params, learning_rate_params, postprocessor, updater_params): self.data_provider = data_provider\\ if isinstance(data_provider, list) else [data_provider] self.wm",
"def replace_the_nones(my_list): ''' Assumes my_list[-1] is np array ''' return [np.zeros(my_list[-1].shape, dtype =",
"action_sample} res['msg'] = batch['recent']['msg'] else: print('little time') save_keys = self.little_save_keys res.update(dict((k, v) for",
": self.um.uncertainty_loss, 'loss_per_example' : self.um.true_loss, 'estimated_world_loss' : self.um.estimated_world_loss} self.dp = data_provider def run(self,",
"range(2): # action_msg = batch.next_state['msg'][i]['msg']['actions'] if batch.next_state['msg'][i] is not None else [] #",
"= tf.int32)) self.act_lr_params, act_lr = get_learning_rate(self.global_step, ** learning_rate_params['world_model']['act_model']) self.fut_lr_params, fut_lr = get_learning_rate(self.global_step, **",
"/ 4.) cv2.imshow('processed1', world_model_res['given'][0, 1] / 4.) cv2.waitKey(1) print('wm loss: ' + str(world_model_res['loss']))",
"self.um.readouts.items() if k not in self.um.save_to_gfs}) #this should be changed for an online",
"v) for k, v in um_res.iteritems()) wm_res_new.update(um_res_new) res['global_step'] = res.pop('um_global_step') res = self.postprocessor.postprocess(wm_res_new,",
"{ self.wm.action : batch['action'], self.wm.action_post : batch['action_post'], self.um.obj_there : batch['obj_there'] } res =",
"= self.postprocessor.postprocess(res, batch) return res class DebuggingForceMagUpdater: def __init__(self, models, data_provider, optimizer_params, learning_rate_params,",
"= False): batch = self.data_provider.dequeue_batch() depths, objects, actions, action_ids, next_depth = postprocess_batch_for_actionmap(batch) wm_feed_dict",
"{} for desc, val in batch.iteritems(): if desc not in ['recent', 'depths1', 'objects1',",
"'action', 'action_post']: tosave = batch['recent'][k] if k in ['action', 'action_post']: tosave = tosave.astype(np.float32)",
"batch return res class ActionUncertaintyValidatorWithReadouts: def __init__(self, model, data_provider): self.dp = data_provider self.wm",
"self.dp = data_provider self.wm = model['world_model'] self.um = model['uncertainty_model'] self.targets = {} self.targets.update({k",
"get_optimizer(fut_lr, self.wm.fut_loss, self.fut_step, optimizer_params['world_model']['fut_model'], var_list = self.wm.fut_var_list) self.targets['act_opt'] = act_opt self.targets['fut_opt'] = fut_opt",
"def __init__(self, models, data_provider, optimizer_params, learning_rate_params, postprocessor, updater_params): self.data_provider = data_provider \\ if",
"res, global_step class FreezeUpdater: def __init__(self, models, data_provider, optimizer_params, learning_rate_params, postprocessor, updater_params): self.data_provider",
"depths_fut # def postprocess_batch_for_actionmap(batch): # prepped = {} # for desc in ['depths1',",
"desc, val in batch.iteritems(): if desc not in ['recent', 'depths1', 'objects1', 'images1']: res['batch'][desc]",
"= { self.wm.states : batch[state_desc], self.wm.action : batch['action'], self.wm.action_post : batch['action_post'] } res",
"save_keys)) #res['msg'] = batch['msg'][-1] entropies = [other[0] for other in batch['recent']['other']] entropies =",
"um_lr}) assert set(self.wm.readouts.keys()) != set(self.um.readouts.keys()) self.targets.update(self.wm.readouts) self.targets.update(self.um.readouts) um_increment = tf.assign_add(self.um.step, 1) assert 'um_increment'",
"data_provider.num_objthere is None else True def run(self, sess): batch = self.dp.dequeue_batch() feed_dict =",
"# next_depths = np.array([batch.next_state['depths1']]) # return prepped['depths1'], prepped['objects1'], actions, action_ids, next_depths class ExperienceReplayPostprocessor:",
"self.um.true_loss}) self.state_desc = updater_params['state_desc'] #checking that we don't have repeat names def start(self,",
": batch['action_post'], self.um.obj_there : batch['obj_there'] } res = sess.run(self.targets, feed_dict = feed_dict) res",
"tf.int32, initializer = tf.constant_initializer(0,dtype = tf.int32)) self.um_lr_params, um_lr = get_learning_rate(self.global_step, ** learning_rate_params['uncertainty_model']) um_opt_params,",
"tf.constant_initializer(0,dtype = tf.int32)) self.fut_step = tf.get_variable('fut_step', [], tf.int32, initializer = tf.constant_initializer(0,dtype = tf.int32))",
"self.global_step} self.postprocessor = postprocessor self.world_action_time = self.world_model.action.get_shape().as_list()[1] def start(self, sess): self.data_provider.start_runner(sess) sess.run(tf.global_variables_initializer()) def",
"# actions = np.array([[np.zeros(batch.next_state['action'][-1].shape, batch.next_state['action'][-1].dtype) if timepoint is None else timepoint for timepoint",
"batch['recent']: looking_at_obj = [1 if msg is not None and msg['msg']['action_type'] == 'OBJ_ACT'",
"res['batch'] = {'obs' : batch['depths1'], 'act' : batch['action'], 'act_post' : batch['action_post'], 'est_loss' :",
"initializer = tf.constant_initializer(0,dtype = tf.int32)) self.um_lr_params, um_lr = get_learning_rate(self.global_step, ** learning_rate_params['uncertainty_model']) um_opt_params, um_opt",
"return res, global_step class JustUncertaintyUpdater: def __init__(self, models, data_provider, optimizer_params, learning_rate_params, postprocessor, updater_params,",
"class ExperienceReplayPostprocessor: def __init__(self, big_save_keys = None, little_save_keys = None, big_save_len = None,",
"= {} for i, dp in enumerate(self.data_provider): provider_batch = dp.dequeue_batch() for k in",
"self.wm.act_loss_per_example } self.dp = data_provider def run(self, sess): batch = self.dp.dequeue_batch() feed_dict =",
"self.data_provider.dequeue_batch() depths, objects, actions, action_ids, next_depth = postprocess_batch_for_actionmap(batch) wm_feed_dict = { self.world_model.s_i :",
"= {'loss' : self.um.uncertainty_loss, 'learning_rate' : um_learning_rate, 'optimizer' : um_opt, 'global_step' : self.global_step}",
"self.um.uncertainty_loss, 'um_lr' : um_lr, 'um_optimizer' : um_opt, 'global_step' : self.global_step, 'loss_per_example' : self.um.true_loss,",
"= fut_lr if not freeze_um: um_lr_params, um_lr = get_learning_rate(self.um_step, **learning_rate_params['uncertainty_model']) um_opt_params, um_opt =",
"np.array([world_model_res['loss']]) } um_res = sess.run(self.um_targets, feed_dict = um_feed_dict) wm_res_new = dict(('wm_' + k,",
"= np.array([depths[:-1]]) obs_fut = np.array([depths[1:]]) actions = np.array([replace_the_nones(act)]) actions_post = np.array([replace_the_nones(act_post)]) return obs_past,",
"self.state_desc feed_dict = { self.wm.states : batch[state_desc], self.wm.action : batch['action'], self.wm.action_post : batch['action_post']",
": self.um.var_list} def update(self, sess): batch = self.dp.dequeue_batch() feed_dict = { self.wm.action :",
"'action' : batch['action'][idx], 'action_post' : batch['action_post'][idx]} # map_draw_res.append(to_add) # res['map_draw'] = map_draw_res res",
"[1 if msg is not None and msg['msg']['action_type']['OBJ_ACT'] else 0 for msg in",
"act_dim = updater_params['act_dim'] print('setting up save loc') self.hdf5 = hdf5 = h5py.File(fn, mode",
"= tf.get_variable('global_step', [], tf.int32, initializer = tf.constant_initializer(0,dtype = tf.int32)) self.wm_lr_params, wm_learning_rate = get_learning_rate(self.global_step,",
": batch[self.state_desc], self.wm.action : batch['action'], self.wm.action_post : batch['action_post'] } self.targets['global_step'] = self.global_step res",
"res = self.postprocessor.postprocess(res, batch) return res, global_step class JustUncertaintyUpdater: def __init__(self, models, data_provider,",
": action_ids, self.world_model.objects : objects } world_model_res = sess.run(self.world_model_targets, feed_dict = wm_feed_dict) if",
"= feed_dict) res['batch'] = {} for desc, val in batch.iteritems(): print(desc) if desc",
"wm = models['world_model'] self.targets = {'act_pred' : self.wm.act_pred, 'act_loss' : self.wm.act_loss, 'estimated_world_loss' :",
"self.state_desc]: batch[k] = np.concatenate(batch[k], axis=0) feed_dict = { self.wm.states : batch[self.state_desc], self.wm.action :",
"in batch.next_state['action']]]) # print('actions shape') # print(actions.shape) # print(len(batch.next_state['action'])) # action_ids_list = []",
"data_provider fn = updater_params['hdf5_filename'] N = updater_params['N_save'] height, width = updater_params['image_shape'] act_dim =",
"batch.next_state['msg'][i]['msg']['actions'] if batch.next_state['msg'][i] is not None else [] # if len(action_msg): # idx",
"h5py import json class RawDepthDiscreteActionUpdater: ''' Provides the training step. This is probably",
"not None and msg['msg']['action_type'] == 'OBJ_ACT' else 0 for msg in provider_recent['msg']] mean_per_provider.append(np.mean(looking_at_obj))",
"FreezeUpdater: def __init__(self, models, data_provider, optimizer_params, learning_rate_params, postprocessor, updater_params): self.data_provider = data_provider \\",
"actions_post, next_depth = postprocess_batch_depth(batch, state_desc) feed_dict = { self.wm.states : batch[state_desc], self.wm.action :",
"= batch['obj_there'] res = sess.run(self.targets, feed_dict = feed_dict) res = self.postprocessor.postprocess(res, batch) return",
"postprocessor, updater_params): self.data_provider = data_provider \\ if isinstance(data_provider, list) else [data_provider] self.wm =",
"self.global_step, 'loss_per_example' : self.um.true_loss, 'estimated_world_loss' : self.um.estimated_world_loss } self.state_desc = updater_params['state_desc'] def update(self,",
"**learning_rate_params['world_model']['act_model']) fut_lr_params, fut_lr = get_learning_rate(self.fut_step, **learning_rate_params['world_model']['fut_model']) act_opt_params, act_opt = get_optimizer(act_lr, self.wm.act_loss, self.act_step, optimizer_params['world_model']['act_model'],",
"self.wm.act_loss, self.act_step, optimizer_params['world_model']['act_model'], var_list = self.wm.act_var_list + self.wm.encode_var_list) fut_opt_params, fut_opt = get_optimizer(fut_lr, self.wm.fut_loss,",
"return res, glstep class LatentUncertaintyUpdater: def __init__(self, world_model, uncertainty_model, data_provider, optimizer_params, learning_rate_params, postprocessor,",
"batch[state_desc], self.wm.action : batch['action'], self.wm.action_post : batch['action_post'] } res = sess.run(self.targets, feed_dict =",
": batch['action'], 'act_post' : batch['action_post'], 'est_loss' : est_losses, 'action_sample' : action_sample} res['msg'] =",
": batch[self.state_desc][idx], # 'action' : batch['action'][idx], 'action_post' : batch['action_post'][idx]} # map_draw_res.append(to_add) # res['map_draw']",
"} self.targets['global_step'] = self.global_step res = sess.run(self.targets, feed_dict = feed_dict) global_step = res['global_step']",
"__init__(self, world_model, uncertainty_model, data_provider, optimizer_params, learning_rate_params, postprocessor, updater_params = None): self.data_provider = data_provider",
"get_learning_rate(self.global_step, ** learning_rate_params['world_model']['act_model']) self.fut_lr_params, fut_lr = get_learning_rate(self.global_step, ** learning_rate_params['world_model']['fut_model']) self.um_lr_params, um_lr = get_learning_rate(self.global_step,",
"little_save_keys = None, big_save_len = None, big_save_freq = None, state_descriptor = None): self.big_save_keys",
"return res class DataWriteUpdater: def __init__(self, data_provider, updater_params): self.data_provider = data_provider fn =",
"{'um_loss' : self.um.uncertainty_loss, 'loss_per_example' : self.um.true_loss, 'estimated_world_loss' : self.um.estimated_world_loss} self.dp = data_provider def",
"__init__(self, models, data_provider, optimizer_params, learning_rate_params, postprocessor, updater_params): self.data_provider = data_provider \\ if isinstance(data_provider,",
"def __init__(self, world_model, uncertainty_model, data_provider, optimizer_params, learning_rate_params, postprocessor, updater_params = None): self.data_provider =",
"} if self.um.insert_obj_there: print('adding obj_there to feed dict') feed_dict[self.um.obj_there] = batch['obj_there'] res =",
"= [other[2] for other in batch['recent']['other']] res['batch'] = {'obs' : batch['depths1'], 'act' :",
"= get_learning_rate(self.global_step, ** learning_rate_params['uncertainty_model']) um_opt_params, um_opt = get_optimizer(um_lr, self.um.uncertainty_loss, self.global_step, optimizer_params['uncertainty_model'], var_list =",
"fut_lr = get_learning_rate(self.global_step, ** learning_rate_params['world_model']['fut_model']) self.um_lr_params, um_lr = get_learning_rate(self.global_step, ** learning_rate_params['uncertainty_model']) act_opt_params, act_opt",
"tf.constant_initializer(0,dtype = tf.int32)) self.action = tf.placeholder = tf.placeholder(tf.float32, [None] + world_model.action_one_hot.get_shape().as_list()[1:]) self.adv =",
"# return depths, actions, next_depth def postprocess_batch_for_actionmap(batch, state_desc): obs, msg, act = batch",
"'loss_per_example' : self.um.true_loss}) self.map_draw_mode = None #Map drawing. Meant to have options, but",
"self.um.exactly_whats_needed: self.targets['oh_my_god'] = self.um.oh_my_god self.state_desc = updater_params['state_desc'] def update(self, sess, visualize = False):",
"self.big_save_len = big_save_len self.big_save_freq = big_save_freq self.state_descriptor = state_descriptor self.big_save_keys.append('map_draw') self.little_save_keys.append('map_draw') self.big_save_keys.extend(['act_lr', 'um_lr'])",
"def __init__(self, models, data_provider, optimizer_params, learning_rate_params, postprocessor, updater_params): self.dp = data_provider self.wm =",
"import h5py import json class RawDepthDiscreteActionUpdater: ''' Provides the training step. This is",
"# for i in range(2): # action_msg = batch.next_state['msg'][i]['msg']['actions'] if batch.next_state['msg'][i] is not",
"self.um_step, optimizer_params['uncertainty_model'], var_list = self.um.var_list) self.targets['um_opt'] = um_opt self.targets['um_lr'] = um_lr self.targets['global_step'] =",
": batch['action_post'][idx]} map_draw_res.append(to_add) res['map_draw'] = map_draw_res res = self.postprocessor.postprocess(res, batch) return res, global_step",
"t in self.map_draw_timestep_indices] # action_samples = self.action_sampler.sample_actions() # action, entropy, estimated_world_loss = self.um.act(sess,",
"def postprocess_batch_for_actionmap(batch): # prepped = {} # for desc in ['depths1', 'objects1']: #",
"False) #self.map_draw_mode = None #Map drawing. Meant to have options, but for now",
"batch) return res class DamianWMUncertaintyUpdater: def __init__(self, world_model, uncertainty_model, data_provider, optimizer_params, learning_rate_params, postprocessor):",
"ActionUncertaintyValidator: def __init__(self, models, data_provider): self.um = um = models['uncertainty_model'] self.wm = wm",
"# map_draw_res.append(to_add) # res['map_draw'] = map_draw_res res = self.postprocessor.postprocess(res, batch) return res, global_step",
"0.5 * vf_loss - entropy * 0.01 rl_opt_params, rl_opt = get_optimizer(learning_rate, self.rl_loss, )",
"postprocessor, updater_params = None): self.data_provider = data_provider self.wm = world_model self.um = uncertainty_model",
"len(batch['recent'][0]) > 0: mean_per_provider = [] for provider_recent in batch['recent']: looking_at_obj = [1",
"res class DebuggingForceMagUpdater: def __init__(self, models, data_provider, optimizer_params, learning_rate_params, postprocessor, updater_params): self.dp =",
"batch['other']] res['batch'] = {} for desc, val in batch.iteritems(): if desc not in",
"but for now just assuming one sort of specification #self.state_desc = updater_params.get('state_desc', 'depths1')",
"{ self.wm.states : batch[self.state_desc], self.wm.action : batch['action'], self.wm.action_post : batch['action_post'] } self.targets['global_step'] =",
"um_opt_params, um_opt = get_optimizer(um_lr, self.um.uncertainty_loss, self.global_step, optimizer_params['uncertainty_model'], var_list = self.um.var_list) self.targets = {'um_loss'",
"elt is None else elt for elt in my_list] def postprocess_batch_depth(batch, state_desc): obs,",
"'um_loss' : self.um.uncertainty_loss, 'estimated_world_loss' : self.um.estimated_world_loss, 'loss_per_example' : self.um.true_loss, 'act_loss_per_example' : self.wm.act_loss_per_example }",
"str(world_model_res['loss'])) um_feed_dict = { self.um.s_i : depths, self.um.action_sample : actions[:, -1], self.um.true_loss :",
"-1], self.um.true_loss : np.array([world_model_res['loss']]) } um_res = sess.run(self.um_targets, feed_dict = um_feed_dict) wm_res_new =",
"return depths, actions, next_depth def postprocess_batch_for_actionmap(batch, state_desc): obs, msg, act = batch prepped",
"print('postprocessor deets') print(global_step) print(self.big_save_freq) print(self.big_save_len) if (global_step) % self.big_save_freq < self.big_save_len: print('big time')",
"**learning_rate_params['uncertainty_model']) self.wm_lr_params, um_opt = get_optimizer(um_learning_rate, self.um.uncertainty_loss, self.global_step, optimizer_params['uncertainty_model']) self.um_targets = {'loss' : self.um.uncertainty_loss,",
"[provider_batch[k]] for k in ['action', 'action_post', 'depths1']: batch[k] = np.concatenate(batch[k], axis=0) feed_dict =",
"v for k, v in self.wm.readouts.items() if k not in self.wm.save_to_gfs}) self.targets.update({k :",
"batch[self.state_desc], self.wm.action : batch['action'], self.wm.action_post : batch['action_post'] } res = sess.run(self.targets, feed_dict =",
": self.global_step} self.postprocessor = postprocessor def start(self, sess): self.data_provider.start_runner(sess) sess.run(tf.global_variables_initializer()) def update(self, sess,",
"msg is not None and msg['msg']['action_type']['OBJ_ACT'] else 0 for msg in batch['recent']['msg']] res['obj_freq']",
"= batch.next_state['msg'][i]['msg']['actions'] if batch.next_state['msg'][i] is not None else [] # if len(action_msg): #",
"3), dtype = np.uint8), 'images1': hdf5.require_dataset('images1', shape = (N, height, width, 3), dtype",
"= False): batch = self.data_provider.dequeue_batch() state_desc = self.state_desc feed_dict = { self.wm.states :",
"k in ['action', 'action_post', self.state_desc]: batch[k] = np.concatenate(batch[k], axis=0) feed_dict = { self.wm.states",
"get_optimizer(um_lr, self.um.uncertainty_loss, self.global_step, optimizer_params['uncertainty_model']) self.targets = {'um_loss' : self.um.uncertainty_loss, 'um_optimizer' : um_opt, 'global_step'",
"= models['uncertainty_model'] freeze_wm = updater_params['freeze_wm'] freeze_um = updater_params['freeze_um'] self.postprocessor = postprocessor self.global_step =",
"if self.um.insert_obj_there: print('adding obj_there to feed dict') feed_dict[self.um.obj_there] = batch['obj_there'] res = sess.run(self.targets,",
"self.wm.states : batch[self.state_desc], self.wm.action : batch['action'], self.wm.action_post : batch['action_post'] } res = sess.run(self.targets,",
"'action' : batch['action'][idx], 'action_post' : batch['action_post'][idx]} map_draw_res.append(to_add) res['map_draw'] = map_draw_res res = self.postprocessor.postprocess(res,",
"= dict(('wm_' + k, v) for k, v in world_model_res.iteritems()) um_res_new = dict(('um_'",
"= get_optimizer(wm_learning_rate, self.world_model.loss, self.global_step, optimizer_params['world_model']) self.world_model_targets = {'given' : self.world_model.processed_input, 'loss' : self.world_model.loss,",
"self.big_save_len: print('big time') save_keys = self.big_save_keys est_losses = [other[1] for other in batch['recent']['other']]",
"self.wm.act_loss, 'um_loss' : self.um.uncertainty_loss, 'estimated_world_loss' : self.um.estimated_world_loss, 'loss_per_example' : self.um.true_loss, 'act_loss_per_example' : self.wm.act_loss_per_example",
"!= 'recent': res['batch'][desc] = val[:, -1] res['recent'] = batch['recent'] class ObjectThereValidater: def __init__(self,",
"visualize = False): batch = self.data_provider.dequeue_batch() state_desc = self.state_desc #depths, actions, actions_post, next_depth",
"not in self.targets self.targets['um_increment'] = um_increment self.obj_there_supervision = updater_params.get('include_obj_there', False) #self.map_draw_mode = None",
"= updater_params.get('state_desc', 'depths1') self.map_draw_mode = updater_params['map_draw_mode'] #this specification specifices batch example indices for",
"in batch['recent']['other']] action_sample = [other[2] for other in batch['recent']['other']] res['batch'] = {'obs' :",
"act_opt, 'fut_optimizer' : fut_opt, 'act_lr' : act_lr, 'fut_lr' : fut_lr, 'fut_loss' : self.wm.fut_loss,",
"+ str(world_model_res['loss'])) um_feed_dict = { self.um.s_i : depths, self.um.action_sample : actions[:, -1], self.um.true_loss",
": um_opt, 'global_step' : self.global_step, 'loss_per_example' : self.um.true_loss, 'estimated_world_loss' : self.um.estimated_world_loss } self.state_desc",
"in ['depths1', 'objects1', 'images1', 'action', 'action_post']: tosave = batch['recent'][k] if k in ['action',",
"finished! ''' def __init__(world_model, rl_model, data_provider, eta): self.data_provider = data_provider self.world_model = world_model",
"world_model, uncertainty_model, data_provider, optimizer_params, learning_rate_params, postprocessor): self.data_provider = data_provider self.world_model = world_model self.um",
"= self.little_save_keys res.update(dict((k, v) for (k, v) in training_results.iteritems() if k in save_keys))",
"tf.assign_add(self.global_step, 1) else: self.global_step = self.global_step / num_not_frozen self.targets['global_step'] = self.global_step self.targets.update({'act_lr' :",
"model['uncertainty_model'] self.targets = {} self.targets.update({k : v for k, v in self.wm.readouts.items() if",
"0 def update(self): batch = self.data_provider.dequeue_batch() bs = len(batch['recent']['msg']) end = self.start +",
"'act_loss' : self.wm.act_loss, 'um_loss' : self.um.uncertainty_loss, 'estimated_world_loss' : self.um.estimated_world_loss, 'loss_per_example' : self.um.true_loss, 'act_loss_per_example'",
"batch['depths1'], self.wm.action : batch['action'], self.wm.obj_there : batch['obj_there'] } return sess.run(self.targets, feed_dict = feed_dict)",
"self.wm.action : batch['action'], self.wm.obj_there : batch['obj_there'] } return sess.run(self.targets, feed_dict = feed_dict) class",
"tf.int32)) self.um_lr_params, um_lr = get_learning_rate(self.global_step, ** learning_rate_params['uncertainty_model']) um_opt_params, um_opt = get_optimizer(um_lr, self.um.uncertainty_loss, self.global_step,",
"hdf5.require_dataset('images1', shape = (N, height, width, 3), dtype = np.uint8), 'action' : hdf5.require_dataset('action',",
"= {'global_step' : self.global_step, 'um_optimizer' : um_opt} assert set(self.wm.readouts.keys()) != set(self.um.readouts.keys()) self.targets.update(self.wm.readouts) self.targets.update(self.um.readouts)",
"self.global_step} self.postprocessor = postprocessor def start(self, sess): self.data_provider.start_runner(sess) sess.run(tf.global_variables_initializer()) def update(self, sess, visualize",
"res['entropy'] = entropies looking_at_obj = [1 if msg is not None and msg['msg']['action_type']['OBJ_ACT']",
"um_lr_params, um_lr = get_learning_rate(self.global_step, **learning_rate_params['uncertainty_model']) um_opt_params, um_opt = get_optimizer(um_lr, self.um.uncertainty_loss, self.global_step, optimizer_params['uncertainty_model']) self.targets",
"have options, but for now just assuming one sort of specification #self.state_desc =",
"updater_params['map_draw_example_indices'] self.map_draw_timestep_indices = updater_params['map_draw_timestep_indices'] self.map_draw_freq = updater_params['map_draw_freq'] def update(self, sess, visualize = False):",
"up') self.start = 0 def update(self): batch = self.data_provider.dequeue_batch() bs = len(batch['recent']['msg']) end",
"= np.array([depths[:-1]]) depths_fut = np.array([depths[:1]]) objects = np.array([replace_the_nones(obs[state_desc])[:-1]]) actions = np.array([replace_the_nones(act)]) action_ids_list =",
"res['global_step'] res = self.postprocessor.postprocess(res, batch) return res, glstep class LatentUncertaintyUpdater: def __init__(self, world_model,",
"= False): batch = {} for i, dp in enumerate(self.data_provider): provider_batch = dp.dequeue_batch()",
"# map_draw_res = [] # for idx in self.map_draw_example_indices: # obs_for_actor = [batch[self.state_desc][idx][t]",
"in self.targets self.targets['um_increment'] = um_increment self.obj_there_supervision = updater_params.get('include_obj_there', False) #self.map_draw_mode = None #Map",
": world_model_res['loss_per_example'] } um_res = sess.run(self.um_targets, feed_dict = um_feed_dict) wm_res_new = dict(('wm_' +",
"self.global_step, 'loss_per_example' : self.um.true_loss}) self.map_draw_mode = None #Map drawing. Meant to have options,",
"feed_dict = feed_dict) #TODO case it for online res['recent'] = {} #if self.map_draw_mode",
"self.map_draw_mode == 'specified_indices': # map_draw_res = [] # for idx in self.map_draw_example_indices: #",
"Meant to have options, but for now just assuming one sort of specification",
"#this specification specifices batch example indices for which we do a forward pass.",
"['action', 'action_post']: tosave = tosave.astype(np.float32) self.handles[k][self.start : end] = batch['recent'][k] self.handles['msg'][self.start : end]",
"return res class DebuggingForceMagUpdater: def __init__(self, models, data_provider, optimizer_params, learning_rate_params, postprocessor, updater_params): self.dp",
"-self.world_action_time : ] } world_model_res = sess.run(self.world_model_targets, feed_dict = wm_feed_dict) um_feed_dict = {",
"self.world_model.objects : objects } world_model_res = sess.run(self.world_model_targets, feed_dict = wm_feed_dict) if visualize: cv2.imshow('pred',",
"v in self.wm.readouts.items() if k not in self.wm.save_to_gfs}) self.targets.update({k : v for k,",
"# obs_for_actor = [batch[self.state_desc][idx][t] for t in self.map_draw_timestep_indices] # action_samples = self.action_sampler.sample_actions() #",
"msg['msg']['action_type'] == 'OBJ_ACT' else 0 for msg in batch['recent']['msg']] res['obj_freq'] = np.mean(looking_at_obj) elif",
"self.wm.states : batch[self.state_desc], self.wm.action : batch['action'], self.wm.action_post : batch ['action_post'] } if self.insert_objthere:",
"self.dp.dequeue_batch() feed_dict = { self.wm.states : batch['depths1'], self.wm.action : batch['action'], self.wm.obj_there : batch['obj_there']",
"get_optimizer(act_lr, self.wm.act_loss, self.global_step, optimizer_params['world_model']['act_model'], var_list = self.wm.act_var_list + self.wm.encode_var_list) self.targets['act_opt'] = act_opt if",
"= feed_dict) res.pop('um_increment') global_step = res['global_step'] #if self.map_draw_mode is not None and global_step",
"and global_step % self.map_draw_freq == 0: if self.map_draw_mode == 'specified_indices': map_draw_res = []",
"type(batch['recent']) == list and len(batch['recent'][0]) > 0: mean_per_provider = [] for provider_recent in",
"'action_sample' : action_sample} res['msg'] = batch['recent']['msg'] else: print('little time') save_keys = self.little_save_keys res.update(dict((k,",
"for i in range(2): action_msg = msg[i]['msg']['actions'] if msg[i] is not None else",
"self.um.estimated_world_loss} self.dp = data_provider def run(self, sess): batch = self.dp.dequeue_batch() feed_dict = {",
": v for k, v in self.wm.readouts.items() if k not in self.wm.save_to_gfs}) self.targets.update({k",
"set(self.um.readouts.keys()) def update(self, sess, visualize = False): if self.um.just_random: print('Selecting action at random')",
"self.targets.update(self.wm.readouts) self.targets.update(self.um.readouts) assert set(self.wm.readouts.keys()) != set(self.um.readouts.keys()) def update(self, sess, visualize = False): if",
"sess.run(self.targets, feed_dict = feed_dict) res['batch'] = {} for desc, val in batch.iteritems(): print(desc)",
"feed_dict = feed_dict) res['batch'] = batch return res class ActionUncertaintyValidatorWithReadouts: def __init__(self, model,",
"act_lr, 'um_lr' : um_lr}) assert set(self.wm.readouts.keys()) != set(self.um.readouts.keys()) self.targets.update(self.wm.readouts) self.targets.update(self.um.readouts) um_increment = tf.assign_add(self.um.step,",
"depths = np.array([[timepoint if timepoint is not None else np.zeros(obs['depths1'][-1].shape, dtype = obs['depths1'][-1].dtype)",
": batch['depths1'], self.wm.action : batch['action'], self.wm.obj_there : batch['obj_there'] } return sess.run(self.targets, feed_dict =",
"'um_optimizer' : um_opt, 'global_step' : self.global_step, 'loss_per_example' : self.um.true_loss, 'estimated_world_loss' : self.um.estimated_world_loss }",
"= get_learning_rate(self.global_step, **learning_rate_params['uncertainty_model']) self.um_lr_params, um_opt = get_optimizer(um_learning_rate, self.um.uncertainty_loss, self.global_step, optimizer_params['uncertainty_model']) self.global_step = self.global_step",
"self.big_save_freq = big_save_freq self.state_descriptor = state_descriptor def postprocess(self, training_results, batch): global_step = training_results['global_step']",
"dtype = obs[desc][-1].dtype) for timepoint in obs[desc]] for obs in batch.states]) # actions",
"action_samples, obs_for_actor) # to_add = {'example_id' : idx, 'action_sample' : action, 'estimated_world_loss' :",
"__init__(self, models, data_provider, optimizer_params, learning_rate_params, postprocessor, updater_params): self.dp = data_provider self.wm = models['world_model']",
"self.um = uncertainty_model self.postprocessor = postprocessor self.global_step = tf.get_variable('global_step', [], tf.int32, initializer =",
"var_list = self.wm.act_var_list + self.wm.encode_var_list) um_opt_params, um_opt = get_optimizer(um_lr, self.um.uncertainty_loss, self.global_step, optimizer_params['uncertainty_model'], var_list",
"= tf.constant_initializer(0,dtype = tf.int32)) self.fut_step = tf.get_variable('fut_step', [], tf.int32, initializer = tf.constant_initializer(0,dtype =",
"set to do nothing self.map_draw_mode = 'specified_indices' #relies on there being just one",
"def update(self, sess): batch = self.dp.dequeue_batch() feed_dict = { self.wm.action : batch['action'], self.wm.action_post",
": self.wm.fut_pred, 'act_pred' : self.wm.act_pred, 'act_optimizer' : act_opt, 'fut_optimizer' : fut_opt, 'act_lr' :",
"def __init__(self, world_model, uncertainty_model, data_provider, optimizer_params, learning_rate_params, postprocessor): self.data_provider = data_provider self.world_model =",
"self.wm.action_post : batch['action_post'] } if self.um.insert_obj_there: print('adding obj_there to feed dict') feed_dict[self.um.obj_there] =",
"tf.get_variable('global_step', [], tf.int32, initializer = tf.constant_initializer(0,dtype = tf.int32)) self.um_lr_params, um_lr = get_learning_rate(self.global_step, **",
"self.world_model.s_i : depths, self.world_model.s_f : next_depth, self.world_model.action : actions, self.world_model.action_id : action_ids, self.world_model.objects",
": batch['action'], self.wm.obj_there : batch['obj_there'] } res = sess.run(self.targets, feed_dict = feed_dict) res",
"= {'act_pred' : self.wm.act_pred, 'act_loss' : self.wm.act_loss, 'act_optimizer' : act_opt, 'um_optimizer' : um_opt,",
"postprocess(self, training_results, batch): global_step = training_results['global_step'] res = {} print('postprocessor deets') print(global_step) print(self.big_save_freq)",
"for other in batch['recent']['other']] res['batch'] = {'obs' : batch['depths1'], 'act' : batch['action'], 'act_post'",
"= updater_params['image_shape'] act_dim = updater_params['act_dim'] print('setting up save loc') self.hdf5 = hdf5 =",
"# for idx in self.map_draw_example_indices: # obs_for_actor = [batch[self.state_desc][idx][t] for t in self.map_draw_timestep_indices]",
"self.um.var_list) self.targets = {'um_loss' : self.um.uncertainty_loss, 'um_lr' : um_lr, 'um_optimizer' : um_opt, 'global_step'",
"#checking that we don't have repeat names def start(self, sess): self.data_provider.start_runner(sess) sess.run(tf.global_variables_initializer()) def",
"+ self.wm.encode_var_list) self.targets['act_opt'] = act_opt if not freeze_um: num_not_frozen += 1 um_opt_params, um_opt",
"self.wm.encode_var_list) fut_opt_params, fut_opt = get_optimizer(fut_lr, self.wm.fut_loss, self.fut_step, optimizer_params['world_model']['fut_model'], var_list = self.wm.fut_var_list) self.targets['act_opt'] =",
"= updater_params['N_save'] height, width = updater_params['image_shape'] act_dim = updater_params['act_dim'] print('setting up save loc')",
"in batch['other']] #action_sample = [other[2] for other in batch['other']] res['batch'] = {} for",
"= little_save_keys self.big_save_len = big_save_len self.big_save_freq = big_save_freq self.state_descriptor = state_descriptor def postprocess(self,",
"np.array([replace_the_nones(obs[state_desc])[:-1]]) actions = np.array([replace_the_nones(act)]) action_ids_list = [] for i in range(2): action_msg =",
"next_depths class ExperienceReplayPostprocessor: def __init__(self, big_save_keys = None, little_save_keys = None, big_save_len =",
"self.um = models['uncertainty_model'] freeze_wm = updater_params['freeze_wm'] freeze_um = updater_params['freeze_um'] self.postprocessor = postprocessor self.global_step",
"'act_loss' : self.wm.act_loss, 'act_optimizer' : act_opt, 'um_optimizer' : um_opt, 'estimated_world_loss' : self.um.estimated_world_loss, 'um_loss'",
"(N, height, width, 3), dtype = np.uint8), 'images1': hdf5.require_dataset('images1', shape = (N, height,",
": estimated_world_loss, 'action_samples' : action_samples, 'depths1' : batch[self.state_desc][idx], 'action' : batch['action'][idx], 'action_post' :",
"self.postprocessor.postprocess(res, batch) return res class DebuggingForceMagUpdater: def __init__(self, models, data_provider, optimizer_params, learning_rate_params, postprocessor,",
"um_learning_rate, 'optimizer' : um_opt, 'global_step' : self.global_step} self.postprocessor = postprocessor self.world_action_time = self.world_model.action.get_shape().as_list()[1]",
"res = self.postprocessor.postprocess(wm_res_new, batch) return res class DamianWMUncertaintyUpdater: def __init__(self, world_model, uncertainty_model, data_provider,",
"self.map_draw_mode = 'specified_indices' #relies on there being just one obs type self.state_desc =",
"is not None and global_step % self.map_draw_freq == 0: # if self.map_draw_mode ==",
"is None else True def run(self, sess): batch = self.dp.dequeue_batch() feed_dict = {",
"um_opt, 'estimated_world_loss' : self.um.estimated_world_loss, 'um_loss' : self.um.uncertainty_loss, 'loss_per_example' : self.um.true_loss, 'global_step' : self.global_step}",
"tf.int32)) self.fut_step = tf.get_variable('fut_step', [], tf.int32, initializer = tf.constant_initializer(0,dtype = tf.int32)) self.um_step =",
"for timepoint in obs[desc]] for obs in batch.states]) # actions = np.array([[np.zeros(batch.next_state['action'][-1].shape, batch.next_state['action'][-1].dtype)",
"learning_rate_params['world_model']['act_model']) self.um_lr_params, um_lr = get_learning_rate(self.global_step, ** learning_rate_params['uncertainty_model']) num_not_frozen = 0 self.targets = {}",
"log_prob_tf = tf.nn.log_softmax(rl_model.logits) prob_tf = tf.nn.softmax(rl_model.logits) pi_loss = -tf.reduce_sum(tf.reduce_sum(log_prob_tf * self.ac, [1]) *",
"'action_sample' : action, 'estimated_world_loss' : estimated_world_loss, 'action_samples' : action_samples, 'depths1' : batch[self.state_desc][idx], 'action'",
"np.array([batch.next_state['depths1']]) # return depths, actions, next_depth def postprocess_batch_for_actionmap(batch, state_desc): obs, msg, act =",
"#action_sample = [other[2] for other in batch['other']] res['batch'] = {} for desc, val",
"self.targets['act_opt'] = act_opt if not freeze_um: num_not_frozen += 1 um_opt_params, um_opt = get_optimizer(um_lr,",
"{ self.wm.states : batch[state_desc], self.wm.action : batch['action'], self.wm.action_post : batch['action_post'] } if self.um.insert_obj_there:",
"'optimizer' : wm_opt, 'prediction' : self.world_model.pred, 'tv' : self.world_model.tv} self.inc_step = self.global_step.assign_add(1) self.um_lr_params,",
"= um_opt if num_not_frozen == 0: self.targets['global_step'] = self.global_step self.targets['increment'] = tf.assign_add(self.global_step, 1)",
"= models['world_model'] self.targets = {'um_loss' : self.um.uncertainty_loss, 'loss_per_example' : self.um.true_loss, 'estimated_world_loss' : self.um.estimated_world_loss}",
"batch['obj_there'] } res = sess.run(self.targets, feed_dict = feed_dict) res = self.postprocessor.postprocess(res, batch) return",
"data_provider): self.um = um = models['uncertainty_model'] self.wm = wm = models['world_model'] self.targets =",
"= [1 if msg is not None and msg['msg']['action_type'] == 'OBJ_ACT' else 0",
"in enumerate(self.data_provider): provider_batch = dp.dequeue_batch() for k in provider_batch: if k in batch:",
"self.um = models['uncertainty_model'] self.wm = models['world_model'] self.targets = {'um_loss' : self.um.uncertainty_loss, 'loss_per_example' :",
"obs_for_actor = [batch[self.state_desc][idx][t] for t in self.map_draw_timestep_indices] action_samples = self.action_sampler.sample_actions() action, entropy, estimated_world_loss",
"is not None, (self.map_draw_mode, action_sampler) self.map_draw_example_indices = updater_params['map_draw_example_indices'] self.map_draw_timestep_indices = updater_params['map_draw_timestep_indices'] self.map_draw_freq =",
"self.um.act(sess, action_samples, obs_for_actor) # to_add = {'example_id' : idx, 'action_sample' : action, 'estimated_world_loss'",
"learning_rate_params['uncertainty_model']) um_opt_params, um_opt = get_optimizer(um_lr, self.um.uncertainty_loss, self.global_step, optimizer_params['uncertainty_model'], var_list = self.um.var_list) self.targets =",
"and global_step % self.map_draw_freq == 0: # if self.map_draw_mode == 'specified_indices': # map_draw_res",
"self.wm.encoding_f, 'fut_pred' : self.wm.fut_pred, 'act_pred' : self.wm.act_pred, 'act_optimizer' : act_opt, 'fut_optimizer' : fut_opt,",
"= None, big_save_freq = None, state_descriptor = None): self.big_save_keys = big_save_keys self.little_save_keys =",
"action_ids_list.append(idx) action_ids = np.array([action_ids_list]) return depths_past, objects, actions, action_ids, depths_fut # def postprocess_batch_for_actionmap(batch):",
": self.wm.fut_loss, 'act_loss' : self.wm.act_loss, 'um_loss' : self.um.uncertainty_loss, 'estimated_world_loss' : self.um.estimated_world_loss, 'loss_per_example' :",
"True def run(self, sess): batch = self.dp.dequeue_batch() feed_dict = { self.wm.states : batch[self.state_desc],",
"batch = self.dp.dequeue_batch() feed_dict = { self.wm.action : batch['action'], self.wm.action_post : batch['action_post'], self.um.obj_there",
"else: self.global_step = self.global_step / num_not_frozen self.targets['global_step'] = self.global_step self.targets.update({'act_lr' : act_lr, 'um_lr'",
"act, act_post = batch depths = replace_the_nones(obs[state_desc]) obs_past = np.array([depths[:-1]]) obs_fut = np.array([depths[1:]])",
"= updater_params['state_desc'] def update(self, sess, visualize = False): batch = self.dp.dequeue_batch() state_desc =",
"= get_learning_rate(self.fut_step, **learning_rate_params['world_model']['fut_model']) act_opt_params, act_opt = get_optimizer(act_lr, self.wm.act_loss, self.act_step, optimizer_params['world_model']['act_model'], var_list = self.wm.act_var_list",
"get_optimizer(um_learning_rate, self.um.uncertainty_loss, self.global_step, optimizer_params['uncertainty_model']) self.um_targets = {'loss' : self.um.uncertainty_loss, 'learning_rate' : um_learning_rate, 'optimizer'",
"= training_results['global_step'] res = {} print('postprocessor deets') print(global_step) print(self.big_save_freq) print(self.big_save_len) if (global_step) %",
"print(learning_rate_params.keys()) um_lr_params, um_lr = get_learning_rate(self.global_step, **learning_rate_params['uncertainty_model']) um_opt_params, um_opt = get_optimizer(um_lr, self.um.uncertainty_loss, self.global_step, optimizer_params['uncertainty_model'])",
"sess.run(self.targets, feed_dict = feed_dict) class ActionUncertaintyValidator: def __init__(self, models, data_provider): self.um = um",
"'act_loss' : self.wm.act_loss, 'estimated_world_loss' : self.um.estimated_world_loss, 'um_loss' : self.um.uncertainty_loss, 'loss_per_example' : self.um.true_loss} self.dp",
"batch = self.dp.dequeue_batch() state_desc = self.state_desc feed_dict = { self.wm.states : batch[state_desc], self.wm.action",
"learning_rate_params['world_model']['fut_model']) self.um_lr_params, um_lr = get_learning_rate(self.global_step, ** learning_rate_params['uncertainty_model']) act_opt_params, act_opt = get_optimizer(act_lr, self.wm.act_loss, self.global_step,",
"act_lr = get_learning_rate(self.global_step, ** learning_rate_params['world_model']['act_model']) self.um_lr_params, um_lr = get_learning_rate(self.global_step, ** learning_rate_params['uncertainty_model']) act_opt_params, act_opt",
"self.um.true_loss, 'estimated_world_loss' : self.um.estimated_world_loss } self.state_desc = updater_params['state_desc'] def update(self, sess, visualize =",
"world_model_res['loss_per_example'] } um_res = sess.run(self.um_targets, feed_dict = um_feed_dict) wm_res_new = dict(('wm_' + k,",
"# 'action' : batch['action'][idx], 'action_post' : batch['action_post'][idx]} # map_draw_res.append(to_add) #res['map_draw'] = map_draw_res return",
"feed_dict = feed_dict) glstep = res['global_step'] res = self.postprocessor.postprocess(res, batch) return res, glstep",
"self.wm = wm = models['world_model'] self.targets = {'act_pred' : self.wm.act_pred, 'act_loss' : self.wm.act_loss,",
"= -10000#just something that's not an id seen action_ids_list.append(idx) action_ids = np.array([action_ids_list]) return",
"'images1', 'action', 'action_post']: tosave = batch['recent'][k] if k in ['action', 'action_post']: tosave =",
"False if data_provider.num_objthere is None else True def run(self, sess): batch = self.dp.dequeue_batch()",
"optimizer_params, learning_rate_params, postprocessor, updater_params = None): self.data_provider = data_provider self.wm = world_model self.um",
"def __init__(self, models, data_provider, optimizer_params, learning_rate_params, postprocessor, updater_params, action_sampler = None): self.data_provider =",
": np.array([world_model_res['loss']]) } um_res = sess.run(self.um_targets, feed_dict = um_feed_dict) wm_res_new = dict(('wm_' +",
"k in ['depths1', 'objects1', 'images1', 'action', 'action_post']: tosave = batch['recent'][k] if k in",
"act_opt_params, act_opt = get_optimizer(act_lr, self.wm.act_loss, self.global_step, optimizer_params['world_model']['act_model'], var_list = self.wm.act_var_list + self.wm.encode_var_list) fut_opt_params,",
"and msg['msg']['action_type'] == 'OBJ_ACT' else 0 for msg in provider_recent['msg']] mean_per_provider.append(np.mean(looking_at_obj)) res['obj_freq'] =",
"self.global_step = self.global_step / 2 self.um_targets = {'loss' : self.um.uncertainty_loss, 'learning_rate' : um_learning_rate,",
"'msg' in batch['recent']: looking_at_obj = [1 if msg is not None and msg['msg']['action_type']",
"# depths = np.array([[timepoint if timepoint is not None else np.zeros(obs['depths1'][-1].shape, dtype =",
"= [other[1] for other in batch['recent']['other']] action_sample = [other[2] for other in batch['recent']['other']]",
"self.world_model.loss, self.global_step, optimizer_params['world_model']) self.world_model_targets = {'given' : self.world_model.processed_input, 'loss' : self.world_model.loss, 'learning_rate' :",
"np.array([depths[:1]]) objects = np.array([replace_the_nones(obs[state_desc])[:-1]]) actions = np.array([replace_the_nones(act)]) action_ids_list = [] for i in",
"actions, next_depth def postprocess_batch_for_actionmap(batch, state_desc): obs, msg, act = batch prepped = {}",
"batch = self.data_provider.dequeue_batch() state_desc = self.um.state_descriptor wm_feed_dict = { self.world_model.states : batch[state_desc], self.world_model.action",
"= {'msg' : hdf5.require_dataset('msg', shape = (N,), dtype = dt), 'depths1' : hdf5.require_dataset('depths1',",
": self.um.estimated_world_loss } self.state_desc = updater_params['state_desc'] def update(self, sess, visualize = False): batch",
": self.um.uncertainty_loss, 'estimated_world_loss' : self.um.estimated_world_loss, 'loss_per_example' : self.um.true_loss, 'act_loss_per_example' : self.wm.act_loss_per_example } self.dp",
"pair[0] in save_keys)) #if 'other' in batch['recent']: # entropies = [other[0] for other",
"[] # for i in range(2): # action_msg = batch.next_state['msg'][i]['msg']['actions'] if batch.next_state['msg'][i] is",
"self.um_lr_params, um_lr = get_learning_rate(self.global_step, ** learning_rate_params['uncertainty_model']) um_opt_params, um_opt = get_optimizer(um_lr, self.um.uncertainty_loss, self.global_step, optimizer_params['uncertainty_model'],",
"= 'specified_indices' #relies on there being just one obs type self.state_desc = data_provider.data_lengths['obs'].keys()[0]",
"self.big_save_keys = big_save_keys self.little_save_keys = little_save_keys self.big_save_len = big_save_len self.big_save_freq = big_save_freq self.state_descriptor",
"actions = np.array([replace_the_nones(act)]) actions_post = np.array([replace_the_nones(act_post)]) return obs_past, actions, actions_post, obs_fut # def",
"self.action_sampler = action_sampler assert self.map_draw_mode == 'specified_indices' and self.action_sampler is not None, (self.map_draw_mode,",
"num_not_frozen = 0 self.targets = {} self.state_desc = updater_params.get('state_desc', 'depths1') if not freeze_wm:",
"= dt), 'depths1' : hdf5.require_dataset('depths1', shape = (N, height, width, 3), dtype =",
"feed_dict = { self.wm.states : batch['depths1'], self.wm.action : batch['action'], self.wm.action_post : batch['action_post'] }",
"self.global_step = tf.get_variable('global_step', [], tf.int32, initializer = tf.constant_initializer(0,dtype = tf.int32)) self.um_lr_params, um_lr =",
"self.postprocessor.postprocess(wm_res_new, batch) return res class DamianWMUncertaintyUpdater: def __init__(self, world_model, uncertainty_model, data_provider, optimizer_params, learning_rate_params,",
"'recent': res['batch'][desc] = val[:, -1] res['recent'] = batch['recent'] class ObjectThereValidater: def __init__(self, models,",
"tf.int32, initializer = tf.constant_initializer(0,dtype = tf.int32)) self.fut_step = tf.get_variable('fut_step', [], tf.int32, initializer =",
"class ActionUncertaintyUpdater: def __init__(self, models, data_provider, optimizer_params, learning_rate_params, postprocessor, updater_params): self.data_provider = data_provider",
"tf.assign_add(self.um.step, 1) assert 'um_increment' not in self.targets self.targets['um_increment'] = um_increment self.obj_there_supervision = updater_params.get('include_obj_there',",
"/ 2 self.targets = {'act_pred' : self.wm.act_pred, 'act_loss' : self.wm.act_loss, 'act_optimizer' : act_opt,",
"= res['global_step'] res = self.postprocessor.postprocess(res, batch) return res, glstep class LatentUncertaintyUpdater: def __init__(self,",
"other in batch['recent']['other']] # entropies = np.mean(entropies) # res['entropy'] = entropies if 'msg'",
"int(action_msg[0]['id']) # action_ids_list.append(idx) # action_ids = np.array([action_ids_list]) # next_depths = np.array([batch.next_state['depths1']]) # return",
"self.wm.action : batch['action'], self.wm.action_post : batch['action_post'], self.um.obj_there : batch['obj_there'] } res = sess.run(self.targets,",
"self.targets['global_step'] = self.global_step self.targets.update({'act_lr' : act_lr, 'um_lr' : um_lr}) assert set(self.wm.readouts.keys()) != set(self.um.readouts.keys())",
"# action_ids_list.append(idx) # action_ids = np.array([action_ids_list]) # next_depths = np.array([batch.next_state['depths1']]) # return prepped['depths1'],",
"wm_feed_dict = { self.world_model.states : batch[state_desc], self.world_model.action : batch['action'][:, -self.world_action_time : ] }",
"[other[0] for other in batch['recent']['other']] # entropies = np.mean(entropies) # res['entropy'] = entropies",
": self.um.true_loss, 'estimated_world_loss' : self.um.estimated_world_loss, 'ans' : self.um.ans, 'oh_my_god' : self.um.oh_my_god, 'model_parameters' :",
"update(self, sess, visualize = False): batch = {} for i, dp in enumerate(self.data_provider):",
"= tf.int32)) print(learning_rate_params.keys()) um_lr_params, um_lr = get_learning_rate(self.global_step, **learning_rate_params['uncertainty_model']) um_opt_params, um_opt = get_optimizer(um_lr, self.um.uncertainty_loss,",
"# res['map_draw'] = map_draw_res res = self.postprocessor.postprocess(res, batch) return res, global_step class FreezeUpdater:",
"batch['recent']['other']] entropies = np.mean(entropies) res['entropy'] = entropies looking_at_obj = [1 if msg is",
":-1], self.um.action_sample : batch['action'][:, -1], self.um.true_loss : world_model_res['loss_per_example'] } um_res = sess.run(self.um_targets, feed_dict",
"'action_post' : batch['action_post'][idx]} # map_draw_res.append(to_add) # res['map_draw'] = map_draw_res res = self.postprocessor.postprocess(res, batch)",
"== 'specified_indices': # map_draw_res = [] # for idx in self.map_draw_example_indices: # obs_for_actor",
"looking_at_obj = [1 if msg is not None and msg['msg']['action_type']['OBJ_ACT'] else 0 for",
": batch['action'][idx], 'action_post' : batch['action_post'][idx]} map_draw_res.append(to_add) res['map_draw'] = map_draw_res res = self.postprocessor.postprocess(res, batch)",
"tf.int32)) self.targets = {} self.state_desc = updater_params.get('state_desc', 'depths1') if not freeze_wm: act_lr_params, act_lr",
"res['obj_freq_per_provider_noprint'] = mean_per_provider return res class UncertaintyPostprocessor: def __init__(self, big_save_keys = None, little_save_keys",
"self.wm.obj_there : batch['obj_there'] } res = sess.run(self.targets, feed_dict = feed_dict) res['batch'] = {}",
"= (N, height, width, 3), dtype = np.uint8), 'action' : hdf5.require_dataset('action', shape =",
"get_learning_rate(self.global_step, ** learning_rate_params['world_model']['act_model']) self.um_lr_params, um_lr = get_learning_rate(self.global_step, ** learning_rate_params['uncertainty_model']) act_opt_params, act_opt = get_optimizer(act_lr,",
"# entropies = np.mean(entropies) # res['entropy'] = entropies if 'msg' in batch['recent']: looking_at_obj",
"v) in training_results.iteritems() if k in save_keys)) #res['msg'] = batch['msg'][-1] entropies = [other[0]",
"= np.mean(entropies) res['entropy'] = entropies looking_at_obj = [1 if msg is not None",
": end] = [json.dumps(msg) for msg in batch['recent']['msg']] self.start = end def close(self):",
"var_list = self.um.var_list) self.global_step = self.global_step / 3 self.targets = {'encoding_i' : self.wm.encoding_i,",
"'act_optimizer' : act_opt, 'um_optimizer' : um_opt, 'estimated_world_loss' : self.um.estimated_world_loss, 'um_loss' : self.um.uncertainty_loss, 'loss_per_example'",
"[] for i in range(2): action_msg = msg[i]['msg']['actions'] if msg[i] is not None",
"optimizer_params['world_model']['act_model'], var_list = self.wm.act_var_list + self.wm.encode_var_list) self.targets['act_opt'] = act_opt if not freeze_um: num_not_frozen",
"self.eta = eta self.global_step = tf.get_variable('global_step', [], tf.int32, initializer = tf.constant_initializer(0,dtype = tf.int32))",
"action_ids, depths_fut # def postprocess_batch_for_actionmap(batch): # prepped = {} # for desc in",
": act_opt, 'um_optimizer' : um_opt, 'estimated_world_loss' : self.um.estimated_world_loss, 'um_loss' : self.um.uncertainty_loss, 'loss_per_example' :",
"3 self.targets = {'encoding_i' : self.wm.encoding_i, 'encoding_f' : self.wm.encoding_f, 'fut_pred' : self.wm.fut_pred, 'act_pred'",
"depths = replace_the_nones(obs[state_desc]) obs_past = np.array([depths[:-1]]) obs_fut = np.array([depths[1:]]) actions = np.array([replace_the_nones(act)]) actions_post",
"#self.map_draw_mode = None #Map drawing. Meant to have options, but for now just",
"def postprocess(self, training_results, batch): global_step = training_results['global_step'] res = {} if (global_step) %",
"postprocess_batch_for_actionmap(batch): # prepped = {} # for desc in ['depths1', 'objects1']: # prepped[desc]",
"batch = self.data_provider.dequeue_batch() depths, objects, actions, action_ids, next_depth = postprocess_batch_for_actionmap(batch) wm_feed_dict = {",
"depths, objects, actions, action_ids, next_depth = postprocess_batch_for_actionmap(batch) wm_feed_dict = { self.world_model.s_i : depths,",
"= {'act_pred' : self.wm.act_pred, 'act_loss' : self.wm.act_loss, 'estimated_world_loss' : self.um.estimated_world_loss, 'um_loss' : self.um.uncertainty_loss,",
"self.global_step self.targets.update({'act_lr' : act_lr, 'um_lr' : um_lr}) assert set(self.wm.readouts.keys()) != set(self.um.readouts.keys()) self.targets.update(self.wm.readouts) self.targets.update(self.um.readouts)",
"self.global_step / 3 self.targets = {'encoding_i' : self.wm.encoding_i, 'encoding_f' : self.wm.encoding_f, 'fut_pred' :",
"world_model_res = sess.run(self.world_model_targets, feed_dict = wm_feed_dict) if visualize: cv2.imshow('pred', world_model_res['prediction'][0] / 4.)#TODO clean",
"in batch['recent']['other']] # entropies = np.mean(entropies) # res['entropy'] = entropies if 'msg' in",
"if not freeze_wm: act_lr_params, act_lr = get_learning_rate(self.act_step, **learning_rate_params['world_model']['act_model']) fut_lr_params, fut_lr = get_learning_rate(self.fut_step, **learning_rate_params['world_model']['fut_model'])",
"get_optimizer(act_lr, self.wm.act_loss, self.global_step, optimizer_params['world_model']['act_model'], var_list = self.wm.act_var_list + self.wm.encode_var_list) fut_opt_params, fut_opt = get_optimizer(fut_lr,",
"is the 'batch.' self.action_sampler = action_sampler assert self.map_draw_mode == 'specified_indices' and self.action_sampler is",
"= np.array([replace_the_nones(obs[state_desc])[:-1]]) actions = np.array([replace_the_nones(act)]) action_ids_list = [] for i in range(2): action_msg",
"data_provider, updater_params): self.data_provider = data_provider fn = updater_params['hdf5_filename'] N = updater_params['N_save'] height, width",
"** learning_rate_params['world_model']) self.wm_opt_params, wm_opt = get_optimizer(wm_learning_rate, self.world_model.loss, self.global_step, optimizer_params['world_model']) self.world_model_targets = {'given' :",
"save_keys)) #if 'other' in batch['recent']: # entropies = [other[0] for other in batch['recent']['other']]",
"= get_learning_rate(self.um_step, **learning_rate_params['uncertainty_model']) um_opt_params, um_opt = get_optimizer(um_lr, self.um.uncertainty_loss, self.um_step, optimizer_params['uncertainty_model'], var_list = self.um.var_list)",
"= tf.get_variable('global_step', [], tf.int32, initializer = tf.constant_initializer(0,dtype = tf.int32)) self.act_lr_params, act_lr = get_learning_rate(self.global_step,",
"print('save loc set up') self.start = 0 def update(self): batch = self.data_provider.dequeue_batch() bs",
"['action', 'action_post', 'depths1']: batch[k] = np.concatenate(batch[k], axis=0) feed_dict = { self.wm.states : batch[self.state_desc],",
"sess.run(tf.global_variables_initializer()) def update(self, sess, visualize = False): batch = self.data_provider.dequeue_batch() state_desc = self.um.state_descriptor",
"= batch return res class ActionUncertaintyValidatorWithReadouts: def __init__(self, model, data_provider): self.dp = data_provider",
"save_keys = self.little_save_keys res.update(dict(pair for pair in training_results.iteritems() if pair[0] in save_keys)) #if",
"# prepped[desc] = np.array([[timepoint if timepoint is not None else np.zeros(obs[desc][-1].shape, dtype =",
"sampling is the 'batch.' #self.action_sampler = action_sampler #assert self.map_draw_mode == 'specified_indices' and self.action_sampler",
": actions[:, -1], self.um.true_loss : np.array([world_model_res['loss']]) } um_res = sess.run(self.um_targets, feed_dict = um_feed_dict)",
"print('setting up save loc') self.hdf5 = hdf5 = h5py.File(fn, mode = 'a') dt",
"um_opt_params, um_opt = get_optimizer(um_lr, self.um.uncertainty_loss, self.global_step, optimizer_params['uncertainty_model'], var_list = self.um.var_list) self.targets = {'global_step'",
"action_ids, self.world_model.objects : objects } world_model_res = sess.run(self.world_model_targets, feed_dict = wm_feed_dict) if visualize:",
"= tf.constant_initializer(0,dtype = tf.int32)) self.targets = {} self.state_desc = updater_params.get('state_desc', 'depths1') if not",
"in self.um.readouts.items() if k not in self.um.save_to_gfs}) #this should be changed for an",
"hdf5.require_dataset('msg', shape = (N,), dtype = dt), 'depths1' : hdf5.require_dataset('depths1', shape = (N,",
"= {} self.state_desc = updater_params.get('state_desc', 'depths1') if not freeze_wm: act_lr_params, act_lr = get_learning_rate(self.act_step,",
"get_learning_rate(self.global_step, ** learning_rate_params['world_model']['act_model']) self.um_lr_params, um_lr = get_learning_rate(self.global_step, ** learning_rate_params['uncertainty_model']) num_not_frozen = 0 self.targets",
"of specification #self.state_desc = updater_params.get('state_desc', 'depths1') #self.map_draw_mode = updater_params['map_draw_mode'] #this specification specifices batch",
"= feed_dict) class ActionUncertaintyValidator: def __init__(self, models, data_provider): self.um = um = models['uncertainty_model']",
"get_optimizer(learning_rate, self.rl_loss, ) def replace_the_nones(my_list): ''' Assumes my_list[-1] is np array ''' return",
"um_opt_params, um_opt = get_optimizer(um_lr, self.um.uncertainty_loss, self.global_step, optimizer_params['uncertainty_model'], var_list = self.um.var_list) self.global_step = self.global_step",
"# 'estimated_world_loss' : self.um.estimated_world_loss, # '' # } #self.targets.update({'um_loss' : self.um.uncertainty_loss, 'um_lr' :",
"self.state_desc = updater_params['state_desc'] def update(self, sess, visualize = False): batch = self.dp.dequeue_batch() state_desc",
": um_increment}) self.targets.update(self.wm.readouts) self.targets.update(self.um.readouts) assert set(self.wm.readouts.keys()) != set(self.um.readouts.keys()) def update(self, sess, visualize =",
"= tf.constant_initializer(0,dtype = tf.int32)) self.um_step = tf.get_variable('ext_uncertainty_step', [], tf.int32, initializer = tf.constant_initializer(0,dtype =",
"for msg in batch['recent']['msg']] self.start = end def close(self): self.hdf5.close() class LatentUncertaintyValidator: def",
"actions, actions_post, obs_fut # def postprocess_batch_depth(batch): # depths = np.array([[timepoint if timepoint is",
"None else np.zeros(obs[desc][-1].shape, dtype = obs[desc][-1].dtype) for timepoint in obs[desc]] for obs in",
"update(self, sess, visualize = False): batch = self.data_provider.dequeue_batch() state_desc = self.state_desc feed_dict =",
"desc! ' + self.state_desc) res = sess.run(self.targets, feed_dict = feed_dict) res.pop('um_increment') global_step =",
"= self.wm.act_var_list + self.wm.encode_var_list) fut_opt_params, fut_opt = get_optimizer(fut_lr, self.wm.fut_loss, self.global_step, optimizer_params['world_model']['fut_model'], var_list =",
"action_ids_list = [] for i in range(2): action_msg = msg[i]['msg']['actions'] if msg[i] is",
"= None): self.data_provider = data_provider \\ if isinstance(data_provider, list) else [data_provider] self.wm =",
": self.global_step} self.postprocessor = postprocessor self.world_action_time = self.world_model.action.get_shape().as_list()[1] def start(self, sess): self.data_provider.start_runner(sess) sess.run(tf.global_variables_initializer())",
"get_optimizer(um_lr, self.um.uncertainty_loss, self.global_step, optimizer_params['uncertainty_model'], var_list = self.um.var_list) self.targets = {'um_loss' : self.um.uncertainty_loss, 'um_lr'",
"self.um = um = models['uncertainty_model'] self.wm = wm = models['world_model'] self.targets = {'act_pred'",
"set(self.um.readouts.keys()) self.targets.update(self.wm.readouts) self.targets.update(self.um.readouts) um_increment = tf.assign_add(self.um.step, 1) assert 'um_increment' not in self.targets self.targets['um_increment']",
"the 'batch.' self.action_sampler = action_sampler assert self.map_draw_mode == 'specified_indices' and self.action_sampler is not",
"and self.action_sampler is not None, (self.map_draw_mode, action_sampler) #self.map_draw_example_indices = updater_params['map_draw_example_indices'] #self.map_draw_timestep_indices = updater_params['map_draw_timestep_indices']",
": action_samples, 'depths1' : batch[self.state_desc][idx], 'action' : batch['action'][idx], 'action_post' : batch['action_post'][idx]} map_draw_res.append(to_add) res['map_draw']",
"get_optimizer(um_lr, self.um.uncertainty_loss, self.um_step, optimizer_params['uncertainty_model'], var_list = self.um.var_list) self.targets['um_opt'] = um_opt self.targets['um_lr'] = um_lr",
"= self.wm.act_var_list + self.wm.encode_var_list) self.targets['act_opt'] = act_opt if not freeze_um: num_not_frozen += 1",
"= self.data_provider.dequeue_batch() state_desc = self.state_desc #depths, actions, actions_post, next_depth = postprocess_batch_depth(batch, state_desc) feed_dict",
"np.array([depths[:-1]]) obs_fut = np.array([depths[1:]]) actions = np.array([replace_the_nones(act)]) actions_post = np.array([replace_the_nones(act_post)]) return obs_past, actions,",
"id seen action_ids_list.append(idx) action_ids = np.array([action_ids_list]) return depths_past, objects, actions, action_ids, depths_fut #",
"obs_past, actions, actions_post, obs_fut # def postprocess_batch_depth(batch): # depths = np.array([[timepoint if timepoint",
"+ self.wm.encode_var_list) um_opt_params, um_opt = get_optimizer(um_lr, self.um.uncertainty_loss, self.global_step, optimizer_params['uncertainty_model'], var_list = self.um.var_list) self.global_step",
"self.world_model.loss, 'learning_rate' : wm_learning_rate, 'optimizer' : wm_opt, 'prediction' : self.world_model.pred, 'tv' : self.world_model.tv}",
"if desc not in ['recent', 'depths1', 'objects1', 'images1']: res['batch'][desc] = val res['recent'] =",
"self.map_draw_mode == 'specified_indices' and self.action_sampler is not None, (self.map_draw_mode, action_sampler) self.map_draw_example_indices = updater_params['map_draw_example_indices']",
"= end def close(self): self.hdf5.close() class LatentUncertaintyValidator: def __init__(self, models, data_provider): self.um =",
"self.wm_lr_params, wm_learning_rate = get_learning_rate(self.global_step, ** learning_rate_params['world_model']) self.wm_opt_params, wm_opt = get_optimizer(wm_learning_rate, self.world_model.loss, self.global_step, optimizer_params['world_model'])",
"= obs[desc][-1].dtype) for timepoint in obs[desc]] for obs in batch.states]) # actions =",
"for i, dp in enumerate(self.data_provider): provider_batch = dp.dequeue_batch() for k in provider_batch: if",
"- self.r)) entropy = -tf.reduce_sum(prob_tf * log_prob_tf) self.rl_loss = pi_loss + 0.5 *",
"self.global_step = tf.get_variable('global_step', [], tf.int32, initializer = tf.constant_initializer(0,dtype = tf.int32)) self.wm_lr_params, wm_learning_rate =",
"= 0 def update(self): batch = self.data_provider.dequeue_batch() bs = len(batch['recent']['msg']) end = self.start",
"{ self.wm.states : batch['depths1'], self.wm.action : batch['action'], self.wm.action_post : batch['action_post'], self.wm.obj_there : batch['obj_there']",
"= self.dp.dequeue_batch() feed_dict = { self.wm.states : batch['depths1'], self.wm.action : batch['action'], self.wm.obj_there :",
"for k in ['action', 'action_post', 'depths1']: batch[k] = np.concatenate(batch[k], axis=0) feed_dict = {",
"'prediction' : self.world_model.pred, 'tv' : self.world_model.tv} self.inc_step = self.global_step.assign_add(1) self.wm_lr_params, um_learning_rate = get_learning_rate(self.global_step,",
"= self.big_save_keys #est_losses = [other[1] for other in batch['other']] #action_sample = [other[2] for",
"self.wm.act_loss, 'estimated_world_loss' : self.um.estimated_world_loss, 'um_loss' : self.um.uncertainty_loss, 'loss_per_example' : self.um.true_loss} self.dp = data_provider",
"batch[k] = [provider_batch[k]] for k in ['action', 'action_post', self.state_desc]: batch[k] = np.concatenate(batch[k], axis=0)",
"= { self.wm.states : batch['depths1'], self.wm.action : batch['action'], self.wm.action_post : batch['action_post'] } res",
"res = self.postprocessor.postprocess(res, batch) return res, global_step class ActionUncertaintyUpdater: def __init__(self, models, data_provider,",
"= uncertainty_model self.global_step = tf.get_variable('global_step', [], tf.int32, initializer = tf.constant_initializer(0,dtype = tf.int32)) self.wm_lr_params,",
"self.um.true_loss, 'estimated_world_loss' : self.um.estimated_world_loss } if self.um.exactly_whats_needed: self.targets['oh_my_god'] = self.um.oh_my_god self.state_desc = updater_params['state_desc']",
"[] # for idx in self.map_draw_example_indices: # obs_for_actor = [batch[self.state_desc][idx][t] for t in",
"self.little_save_keys = little_save_keys self.big_save_len = big_save_len self.big_save_freq = big_save_freq self.state_descriptor = state_descriptor def",
"one obs type self.state_desc = data_provider.data_lengths['obs'].keys()[0] self.insert_objthere = False if data_provider.num_objthere is None",
"'estimated_world_loss' : self.um.estimated_world_loss, 'um_loss' : self.um.uncertainty_loss, 'loss_per_example' : self.um.true_loss} self.dp = data_provider def",
"self.world_model.loss, self.global_step, optimizer_params['world_model']) self.world_model_targets = {'given' : self.world_model.processed_input, 'loss' : self.world_model.loss, 'loss_per_example' :",
"# 'fut_pred' : self.wm.fut_pred, 'act_pred' : self.wm.act_pred, # 'fut_loss' : self.wm.fut_loss, 'act_loss' :",
"(self.map_draw_mode, action_sampler) #self.map_draw_example_indices = updater_params['map_draw_example_indices'] #self.map_draw_timestep_indices = updater_params['map_draw_timestep_indices'] #self.map_draw_freq = updater_params['map_draw_freq'] def update(self,",
"return sess.run(self.targets, feed_dict = feed_dict) class ActionUncertaintyValidator: def __init__(self, models, data_provider): self.um =",
"= (N,), dtype = dt), 'depths1' : hdf5.require_dataset('depths1', shape = (N, height, width,",
"{} if (global_step) % self.big_save_freq < self.big_save_len: save_keys = self.big_save_keys #est_losses = [other[1]",
"cv2.imshow('processed0', world_model_res['given'][0, 0] / 4.) cv2.imshow('processed1', world_model_res['given'][0, 1] / 4.) cv2.waitKey(1) print('wm loss:",
"return res, global_step class ActionUncertaintyUpdater: def __init__(self, models, data_provider, optimizer_params, learning_rate_params, postprocessor, updater_params):",
"def update(self): batch = self.data_provider.dequeue_batch() bs = len(batch['recent']['msg']) end = self.start + bs",
"#if self.map_draw_mode == 'specified_indices': # map_draw_res = [] # for idx in self.map_draw_example_indices:",
"{'obs' : batch['depths1'], 'act' : batch['action'], 'act_post' : batch['action_post'], 'est_loss' : est_losses, 'action_sample'",
"print(len(batch.next_state['action'])) # action_ids_list = [] # for i in range(2): # action_msg =",
"sort of specification #self.state_desc = updater_params.get('state_desc', 'depths1') #self.map_draw_mode = updater_params['map_draw_mode'] #this specification specifices",
"in batch['other']] res['batch'] = {} for desc, val in batch.iteritems(): if desc not",
"def update(self, sess, visualize = False): if self.um.just_random: print('Selecting action at random') batch",
"batch depths = replace_the_nones(obs[state_desc]) obs_past = np.array([depths[:-1]]) obs_fut = np.array([depths[1:]]) actions = np.array([replace_the_nones(act)])",
"self.um.var_list) self.targets['um_opt'] = um_opt if num_not_frozen == 0: self.targets['global_step'] = self.global_step self.targets['increment'] =",
"self.global_step, 'loss_per_example' : self.um.true_loss, 'estimated_world_loss' : self.um.estimated_world_loss } if self.um.exactly_whats_needed: self.targets['oh_my_god'] = self.um.oh_my_god",
"get_learning_rate(self.global_step, **learning_rate_params['uncertainty_model']) self.um_lr_params, um_opt = get_optimizer(um_learning_rate, self.um.uncertainty_loss, self.global_step, optimizer_params['uncertainty_model']) self.global_step = self.global_step /",
"'estimated_world_loss' : self.um.estimated_world_loss } self.targets.update({'um_loss' : self.um.uncertainty_loss, 'um_lr' : um_lr, 'um_optimizer' : um_opt,",
"res['obj_freq'] = np.mean(looking_at_obj) return res class DataWriteUpdater: def __init__(self, data_provider, updater_params): self.data_provider =",
"= get_optimizer(um_lr, self.um.uncertainty_loss, self.global_step, optimizer_params['uncertainty_model']) self.targets = {'um_loss' : self.um.uncertainty_loss, 'um_optimizer' : um_opt,",
"{ self.wm.states : batch[self.state_desc], self.wm.action : batch['action'], self.wm.action_post : batch ['action_post'] } if",
"\\ if isinstance(data_provider, list) else [data_provider] self.wm = models['world_model'] self.um = models['uncertainty_model'] freeze_wm",
"axis = 0) feed_dict[self.wm.obj_there_via_msg] = batch['obj_there'] print('state desc! ' + self.state_desc) res =",
"** learning_rate_params['uncertainty_model']) num_not_frozen = 0 self.targets = {} self.state_desc = updater_params.get('state_desc', 'depths1') if",
"action_samples, 'depths1' : batch[self.state_desc][idx], # 'action' : batch['action'][idx], 'action_post' : batch['action_post'][idx]} # map_draw_res.append(to_add)",
"= postprocess_batch_for_actionmap(batch) wm_feed_dict = { self.world_model.s_i : depths, self.world_model.s_f : next_depth, self.world_model.action :",
"updater_params['state_desc'] def update(self, sess, visualize = False): batch = self.dp.dequeue_batch() state_desc = self.state_desc",
": um_lr}) assert set(self.wm.readouts.keys()) != set(self.um.readouts.keys()) self.targets.update(self.wm.readouts) self.targets.update(self.um.readouts) um_increment = tf.assign_add(self.um.step, 1) assert",
"= [provider_batch[k]] for k in ['action', 'action_post', 'depths1']: batch[k] = np.concatenate(batch[k], axis=0) feed_dict",
"in batch['recent']['msg']] self.start = end def close(self): self.hdf5.close() class LatentUncertaintyValidator: def __init__(self, models,",
"res class DamianWMUncertaintyUpdater: def __init__(self, world_model, uncertainty_model, data_provider, optimizer_params, learning_rate_params, postprocessor): self.data_provider =",
"one forward pass each index because action sampling is the 'batch.' self.action_sampler =",
"#self.map_draw_mode = updater_params['map_draw_mode'] #this specification specifices batch example indices for which we do",
"big_save_freq self.state_descriptor = state_descriptor def postprocess(self, training_results, batch): global_step = training_results['global_step'] res =",
"# if len(action_msg): # idx = int(action_msg[0]['id']) # action_ids_list.append(idx) # action_ids = np.array([action_ids_list])",
"um_opt, 'global_step' : self.global_step, 'loss_per_example' : self.um.true_loss, 'estimated_world_loss' : self.um.estimated_world_loss, 'ans' : self.um.ans,",
"if pair[0] in save_keys)) #if 'other' in batch['recent']: # entropies = [other[0] for",
"fn = updater_params['hdf5_filename'] N = updater_params['N_save'] height, width = updater_params['image_shape'] act_dim = updater_params['act_dim']",
"= feed_dict) global_step = res['global_step'] if self.map_draw_mode is not None and global_step %",
"'um_loss' : self.um.uncertainty_loss, 'loss_per_example' : self.um.true_loss} self.dp = data_provider def run(self, sess): batch",
"= tf.constant_initializer(0,dtype = tf.int32)) self.act_step = tf.get_variable('act_step', [], tf.int32, initializer = tf.constant_initializer(0,dtype =",
"obs, msg, act, act_post = batch depths = replace_the_nones(obs[state_desc]) obs_past = np.array([depths[:-1]]) obs_fut",
"um_increment}) self.targets.update(self.wm.readouts) self.targets.update(self.um.readouts) assert set(self.wm.readouts.keys()) != set(self.um.readouts.keys()) def update(self, sess, visualize = False):",
"self.little_save_keys.append('map_draw') self.big_save_keys.extend(['act_lr', 'um_lr']) self.little_save_keys.extend(['act_lr', 'um_lr']) def postprocess(self, training_results, batch): global_step = training_results['global_step'] res",
"self.state_desc = updater_params.get('state_desc', 'depths1') if not freeze_wm: num_not_frozen += 1 act_opt_params, act_opt =",
"feed_dict = feed_dict) global_step = res['global_step'] if self.map_draw_mode is not None and global_step",
"{'act_pred' : self.wm.act_pred, 'act_loss' : self.wm.act_loss, 'act_optimizer' : act_opt, 'um_optimizer' : um_opt, 'estimated_world_loss'",
"self.um_targets = {'loss' : self.um.uncertainty_loss, 'learning_rate' : um_learning_rate, 'optimizer' : um_opt, 'global_step' :",
"__init__(self, big_save_keys = None, little_save_keys = None, big_save_len = None, big_save_freq = None,",
"1] / 4.) cv2.waitKey(1) print('wm loss: ' + str(world_model_res['loss'])) um_feed_dict = { self.um.s_i",
"self.wm_lr_params, um_opt = get_optimizer(um_learning_rate, self.um.uncertainty_loss, self.global_step, optimizer_params['uncertainty_model']) self.um_targets = {'loss' : self.um.uncertainty_loss, 'learning_rate'",
"= np.array([replace_the_nones(act)]) action_ids_list = [] for i in range(2): action_msg = msg[i]['msg']['actions'] if",
"in save_keys)) #if 'other' in batch['recent']: # entropies = [other[0] for other in",
"res = sess.run(self.targets, feed_dict = feed_dict) res['batch'] = {} for desc, val in",
"updater_params['map_draw_timestep_indices'] self.map_draw_freq = updater_params['map_draw_freq'] def update(self, sess, visualize = False): batch = {}",
"= 'a') dt = h5py.special_dtype(vlen = str) self.handles = {'msg' : hdf5.require_dataset('msg', shape",
"depths, actions, next_depth def postprocess_batch_for_actionmap(batch, state_desc): obs, msg, act = batch prepped =",
"self.action_sampler.sample_actions() action, entropy, estimated_world_loss = self.um.act(sess, action_samples, obs_for_actor) to_add = {'example_id' : idx,",
"= models['world_model'] self.targets = { 'act_pred' : self.wm.act_pred, 'fut_loss' : self.wm.fut_loss, 'act_loss' :",
"1 um_opt_params, um_opt = get_optimizer(um_lr, self.um.uncertainty_loss, self.global_step, optimizer_params['uncertainty_model'], var_list = self.um.var_list) self.targets['um_opt'] =",
"(self.map_draw_mode, action_sampler) self.map_draw_example_indices = updater_params['map_draw_example_indices'] self.map_draw_timestep_indices = updater_params['map_draw_timestep_indices'] self.map_draw_freq = updater_params['map_draw_freq'] def update(self,",
"def postprocess_batch_for_actionmap(batch, state_desc): obs, msg, act = batch prepped = {} depths =",
"training_results.iteritems() if pair[0] in save_keys)) #if 'other' in batch['recent']: # entropies = [other[0]",
"self.map_draw_timestep_indices = updater_params['map_draw_timestep_indices'] self.map_draw_freq = updater_params['map_draw_freq'] def update(self, sess, visualize = False): batch",
": self.world_model.loss_per_example, 'learning_rate' : wm_learning_rate, 'optimizer' : wm_opt, 'prediction' : self.world_model.pred, 'tv' :",
"= get_optimizer(act_lr, self.wm.act_loss, self.global_step, optimizer_params['world_model']['act_model'], var_list = self.wm.act_var_list + self.wm.encode_var_list) um_opt_params, um_opt =",
"def update(self, sess, visualize = False): batch = self.data_provider.dequeue_batch() depths, objects, actions, action_ids,",
"= None): self.data_provider = data_provider self.wm = world_model self.um = uncertainty_model self.postprocessor =",
": self.um.estimated_world_loss, # '' # } #self.targets.update({'um_loss' : self.um.uncertainty_loss, 'um_lr' : um_lr, 'um_optimizer'",
"np import cv2 from curiosity.interaction import models import h5py import json class RawDepthDiscreteActionUpdater:",
"sess.run(self.targets, feed_dict = feed_dict) global_step = res['global_step'] if self.map_draw_mode is not None and",
"= { self.um.s_i : batch[state_desc][:, :-1], self.um.action_sample : batch['action'][:, -1], self.um.true_loss : world_model_res['loss_per_example']",
": ] } world_model_res = sess.run(self.world_model_targets, feed_dict = wm_feed_dict) um_feed_dict = { self.um.s_i",
"= self.global_step res = sess.run(self.targets, feed_dict = feed_dict) global_step = res['global_step'] if self.map_draw_mode",
"= self.global_step / 2 self.um_targets = {'loss' : self.um.uncertainty_loss, 'learning_rate' : um_learning_rate, 'optimizer'",
"self.map_draw_example_indices: obs_for_actor = [batch[self.state_desc][idx][t] for t in self.map_draw_timestep_indices] action_samples = self.action_sampler.sample_actions() action, entropy,",
"specification self.state_desc = updater_params.get('state_desc', 'depths1') self.map_draw_mode = updater_params['map_draw_mode'] #this specification specifices batch example",
"'fut_pred' : self.wm.fut_pred, 'act_pred' : self.wm.act_pred, # 'fut_loss' : self.wm.fut_loss, 'act_loss' : self.wm.act_loss,",
"for k, v in self.um.readouts.items() if k not in self.um.save_to_gfs}) #this should be",
"isinstance(data_provider, list) else [data_provider] self.wm = models['world_model'] self.um = models['uncertainty_model'] freeze_wm = updater_params['freeze_wm']",
"batch) return res class SquareForceMagUpdater: def __init__(self, models, data_provider, optimizer_params, learning_rate_params, postprocessor, updater_params):",
"initializer = tf.constant_initializer(0, dtype = tf.int32)) print(learning_rate_params.keys()) um_lr_params, um_lr = get_learning_rate(self.global_step, **learning_rate_params['uncertainty_model']) um_opt_params,",
"actions[:, -1], self.um.true_loss : np.array([world_model_res['loss']]) } um_res = sess.run(self.um_targets, feed_dict = um_feed_dict) wm_res_new",
"__init__(self, models, data_provider, optimizer_params, learning_rate_params, postprocessor, updater_params): self.data_provider = data_provider\\ if isinstance(data_provider, list)",
"= get_learning_rate(self.global_step, ** learning_rate_params['world_model']['act_model']) self.fut_lr_params, fut_lr = get_learning_rate(self.global_step, ** learning_rate_params['world_model']['fut_model']) self.um_lr_params, um_lr =",
"for an online data provider, set to do nothing self.map_draw_mode = 'specified_indices' #relies",
"not None and global_step % self.map_draw_freq == 0: if self.map_draw_mode == 'specified_indices': map_draw_res",
"= self.postprocessor.postprocess(res, batch) return res, global_step class JustUncertaintyUpdater: def __init__(self, models, data_provider, optimizer_params,",
"'depths1') self.map_draw_mode = updater_params['map_draw_mode'] #this specification specifices batch example indices for which we",
"msg[i]['msg']['actions'] if msg[i] is not None else [] if len(action_msg): idx = int(action_msg[0]['id'])",
"(global_step) % self.big_save_freq < self.big_save_len: print('big time') save_keys = self.big_save_keys est_losses = [other[1]",
"= updater_params['map_draw_timestep_indices'] #self.map_draw_freq = updater_params['map_draw_freq'] def update(self, sess, visualize = False): if self.um.just_random:",
"feed_dict) res = self.postprocessor.postprocess(res, batch) return res class SquareForceMagUpdater: def __init__(self, models, data_provider,",
": self.world_model.pred, 'tv' : self.world_model.tv} self.inc_step = self.global_step.assign_add(1) self.wm_lr_params, um_learning_rate = get_learning_rate(self.global_step, **learning_rate_params['uncertainty_model'])",
"= tf.get_variable('ext_uncertainty_step', [], tf.int32, initializer = tf.constant_initializer(0,dtype = tf.int32)) self.targets = {} self.state_desc",
"2 self.um_targets = {'loss' : self.um.uncertainty_loss, 'learning_rate' : um_learning_rate, 'optimizer' : um_opt, 'global_step'",
"batch.iteritems(): print(desc) if desc == 'obj_there': res['batch'][desc] = val elif desc != 'recent':",
"# '' # } #self.targets.update({'um_loss' : self.um.uncertainty_loss, 'um_lr' : um_lr, 'um_optimizer' : um_opt,",
"None, little_save_keys = None, big_save_len = None, big_save_freq = None, state_descriptor = None):",
"# def postprocess_batch_for_actionmap(batch): # prepped = {} # for desc in ['depths1', 'objects1']:",
"-tf.reduce_sum(tf.reduce_sum(log_prob_tf * self.ac, [1]) * self.adv) vf_loss = .5 * tf.reduce_sum(tf.square(rl_model.vf - self.r))",
"update(self, sess, visualize = False): batch = self.data_provider.dequeue_batch() state_desc = self.state_desc #depths, actions,",
"estimated_world_loss = self.um.act(sess, action_samples, obs_for_actor) # to_add = {'example_id' : idx, 'action_sample' :",
"to feed dict') feed_dict[self.um.obj_there] = batch['obj_there'] res = sess.run(self.targets, feed_dict = feed_dict) res",
"= tf.assign_add(self.um.step, 1) self.targets.update({'global_increment' : global_increment, 'um_increment' : um_increment}) self.targets.update(self.wm.readouts) self.targets.update(self.um.readouts) assert set(self.wm.readouts.keys())",
"action_sampler assert self.map_draw_mode == 'specified_indices' and self.action_sampler is not None, (self.map_draw_mode, action_sampler) self.map_draw_example_indices",
"models['uncertainty_model'] self.wm = models['world_model'] self.targets = {'um_loss' : self.um.uncertainty_loss, 'loss_per_example' : self.um.true_loss, 'estimated_world_loss'",
"width, 3), dtype = np.uint8), 'action' : hdf5.require_dataset('action', shape = (N, act_dim), dtype",
"feed_dict[self.wm.obj_there_via_msg] = batch['obj_there'] res = sess.run(self.targets, feed_dict = feed_dict) #TODO case it for",
"= {'obs' : batch['depths1'], 'act' : batch['action'], 'act_post' : batch['action_post'], 'est_loss' : est_losses,",
"for k, v in world_model_res.iteritems()) um_res_new = dict(('um_' + k, v) for k,",
"big_save_len self.big_save_freq = big_save_freq self.state_descriptor = state_descriptor def postprocess(self, training_results, batch): global_step =",
"obj_there to feed dict') feed_dict[self.um.obj_there] = batch['obj_there'] res = sess.run(self.targets, feed_dict = feed_dict)",
"map_draw_res.append(to_add) res['map_draw'] = map_draw_res res = self.postprocessor.postprocess(res, batch) return res, global_step class ActionUncertaintyUpdater:",
"#if self.map_draw_mode is not None and global_step % self.map_draw_freq == 0: # if",
"entropies if 'msg' in batch['recent']: looking_at_obj = [1 if msg is not None",
"batch['obj_there'] } res = sess.run(self.targets, feed_dict = feed_dict) res['batch'] = {} for desc,",
"um_opt, # 'global_step' : self.global_step, 'loss_per_example' : self.um.true_loss}) self.map_draw_mode = None #Map drawing.",
"k in ['action', 'action_post']: tosave = tosave.astype(np.float32) self.handles[k][self.start : end] = batch['recent'][k] self.handles['msg'][self.start",
"self.act_lr_params, act_lr = get_learning_rate(self.global_step, ** learning_rate_params['world_model']['act_model']) self.um_lr_params, um_lr = get_learning_rate(self.global_step, ** learning_rate_params['uncertainty_model']) act_opt_params,",
"sess): self.data_provider.start_runner(sess) sess.run(tf.global_variables_initializer()) def update(self, sess, visualize = False): batch = self.data_provider.dequeue_batch() depths,",
"feed_dict) #TODO case it for online res['recent'] = {} #if self.map_draw_mode == 'specified_indices':",
"action sampling is the 'batch.' #self.action_sampler = action_sampler #assert self.map_draw_mode == 'specified_indices' and",
"global_increment, 'um_increment' : um_increment}) self.targets.update(self.wm.readouts) self.targets.update(self.um.readouts) assert set(self.wm.readouts.keys()) != set(self.um.readouts.keys()) def update(self, sess,",
"not None, (self.map_draw_mode, action_sampler) #self.map_draw_example_indices = updater_params['map_draw_example_indices'] #self.map_draw_timestep_indices = updater_params['map_draw_timestep_indices'] #self.map_draw_freq = updater_params['map_draw_freq']",
"import tensorflow as tf from tfutils.base import get_optimizer, get_learning_rate import numpy as np",
"= self.wm.fut_var_list) um_opt_params, um_opt = get_optimizer(um_lr, self.um.uncertainty_loss, self.global_step, optimizer_params['uncertainty_model'], var_list = self.um.var_list) self.global_step",
"self.um.oh_my_god, 'model_parameters' : self.um.var_list} def update(self, sess): batch = self.dp.dequeue_batch() feed_dict = {",
"specification #self.state_desc = updater_params.get('state_desc', 'depths1') #self.map_draw_mode = updater_params['map_draw_mode'] #this specification specifices batch example",
"fut_opt self.targets['act_lr'] = act_lr self.targets['fut_lr'] = fut_lr if not freeze_um: um_lr_params, um_lr =",
"self.um.true_loss} self.dp = data_provider def run(self, sess): batch = self.dp.dequeue_batch() feed_dict = {",
"res['batch'][desc] = val[:, -1] res['recent'] = batch['recent'] class ObjectThereValidater: def __init__(self, models, data_provider):",
"self.ac, [1]) * self.adv) vf_loss = .5 * tf.reduce_sum(tf.square(rl_model.vf - self.r)) entropy =",
"close(self): self.hdf5.close() class LatentUncertaintyValidator: def __init__(self, models, data_provider): self.um = models['uncertainty_model'] self.wm =",
"self.global_step.assign_add(1) self.wm_lr_params, um_learning_rate = get_learning_rate(self.global_step, **learning_rate_params['uncertainty_model']) self.wm_lr_params, um_opt = get_optimizer(um_learning_rate, self.um.uncertainty_loss, self.global_step, optimizer_params['uncertainty_model'])",
"= tf.nn.log_softmax(rl_model.logits) prob_tf = tf.nn.softmax(rl_model.logits) pi_loss = -tf.reduce_sum(tf.reduce_sum(log_prob_tf * self.ac, [1]) * self.adv)",
"sess.run(self.world_model_targets, feed_dict = wm_feed_dict) um_feed_dict = { self.um.s_i : batch[state_desc][:, :-1], self.um.action_sample :",
"in self.wm.save_to_gfs}) self.targets.update({k : v for k, v in self.um.readouts.items() if k not",
"if self.map_draw_mode == 'specified_indices': map_draw_res = [] for idx in self.map_draw_example_indices: obs_for_actor =",
"data_provider, optimizer_params, learning_rate_params, postprocessor, updater_params): self.data_provider = data_provider\\ if isinstance(data_provider, list) else [data_provider]",
"= np.mean(looking_at_obj) return res class DataWriteUpdater: def __init__(self, data_provider, updater_params): self.data_provider = data_provider",
"global_step = training_results['global_step'] res = {} print('postprocessor deets') print(global_step) print(self.big_save_freq) print(self.big_save_len) if (global_step)",
"v in world_model_res.iteritems()) um_res_new = dict(('um_' + k, v) for k, v in",
"is not None else np.zeros(obs['depths1'][-1].shape, dtype = obs['depths1'][-1].dtype) for timepoint in obs['depths1']] for",
"replace_the_nones(obs[state_desc]) obs_past = np.array([depths[:-1]]) obs_fut = np.array([depths[1:]]) actions = np.array([replace_the_nones(act)]) actions_post = np.array([replace_the_nones(act_post)])",
"wm_opt, 'prediction' : self.world_model.pred, 'tv' : self.world_model.tv} self.inc_step = self.global_step.assign_add(1) self.wm_lr_params, um_learning_rate =",
"action_msg = msg[i]['msg']['actions'] if msg[i] is not None else [] if len(action_msg): idx",
"get_learning_rate(self.global_step, **learning_rate_params['uncertainty_model']) self.wm_lr_params, um_opt = get_optimizer(um_learning_rate, self.um.uncertainty_loss, self.global_step, optimizer_params['uncertainty_model']) self.um_targets = {'loss' :",
"act_lr = get_learning_rate(self.global_step, ** learning_rate_params['world_model']['act_model']) self.fut_lr_params, fut_lr = get_learning_rate(self.global_step, ** learning_rate_params['world_model']['fut_model']) self.um_lr_params, um_lr",
"'optimizer' : um_opt, 'global_step' : self.global_step} self.postprocessor = postprocessor self.world_action_time = self.world_model.action.get_shape().as_list()[1] def",
"self.act_step = tf.get_variable('act_step', [], tf.int32, initializer = tf.constant_initializer(0,dtype = tf.int32)) self.fut_step = tf.get_variable('fut_step',",
"forward pass each index because action sampling is the 'batch.' #self.action_sampler = action_sampler",
"== list and len(batch['recent'][0]) > 0: mean_per_provider = [] for provider_recent in batch['recent']:",
"self.wm.states : batch[state_desc], self.wm.action : batch['action'], self.wm.obj_there : batch['obj_there'] } res = sess.run(self.targets,",
"postprocessor, updater_params, action_sampler = None): self.data_provider = data_provider \\ if isinstance(data_provider, list) else",
"= world_model self.um = uncertainty_model self.global_step = tf.get_variable('global_step', [], tf.int32, initializer = tf.constant_initializer(0,dtype",
"* tf.reduce_sum(tf.square(rl_model.vf - self.r)) entropy = -tf.reduce_sum(prob_tf * log_prob_tf) self.rl_loss = pi_loss +",
"< self.big_save_len: print('big time') save_keys = self.big_save_keys est_losses = [other[1] for other in",
"self.global_step / 2 self.targets = {'act_pred' : self.wm.act_pred, 'act_loss' : self.wm.act_loss, 'act_optimizer' :",
"action, 'estimated_world_loss' : estimated_world_loss, # 'action_samples' : action_samples, 'depths1' : batch[self.state_desc][idx], # 'action'",
"self.global_step, optimizer_params['world_model']['fut_model'], var_list = self.wm.fut_var_list) um_opt_params, um_opt = get_optimizer(um_lr, self.um.uncertainty_loss, self.global_step, optimizer_params['uncertainty_model'], var_list",
"global_step = res['global_step'] if self.map_draw_mode is not None and global_step % self.map_draw_freq ==",
"and msg['msg']['action_type'] == 'OBJ_ACT' else 0 for msg in batch['recent']['msg']] res['obj_freq'] = np.mean(looking_at_obj)",
"for k, v in self.wm.readouts.items() if k not in self.wm.save_to_gfs}) self.targets.update({k : v",
"= None, big_save_len = None, big_save_freq = None, state_descriptor = None): self.big_save_keys =",
"= self.um.var_list) self.global_step = self.global_step / 2 self.targets = {'act_pred' : self.wm.act_pred, 'act_loss'",
"self.um.act(sess, action_samples, obs_for_actor) to_add = {'example_id' : idx, 'action_sample' : action, 'estimated_world_loss' :",
": global_increment, 'um_increment' : um_increment}) self.targets.update(self.wm.readouts) self.targets.update(self.um.readouts) assert set(self.wm.readouts.keys()) != set(self.um.readouts.keys()) def update(self,",
"[other[1] for other in batch['other']] #action_sample = [other[2] for other in batch['other']] res['batch']",
"self.obj_there_supervision = updater_params.get('include_obj_there', False) #self.map_draw_mode = None #Map drawing. Meant to have options,",
"act_opt if not freeze_um: num_not_frozen += 1 um_opt_params, um_opt = get_optimizer(um_lr, self.um.uncertainty_loss, self.global_step,",
"self.data_provider.start_runner(sess) sess.run(tf.global_variables_initializer()) def update(self, sess, visualize = False): batch = self.data_provider.dequeue_batch() state_desc =",
"world_model_res['tv'][0] / 4.) cv2.imshow('processed0', world_model_res['given'][0, 0] / 4.) cv2.imshow('processed1', world_model_res['given'][0, 1] / 4.)",
"tf.assign_add(self.global_step, 1) um_increment = tf.assign_add(self.um.step, 1) self.targets.update({'global_increment' : global_increment, 'um_increment' : um_increment}) self.targets.update(self.wm.readouts)",
"shape = (N,), dtype = dt), 'depths1' : hdf5.require_dataset('depths1', shape = (N, height,",
": idx, 'action_sample' : action, 'estimated_world_loss' : estimated_world_loss, 'action_samples' : action_samples, 'depths1' :",
"= { self.world_model.states : batch[state_desc], self.world_model.action : batch['action'][:, -self.world_action_time : ] } world_model_res",
"k in ['action', 'action_post', 'depths1']: batch[k] = np.concatenate(batch[k], axis=0) state_desc = 'depths1' #depths,",
"rl_opt = get_optimizer(learning_rate, self.rl_loss, ) def replace_the_nones(my_list): ''' Assumes my_list[-1] is np array",
"{ self.wm.states : batch[state_desc], self.wm.action : batch['action'], self.wm.action_post : batch['action_post'] } self.targets['global_step'] =",
"__init__(world_model, rl_model, data_provider, eta): self.data_provider = data_provider self.world_model = world_model self.rl_model = rl_model",
"objects, actions, action_ids, next_depth = postprocess_batch_for_actionmap(batch) wm_feed_dict = { self.world_model.s_i : depths, self.world_model.s_f",
"tf.int32, initializer = tf.constant_initializer(0,dtype = tf.int32)) self.action = tf.placeholder = tf.placeholder(tf.float32, [None] +",
"res['batch'] = {} for desc, val in batch.iteritems(): print(desc) if desc == 'obj_there':",
"self.targets.update(self.um.readouts) assert set(self.wm.readouts.keys()) != set(self.um.readouts.keys()) def update(self, sess, visualize = False): if self.um.just_random:",
"= False): batch = self.dp.dequeue_batch() state_desc = self.state_desc feed_dict = { self.wm.states :",
"= None): self.big_save_keys = big_save_keys self.little_save_keys = little_save_keys self.big_save_len = big_save_len self.big_save_freq =",
"{} #if self.map_draw_mode == 'specified_indices': # map_draw_res = [] # for idx in",
"feed_dict = { self.wm.states : batch[self.state_desc], self.wm.action : batch['action'], self.wm.action_post : batch['action_post'] }",
"self.global_step, optimizer_params['world_model']) self.world_model_targets = {'given' : self.world_model.processed_input, 'loss' : self.world_model.loss, 'loss_per_example' : self.world_model.loss_per_example,",
"it for online res['recent'] = {} #if self.map_draw_mode == 'specified_indices': # map_draw_res =",
"tf.get_variable('ext_uncertainty_step', [], tf.int32, initializer = tf.constant_initializer(0,dtype = tf.int32)) self.targets = {} self.state_desc =",
"= [] for provider_recent in batch['recent']: looking_at_obj = [1 if msg is not",
"action_sampler) #self.map_draw_example_indices = updater_params['map_draw_example_indices'] #self.map_draw_timestep_indices = updater_params['map_draw_timestep_indices'] #self.map_draw_freq = updater_params['map_draw_freq'] def update(self, sess,",
"= False): batch = self.data_provider.dequeue_batch() state_desc = self.um.state_descriptor wm_feed_dict = { self.world_model.states :",
"drawing. Meant to have options, but for now just assuming one sort of",
"#assert self.map_draw_mode == 'specified_indices' and self.action_sampler is not None, (self.map_draw_mode, action_sampler) #self.map_draw_example_indices =",
"est_losses, 'action_sample' : action_sample} res['msg'] = batch['recent']['msg'] else: print('little time') save_keys = self.little_save_keys",
"(k, v) in training_results.iteritems() if k in save_keys)) #res['msg'] = batch['msg'][-1] entropies =",
": self.wm.act_loss, 'um_loss' : self.um.uncertainty_loss, 'estimated_world_loss' : self.um.estimated_world_loss, 'loss_per_example' : self.um.true_loss, 'act_loss_per_example' :",
"= [1 if msg is not None and msg['msg']['action_type']['OBJ_ACT'] else 0 for msg",
"} if self.obj_there_supervision: batch['obj_there'] = np.concatenate(batch['obj_there'], axis = 0) feed_dict[self.wm.obj_there_via_msg] = batch['obj_there'] print('state",
"self.data_provider = data_provider self.world_model = world_model self.rl_model = rl_model self.eta = eta self.global_step",
"um_feed_dict = { self.um.s_i : batch[state_desc][:, :-1], self.um.action_sample : batch['action'][:, -1], self.um.true_loss :",
"= batch['recent'] class ObjectThereValidater: def __init__(self, models, data_provider): self.um = models['uncertainty_model'] self.wm =",
"cv2.imshow('pred', world_model_res['prediction'][0] / 4.)#TODO clean up w colors cv2.imshow('tv', world_model_res['tv'][0] / 4.) cv2.imshow('processed0',",
"map_draw_res return res class ObjectThereUpdater: def __init__(self, world_model, uncertainty_model, data_provider, optimizer_params, learning_rate_params, postprocessor,",
": self.global_step, 'loss_per_example' : self.um.true_loss}) self.map_draw_mode = None #Map drawing. Meant to have",
"learning_rate_params, postprocessor, updater_params): self.data_provider = data_provider\\ if isinstance(data_provider, list) else [data_provider] self.wm =",
"else timepoint for timepoint in batch.next_state['action']]]) # print('actions shape') # print(actions.shape) # print(len(batch.next_state['action']))",
"state_desc = self.state_desc feed_dict = { self.wm.states : batch[state_desc], self.wm.action : batch['action'], self.wm.obj_there",
"self.world_model.processed_input, 'loss' : self.world_model.loss, 'learning_rate' : wm_learning_rate, 'optimizer' : wm_opt, 'prediction' : self.world_model.pred,",
"+ bs for k in ['depths1', 'objects1', 'images1', 'action', 'action_post']: tosave = batch['recent'][k]",
"'act_pred' : self.wm.act_pred, 'fut_loss' : self.wm.fut_loss, 'act_loss' : self.wm.act_loss, 'um_loss' : self.um.uncertainty_loss, 'estimated_world_loss'",
"tf.get_variable('global_step', [], tf.int32, initializer = tf.constant_initializer(0, dtype = tf.int32)) print(learning_rate_params.keys()) um_lr_params, um_lr =",
"res = sess.run(self.targets, feed_dict = feed_dict) res['batch'] = batch return res class ActionUncertaintyValidatorWithReadouts:",
"is not None and msg['msg']['action_type'] == 'OBJ_ACT' else 0 for msg in batch['recent']['msg']]",
": batch[state_desc], self.wm.action : batch['action'], self.wm.obj_there : batch['obj_there'] } res = sess.run(self.targets, feed_dict",
"self.world_model.tv} self.inc_step = self.global_step.assign_add(1) self.um_lr_params, um_learning_rate = get_learning_rate(self.global_step, **learning_rate_params['uncertainty_model']) self.um_lr_params, um_opt = get_optimizer(um_learning_rate,",
"feed_dict = feed_dict) res = self.postprocessor.postprocess(res, batch) return res class SquareForceMagUpdater: def __init__(self,",
"'um_optimizer' : um_opt, # 'global_step' : self.global_step, 'loss_per_example' : self.um.true_loss}) self.map_draw_mode = None",
"'fut_pred' : self.wm.fut_pred, 'act_pred' : self.wm.act_pred, 'act_optimizer' : act_opt, 'fut_optimizer' : fut_opt, 'act_lr'",
"return res class UncertaintyUpdater: def __init__(self, world_model, uncertainty_model, data_provider, optimizer_params, learning_rate_params, postprocessor): self.data_provider",
"print(actions.shape) # print(len(batch.next_state['action'])) # action_ids_list = [] # for i in range(2): #",
"res.update(dict(pair for pair in training_results.iteritems() if pair[0] in save_keys)) #if 'other' in batch['recent']:",
"= updater_params['state_desc'] #checking that we don't have repeat names def start(self, sess): self.data_provider.start_runner(sess)",
"msg in batch['recent']['msg']] res['obj_freq'] = np.mean(looking_at_obj) elif type(batch['recent']) == list and len(batch['recent'][0]) >",
"msg is not None and msg['msg']['action_type'] == 'OBJ_ACT' else 0 for msg in",
"self.um.estimated_world_loss, 'ans' : self.um.ans, 'oh_my_god' : self.um.oh_my_god, 'model_parameters' : self.um.var_list} def update(self, sess):",
"self.global_step = tf.get_variable('global_step', [], tf.int32, initializer = tf.constant_initializer(0,dtype = tf.int32)) self.act_lr_params, act_lr =",
"res['obj_freq'] = np.mean(looking_at_obj) elif type(batch['recent']) == list and len(batch['recent'][0]) > 0: mean_per_provider =",
"tf.int32, initializer = tf.constant_initializer(0,dtype = tf.int32)) self.act_lr_params, act_lr = get_learning_rate(self.global_step, ** learning_rate_params['world_model']['act_model']) self.um_lr_params,",
"'depths1' #depths, actions, actions_post, next_depth = postprocess_batch_depth(batch, state_desc) feed_dict = { self.wm.states :",
"[other[2] for other in batch['other']] res['batch'] = {} for desc, val in batch.iteritems():",
"= { self.wm.states : batch[self.state_desc], self.wm.action : batch['action'], self.wm.action_post : batch['action_post'] } self.targets['global_step']",
"feed_dict[self.um.obj_there] = batch['obj_there'] res = sess.run(self.targets, feed_dict = feed_dict) res = self.postprocessor.postprocess(res, batch)",
"models, data_provider, optimizer_params, learning_rate_params, postprocessor, updater_params, action_sampler = None): self.data_provider = data_provider \\",
"updater_params['map_draw_freq'] def update(self, sess, visualize = False): batch = {} for i, dp",
"list) else [data_provider] self.wm = models['world_model'] self.um = models['uncertainty_model'] self.postprocessor = postprocessor self.global_step",
"= np.array([[timepoint if timepoint is not None else np.zeros(obs[desc][-1].shape, dtype = obs[desc][-1].dtype) for",
"um_lr = get_learning_rate(self.global_step, ** learning_rate_params['uncertainty_model']) act_opt_params, act_opt = get_optimizer(act_lr, self.wm.act_loss, self.global_step, optimizer_params['world_model']['act_model'], var_list",
"act_lr = get_learning_rate(self.act_step, **learning_rate_params['world_model']['act_model']) fut_lr_params, fut_lr = get_learning_rate(self.fut_step, **learning_rate_params['world_model']['fut_model']) act_opt_params, act_opt = get_optimizer(act_lr,",
": batch['obj_there'] } res = sess.run(self.targets, feed_dict = feed_dict) res['batch'] = {} for",
"we can put parallelization. Not finished! ''' def __init__(world_model, rl_model, data_provider, eta): self.data_provider",
"batch['obj_there'] res = sess.run(self.targets, feed_dict = feed_dict) res = self.postprocessor.postprocess(res, batch) return res",
"just assuming one sort of specification #self.state_desc = updater_params.get('state_desc', 'depths1') #self.map_draw_mode = updater_params['map_draw_mode']",
"is not None else [] # if len(action_msg): # idx = int(action_msg[0]['id']) #",
"= self.global_step / 3 self.targets = {'encoding_i' : self.wm.encoding_i, 'encoding_f' : self.wm.encoding_f, 'fut_pred'",
"= {} #if self.map_draw_mode == 'specified_indices': # map_draw_res = [] # for idx",
"actions, self.world_model.action_id : action_ids, self.world_model.objects : objects } world_model_res = sess.run(self.world_model_targets, feed_dict =",
"for k in provider_batch: if k in batch: batch[k].append(provider_batch[k]) else: batch[k] = [provider_batch[k]]",
"= sess.run(self.targets, feed_dict = feed_dict) res = self.postprocessor.postprocess(res, batch) return res class UncertaintyUpdater:",
"Assumes my_list[-1] is np array ''' return [np.zeros(my_list[-1].shape, dtype = my_list[-1].dtype) if elt",
"batch['obj_there'] } return sess.run(self.targets, feed_dict = feed_dict) class ActionUncertaintyValidator: def __init__(self, models, data_provider):",
"'um_loss' : self.um.uncertainty_loss, 'loss_per_example' : self.um.true_loss, 'global_step' : self.global_step} def update(self, sess, visualize",
"= sess.run(self.world_model_targets, feed_dict = wm_feed_dict) if visualize: cv2.imshow('pred', world_model_res['prediction'][0] / 4.)#TODO clean up",
"have repeat names def start(self, sess): self.data_provider.start_runner(sess) sess.run(tf.global_variables_initializer()) def update(self, sess, visualize =",
"postprocessor self.global_step = tf.get_variable('global_step', [], tf.int32, initializer = tf.constant_initializer(0,dtype = tf.int32)) self.um_lr_params, um_lr",
"= map_draw_res return res class ObjectThereUpdater: def __init__(self, world_model, uncertainty_model, data_provider, optimizer_params, learning_rate_params,",
"next_depth, self.world_model.action : actions, self.world_model.action_id : action_ids, self.world_model.objects : objects } world_model_res =",
"batch: batch[k].append(provider_batch[k]) else: batch[k] = [provider_batch[k]] for k in ['action', 'action_post', self.state_desc]: batch[k]",
"res['map_draw'] = map_draw_res res = self.postprocessor.postprocess(res, batch) return res, global_step class FreezeUpdater: def",
"other in batch['other']] #action_sample = [other[2] for other in batch['other']] res['batch'] = {}",
"\\ if isinstance(data_provider, list) else [data_provider] self.wm = models['world_model'] self.um = models['uncertainty_model'] self.postprocessor",
"self.wm_lr_params, um_learning_rate = get_learning_rate(self.global_step, **learning_rate_params['uncertainty_model']) self.wm_lr_params, um_opt = get_optimizer(um_learning_rate, self.um.uncertainty_loss, self.global_step, optimizer_params['uncertainty_model']) self.um_targets",
"[np.zeros(my_list[-1].shape, dtype = my_list[-1].dtype) if elt is None else elt for elt in",
"= replace_the_nones(obs[state_desc]) depths_past = np.array([depths[:-1]]) depths_fut = np.array([depths[:1]]) objects = np.array([replace_the_nones(obs[state_desc])[:-1]]) actions =",
"batch['action_post'][idx]} # map_draw_res.append(to_add) #res['map_draw'] = map_draw_res return res class ObjectThereUpdater: def __init__(self, world_model,",
"return prepped['depths1'], prepped['objects1'], actions, action_ids, next_depths class ExperienceReplayPostprocessor: def __init__(self, big_save_keys = None,",
"**learning_rate_params['world_model']['fut_model']) act_opt_params, act_opt = get_optimizer(act_lr, self.wm.act_loss, self.act_step, optimizer_params['world_model']['act_model'], var_list = self.wm.act_var_list + self.wm.encode_var_list)",
"models, data_provider, optimizer_params, learning_rate_params, postprocessor, updater_params): self.data_provider = data_provider\\ if isinstance(data_provider, list) else",
"freeze_wm = updater_params['freeze_wm'] freeze_um = updater_params['freeze_um'] self.postprocessor = postprocessor self.global_step = tf.get_variable('global_step', [],",
"act_opt_params, act_opt = get_optimizer(act_lr, self.wm.act_loss, self.global_step, optimizer_params['world_model']['act_model'], var_list = self.wm.act_var_list + self.wm.encode_var_list) self.targets['act_opt']",
"being just one obs type self.state_desc = data_provider.data_lengths['obs'].keys()[0] self.insert_objthere = False if data_provider.num_objthere",
"= np.uint8), 'objects1' : hdf5.require_dataset('objects1', shape = (N, height, width, 3), dtype =",
"== 'specified_indices': map_draw_res = [] for idx in self.map_draw_example_indices: obs_for_actor = [batch[self.state_desc][idx][t] for",
"None and global_step % self.map_draw_freq == 0: if self.map_draw_mode == 'specified_indices': map_draw_res =",
"dtype = np.float32), 'action_post' : hdf5.require_dataset('action_post', shape = (N, act_dim), dtype = np.float32)}",
"np.array([[timepoint if timepoint is not None else np.zeros(obs['depths1'][-1].shape, dtype = obs['depths1'][-1].dtype) for timepoint",
"k in batch: batch[k].append(provider_batch[k]) else: batch[k] = [provider_batch[k]] for k in ['action', 'action_post',",
"= um_feed_dict) wm_res_new = dict(('wm_' + k, v) for k, v in world_model_res.iteritems())",
"um_opt = get_optimizer(um_lr, self.um.uncertainty_loss, self.global_step, optimizer_params['uncertainty_model'], var_list = self.um.var_list) self.targets['um_opt'] = um_opt if",
"uncertainty_model self.global_step = tf.get_variable('global_step', [], tf.int32, initializer = tf.constant_initializer(0,dtype = tf.int32)) self.wm_lr_params, wm_learning_rate",
"= h5py.special_dtype(vlen = str) self.handles = {'msg' : hdf5.require_dataset('msg', shape = (N,), dtype",
"'global_step' : self.global_step} self.postprocessor = postprocessor self.world_action_time = self.world_model.action.get_shape().as_list()[1] def start(self, sess): self.data_provider.start_runner(sess)",
"elt in my_list] def postprocess_batch_depth(batch, state_desc): obs, msg, act, act_post = batch depths",
"batch['obj_there'] print('state desc! ' + self.state_desc) res = sess.run(self.targets, feed_dict = feed_dict) res.pop('um_increment')",
"'loss_per_example' : self.um.true_loss, 'estimated_world_loss' : self.um.estimated_world_loss } if self.um.exactly_whats_needed: self.targets['oh_my_god'] = self.um.oh_my_god self.state_desc",
"and len(batch['recent'][0]) > 0: mean_per_provider = [] for provider_recent in batch['recent']: looking_at_obj =",
"batch['action'][idx], 'action_post' : batch['action_post'][idx]} map_draw_res.append(to_add) res['map_draw'] = map_draw_res res = self.postprocessor.postprocess(res, batch) return",
": self.wm.act_pred, 'act_loss' : self.wm.act_loss, 'act_optimizer' : act_opt, 'um_optimizer' : um_opt, 'estimated_world_loss' :",
"= val[:, -1] res['recent'] = batch['recent'] class ObjectThereValidater: def __init__(self, models, data_provider): self.um",
"class DataWriteUpdater: def __init__(self, data_provider, updater_params): self.data_provider = data_provider fn = updater_params['hdf5_filename'] N",
"in training_results.iteritems() if k in save_keys)) #res['msg'] = batch['msg'][-1] entropies = [other[0] for",
"self.little_save_keys res.update(dict(pair for pair in training_results.iteritems() if pair[0] in save_keys)) #if 'other' in",
"obs_fut = np.array([depths[1:]]) actions = np.array([replace_the_nones(act)]) actions_post = np.array([replace_the_nones(act_post)]) return obs_past, actions, actions_post,",
"self.wm.fut_var_list) self.targets['act_opt'] = act_opt self.targets['fut_opt'] = fut_opt self.targets['act_lr'] = act_lr self.targets['fut_lr'] = fut_lr",
"class LatentUncertaintyValidator: def __init__(self, models, data_provider): self.um = models['uncertainty_model'] self.wm = models['world_model'] self.targets",
"tf.placeholder(tf.float32, [None] + world_model.action_one_hot.get_shape().as_list()[1:]) self.adv = tf.placeholder(tf.float32, [None]) self.r = tf.placeholder(tf.float32, [None]) log_prob_tf",
"self.big_save_keys.extend(['act_lr', 'um_lr']) self.little_save_keys.extend(['act_lr', 'um_lr']) def postprocess(self, training_results, batch): global_step = training_results['global_step'] res =",
"self.targets = {} self.state_desc = updater_params.get('state_desc', 'depths1') if not freeze_wm: act_lr_params, act_lr =",
"N = updater_params['N_save'] height, width = updater_params['image_shape'] act_dim = updater_params['act_dim'] print('setting up save",
"= { self.wm.states : batch[self.state_desc], self.wm.action : batch['action'], self.wm.action_post : batch['action_post'] } if",
"'objects1', 'images1', 'action', 'action_post']: tosave = batch['recent'][k] if k in ['action', 'action_post']: tosave",
"self.wm.fut_pred, 'act_pred' : self.wm.act_pred, 'act_optimizer' : act_opt, 'fut_optimizer' : fut_opt, 'act_lr' : act_lr,",
"= get_optimizer(um_lr, self.um.uncertainty_loss, self.global_step, optimizer_params['uncertainty_model'], var_list = self.um.var_list) self.targets['um_opt'] = um_opt if num_not_frozen",
"res['map_draw'] = map_draw_res res = self.postprocessor.postprocess(res, batch) return res, global_step class JustUncertaintyUpdater: def",
"% self.map_draw_freq == 0: # if self.map_draw_mode == 'specified_indices': # map_draw_res = []",
"state_descriptor self.big_save_keys.append('map_draw') self.little_save_keys.append('map_draw') self.big_save_keys.extend(['act_lr', 'um_lr']) self.little_save_keys.extend(['act_lr', 'um_lr']) def postprocess(self, training_results, batch): global_step =",
"self.data_provider.dequeue_batch() state_desc = self.state_desc #depths, actions, actions_post, next_depth = postprocess_batch_depth(batch, state_desc) feed_dict =",
"self.targets.update(self.wm.readouts) self.targets.update(self.um.readouts) #self.targets = { # 'fut_pred' : self.wm.fut_pred, 'act_pred' : self.wm.act_pred, #",
"self.global_step global_increment = tf.assign_add(self.global_step, 1) um_increment = tf.assign_add(self.um.step, 1) self.targets.update({'global_increment' : global_increment, 'um_increment'",
"= big_save_freq self.state_descriptor = state_descriptor def postprocess(self, training_results, batch): global_step = training_results['global_step'] res",
"'estimated_world_loss' : estimated_world_loss, 'action_samples' : action_samples, 'depths1' : batch[self.state_desc][idx], 'action' : batch['action'][idx], 'action_post'",
"action_ids = np.array([action_ids_list]) # next_depths = np.array([batch.next_state['depths1']]) # return prepped['depths1'], prepped['objects1'], actions, action_ids,",
"desc not in ['recent', 'depths1', 'objects1', 'images1']: res['batch'][desc] = val res['recent'] = batch['recent']",
"'act_lr' : act_lr, 'fut_lr' : fut_lr, 'fut_loss' : self.wm.fut_loss, 'act_loss' : self.wm.act_loss, 'estimated_world_loss'",
"fut_lr if not freeze_um: um_lr_params, um_lr = get_learning_rate(self.um_step, **learning_rate_params['uncertainty_model']) um_opt_params, um_opt = get_optimizer(um_lr,",
"batch['action'][:, -self.world_action_time : ] } world_model_res = sess.run(self.world_model_targets, feed_dict = wm_feed_dict) um_feed_dict =",
": batch['action'], self.wm.action_post : batch['action_post'] } self.targets['global_step'] = self.global_step res = sess.run(self.targets, feed_dict",
": um_opt, 'global_step' : self.global_step} self.postprocessor = postprocessor self.world_action_time = self.world_model.action.get_shape().as_list()[1] def start(self,",
"# idx = int(action_msg[0]['id']) # action_ids_list.append(idx) # action_ids = np.array([action_ids_list]) # next_depths =",
"feed_dict) class ActionUncertaintyValidator: def __init__(self, models, data_provider): self.um = um = models['uncertainty_model'] self.wm",
"= -tf.reduce_sum(prob_tf * log_prob_tf) self.rl_loss = pi_loss + 0.5 * vf_loss - entropy",
"hdf5.require_dataset('depths1', shape = (N, height, width, 3), dtype = np.uint8), 'objects1' : hdf5.require_dataset('objects1',",
"mean_per_provider = [] for provider_recent in batch['recent']: looking_at_obj = [1 if msg is",
"batch['action'], self.wm.action_post : batch['action_post'], self.um.obj_there : batch['obj_there'] } res = sess.run(self.targets, feed_dict =",
"models['uncertainty_model'] freeze_wm = updater_params['freeze_wm'] freeze_um = updater_params['freeze_um'] self.postprocessor = postprocessor self.global_step = tf.get_variable('global_step',",
"** learning_rate_params['uncertainty_model']) act_opt_params, act_opt = get_optimizer(act_lr, self.wm.act_loss, self.global_step, optimizer_params['world_model']['act_model'], var_list = self.wm.act_var_list +",
"= tf.constant_initializer(0,dtype = tf.int32)) self.action = tf.placeholder = tf.placeholder(tf.float32, [None] + world_model.action_one_hot.get_shape().as_list()[1:]) self.adv",
"= {'um_loss' : self.um.uncertainty_loss, 'um_optimizer' : um_opt, 'global_step' : self.global_step, 'loss_per_example' : self.um.true_loss,",
"#self.action_sampler = action_sampler #assert self.map_draw_mode == 'specified_indices' and self.action_sampler is not None, (self.map_draw_mode,",
"batch example indices for which we do a forward pass. #need to do",
"= self.um.var_list) self.targets = {'global_step' : self.global_step, 'um_optimizer' : um_opt} assert set(self.wm.readouts.keys()) !=",
"self.targets['increment'] = tf.assign_add(self.global_step, 1) else: self.global_step = self.global_step / num_not_frozen self.targets['global_step'] = self.global_step",
"feed_dict = { self.wm.states : batch['depths1'], self.wm.action : batch['action'], self.wm.action_post : batch['action_post'], self.wm.obj_there",
"um_feed_dict = { self.um.s_i : depths, self.um.action_sample : actions[:, -1], self.um.true_loss : np.array([world_model_res['loss']])",
"tf.get_variable('global_step', [], tf.int32, initializer = tf.constant_initializer(0,dtype = tf.int32)) self.action = tf.placeholder = tf.placeholder(tf.float32,",
"wm_feed_dict = { self.world_model.s_i : depths, self.world_model.s_f : next_depth, self.world_model.action : actions, self.world_model.action_id",
"models import h5py import json class RawDepthDiscreteActionUpdater: ''' Provides the training step. This",
"res['batch'] = batch return res class ActionUncertaintyValidatorWithReadouts: def __init__(self, model, data_provider): self.dp =",
"Not finished! ''' def __init__(world_model, rl_model, data_provider, eta): self.data_provider = data_provider self.world_model =",
"sess.run(tf.global_variables_initializer()) def update(self, sess, visualize = False): batch = self.data_provider.dequeue_batch() state_desc = self.state_desc",
"= state_descriptor self.big_save_keys.append('map_draw') self.little_save_keys.append('map_draw') self.big_save_keys.extend(['act_lr', 'um_lr']) self.little_save_keys.extend(['act_lr', 'um_lr']) def postprocess(self, training_results, batch): global_step",
"else elt for elt in my_list] def postprocess_batch_depth(batch, state_desc): obs, msg, act, act_post",
"= batch depths = replace_the_nones(obs[state_desc]) obs_past = np.array([depths[:-1]]) obs_fut = np.array([depths[1:]]) actions =",
"= int(action_msg[0]['id']) # action_ids_list.append(idx) # action_ids = np.array([action_ids_list]) # next_depths = np.array([batch.next_state['depths1']]) #",
"postprocess_batch_depth(batch, state_desc): obs, msg, act, act_post = batch depths = replace_the_nones(obs[state_desc]) obs_past =",
"self.dp.dequeue_batch() feed_dict = { self.wm.states : batch['depths1'], self.wm.action : batch['action'], self.wm.action_post : batch['action_post']",
"None and msg['msg']['action_type']['OBJ_ACT'] else 0 for msg in batch['recent']['msg']] res['obj_freq'] = np.mean(looking_at_obj) return",
"online res['recent'] = {} #if self.map_draw_mode == 'specified_indices': # map_draw_res = [] #",
"{} for desc, val in batch.iteritems(): print(desc) if desc == 'obj_there': res['batch'][desc] =",
"= msg[i]['msg']['actions'] if msg[i] is not None else [] if len(action_msg): idx =",
"entropies looking_at_obj = [1 if msg is not None and msg['msg']['action_type']['OBJ_ACT'] else 0",
"tf.int32, initializer = tf.constant_initializer(0,dtype = tf.int32)) self.wm_lr_params, wm_learning_rate = get_learning_rate(self.global_step, ** learning_rate_params['world_model']) self.wm_opt_params,",
"k, v in world_model_res.iteritems()) um_res_new = dict(('um_' + k, v) for k, v",
"self.um.uncertainty_loss, self.global_step, optimizer_params['uncertainty_model'], var_list = self.um.var_list) self.targets = {'um_loss' : self.um.uncertainty_loss, 'um_lr' :",
"obs_for_actor) to_add = {'example_id' : idx, 'action_sample' : action, 'estimated_world_loss' : estimated_world_loss, 'action_samples'",
"training_results['global_step'] res = {} print('postprocessor deets') print(global_step) print(self.big_save_freq) print(self.big_save_len) if (global_step) % self.big_save_freq",
": hdf5.require_dataset('action', shape = (N, act_dim), dtype = np.float32), 'action_post' : hdf5.require_dataset('action_post', shape",
": um_lr, 'um_optimizer' : um_opt, 'global_step' : self.global_step, 'loss_per_example' : self.um.true_loss}) self.state_desc =",
"if self.um.exactly_whats_needed: self.targets['oh_my_god'] = self.um.oh_my_god self.state_desc = updater_params['state_desc'] def update(self, sess, visualize =",
"else [] # if len(action_msg): # idx = int(action_msg[0]['id']) # action_ids_list.append(idx) # action_ids",
"batch['action'], self.wm.action_post : batch['action_post'], self.wm.obj_there : batch['obj_there'] } res = sess.run(self.targets, feed_dict =",
"res = self.postprocessor.postprocess(res, batch) return res class UncertaintyUpdater: def __init__(self, world_model, uncertainty_model, data_provider,",
"actions_post = np.array([replace_the_nones(act_post)]) return obs_past, actions, actions_post, obs_fut # def postprocess_batch_depth(batch): # depths",
"postprocessor, updater_params): self.data_provider = data_provider\\ if isinstance(data_provider, list) else [data_provider] self.wm = models['world_model']",
"self.global_step} def update(self, sess, visualize = False): batch = {} for i, dp",
"shape = (N, height, width, 3), dtype = np.uint8), 'action' : hdf5.require_dataset('action', shape",
"batch[state_desc], self.wm.action : batch['action'], self.wm.action_post : batch['action_post'] } self.targets['global_step'] = self.global_step res =",
"= models['uncertainty_model'] self.postprocessor = postprocessor self.global_step = tf.get_variable('global_step', [], tf.int32, initializer = tf.constant_initializer(0,dtype",
"!= set(self.um.readouts.keys()) self.targets.update(self.wm.readouts) self.targets.update(self.um.readouts) #self.targets = { # 'fut_pred' : self.wm.fut_pred, 'act_pred' :",
"= feed_dict) res = self.postprocessor.postprocess(res, batch) return res class UncertaintyUpdater: def __init__(self, world_model,",
"if isinstance(data_provider, list) else [data_provider] self.wm = models['world_model'] self.um = models['uncertainty_model'] freeze_wm =",
"little_save_keys self.big_save_len = big_save_len self.big_save_freq = big_save_freq self.state_descriptor = state_descriptor def postprocess(self, training_results,",
"as np import cv2 from curiosity.interaction import models import h5py import json class",
"= self.big_save_keys est_losses = [other[1] for other in batch['recent']['other']] action_sample = [other[2] for",
"in save_keys)) #res['msg'] = batch['msg'][-1] entropies = [other[0] for other in batch['recent']['other']] entropies",
"self.start = 0 def update(self): batch = self.data_provider.dequeue_batch() bs = len(batch['recent']['msg']) end =",
"class UncertaintyUpdater: def __init__(self, world_model, uncertainty_model, data_provider, optimizer_params, learning_rate_params, postprocessor): self.data_provider = data_provider",
"self.um.insert_obj_there: print('adding obj_there to feed dict') feed_dict[self.um.obj_there] = batch['obj_there'] res = sess.run(self.targets, feed_dict",
"= postprocessor self.world_action_time = self.world_model.action.get_shape().as_list()[1] def start(self, sess): self.data_provider.start_runner(sess) sess.run(tf.global_variables_initializer()) def update(self, sess,",
"self.wm.act_loss, 'estimated_world_loss' : self.um.estimated_world_loss } self.targets.update({'um_loss' : self.um.uncertainty_loss, 'um_lr' : um_lr, 'um_optimizer' :",
"= tf.get_variable('global_step', [], tf.int32, initializer = tf.constant_initializer(0,dtype = tf.int32)) self.um_lr_params, um_lr = get_learning_rate(self.global_step,",
"else 0 for msg in batch['recent']['msg']] res['obj_freq'] = np.mean(looking_at_obj) elif type(batch['recent']) == list",
"self.global_step self.targets['increment'] = tf.assign_add(self.global_step, 1) else: self.global_step = self.global_step / num_not_frozen self.targets['global_step'] =",
"= tf.constant_initializer(0,dtype = tf.int32)) self.act_lr_params, act_lr = get_learning_rate(self.global_step, ** learning_rate_params['world_model']['act_model']) self.um_lr_params, um_lr =",
"big_save_len self.big_save_freq = big_save_freq self.state_descriptor = state_descriptor self.big_save_keys.append('map_draw') self.little_save_keys.append('map_draw') self.big_save_keys.extend(['act_lr', 'um_lr']) self.little_save_keys.extend(['act_lr', 'um_lr'])",
": batch['action_post'] } res = sess.run(self.targets, feed_dict = feed_dict) res.pop('um_increment') res.pop('global_increment') global_step =",
"data_provider, optimizer_params, learning_rate_params, postprocessor, updater_params = None): self.data_provider = data_provider self.wm = world_model",
"} return sess.run(self.targets, feed_dict = feed_dict) class ActionUncertaintyValidator: def __init__(self, models, data_provider): self.um",
"#this should be changed for an online data provider, set to do nothing",
"# map_draw_res.append(to_add) #res['map_draw'] = map_draw_res return res class ObjectThereUpdater: def __init__(self, world_model, uncertainty_model,",
"colors cv2.imshow('tv', world_model_res['tv'][0] / 4.) cv2.imshow('processed0', world_model_res['given'][0, 0] / 4.) cv2.imshow('processed1', world_model_res['given'][0, 1]",
"updater_params['state_desc'] def update(self, sess, visualize = False): batch = self.data_provider.dequeue_batch() state_desc = self.state_desc",
"batch['action'], self.wm.obj_there : batch['obj_there'] } return sess.run(self.targets, feed_dict = feed_dict) class ActionUncertaintyValidator: def",
"{'act_pred' : self.wm.act_pred, 'act_loss' : self.wm.act_loss, 'estimated_world_loss' : self.um.estimated_world_loss, 'um_loss' : self.um.uncertainty_loss, 'loss_per_example'",
"+ world_model.action_one_hot.get_shape().as_list()[1:]) self.adv = tf.placeholder(tf.float32, [None]) self.r = tf.placeholder(tf.float32, [None]) log_prob_tf = tf.nn.log_softmax(rl_model.logits)",
"self.postprocessor = postprocessor self.global_step = tf.get_variable('global_step', [], tf.int32, initializer = tf.constant_initializer(0,dtype = tf.int32))",
"self.data_provider.dequeue_batch() state_desc = self.state_desc feed_dict = { self.wm.states : batch[state_desc], self.wm.action : batch['action'],",
"the training step. ''' import sys sys.path.append('tfutils') import tensorflow as tf from tfutils.base",
"None else True def run(self, sess): batch = self.dp.dequeue_batch() feed_dict = { self.wm.states",
"class DebuggingForceMagUpdater: def __init__(self, models, data_provider, optimizer_params, learning_rate_params, postprocessor, updater_params): self.dp = data_provider",
": self.wm.act_pred, 'fut_loss' : self.wm.fut_loss, 'act_loss' : self.wm.act_loss, 'um_loss' : self.um.uncertainty_loss, 'estimated_world_loss' :",
"print(self.big_save_freq) print(self.big_save_len) if (global_step) % self.big_save_freq < self.big_save_len: print('big time') save_keys = self.big_save_keys",
"else: batch[k] = [provider_batch[k]] for k in ['action', 'action_post', self.state_desc]: batch[k] = np.concatenate(batch[k],",
"= [batch[self.state_desc][idx][t] for t in self.map_draw_timestep_indices] action_samples = self.action_sampler.sample_actions() action, entropy, estimated_world_loss =",
"self.global_step / 2 self.um_targets = {'loss' : self.um.uncertainty_loss, 'learning_rate' : um_learning_rate, 'optimizer' :",
"visualize = False): batch = self.data_provider.dequeue_batch() state_desc = self.um.state_descriptor wm_feed_dict = { self.world_model.states",
"= { self.um.s_i : depths, self.um.action_sample : actions[:, -1], self.um.true_loss : np.array([world_model_res['loss']]) }",
"self.wm.encode_var_list) self.targets['act_opt'] = act_opt if not freeze_um: num_not_frozen += 1 um_opt_params, um_opt =",
"batch[self.state_desc][idx], # 'action' : batch['action'][idx], 'action_post' : batch['action_post'][idx]} # map_draw_res.append(to_add) #res['map_draw'] = map_draw_res",
"= sess.run(self.targets, feed_dict = feed_dict) res['batch'] = batch return res class ActionUncertaintyValidatorWithReadouts: def",
"[batch[self.state_desc][idx][t] for t in self.map_draw_timestep_indices] # action_samples = self.action_sampler.sample_actions() # action, entropy, estimated_world_loss",
"updater_params['N_save'] height, width = updater_params['image_shape'] act_dim = updater_params['act_dim'] print('setting up save loc') self.hdf5",
"for now just assuming one sort of specification self.state_desc = updater_params.get('state_desc', 'depths1') self.map_draw_mode",
"None): self.big_save_keys = big_save_keys self.little_save_keys = little_save_keys self.big_save_len = big_save_len self.big_save_freq = big_save_freq",
"tf.get_variable('fut_step', [], tf.int32, initializer = tf.constant_initializer(0,dtype = tf.int32)) self.um_step = tf.get_variable('ext_uncertainty_step', [], tf.int32,",
"= wm_feed_dict) um_feed_dict = { self.um.s_i : batch[state_desc][:, :-1], self.um.action_sample : batch['action'][:, -1],",
"self.wm.action_post : batch ['action_post'] } if self.insert_objthere: feed_dict[self.wm.obj_there_via_msg] = batch['obj_there'] res = sess.run(self.targets,",
"models['uncertainty_model'] self.postprocessor = postprocessor self.global_step = tf.get_variable('global_step', [], tf.int32, initializer = tf.constant_initializer(0,dtype =",
"data_provider \\ if isinstance(data_provider, list) else [data_provider] self.wm = models['world_model'] self.um = models['uncertainty_model']",
"class ObjectThereValidater: def __init__(self, models, data_provider): self.um = models['uncertainty_model'] self.wm = models['world_model'] self.targets",
"self.wm.states : batch[state_desc], self.wm.action : batch['action'], self.wm.action_post : batch['action_post'] } if self.um.insert_obj_there: print('adding",
"= get_optimizer(act_lr, self.wm.act_loss, self.global_step, optimizer_params['world_model']['act_model'], var_list = self.wm.act_var_list + self.wm.encode_var_list) self.targets['act_opt'] = act_opt",
"k, v in self.um.readouts.items() if k not in self.um.save_to_gfs}) #this should be changed",
"== 'OBJ_ACT' else 0 for msg in batch['recent']['msg']] res['obj_freq'] = np.mean(looking_at_obj) elif type(batch['recent'])",
"tf.constant_initializer(0,dtype = tf.int32)) self.act_step = tf.get_variable('act_step', [], tf.int32, initializer = tf.constant_initializer(0,dtype = tf.int32))",
"== 'specified_indices' and self.action_sampler is not None, (self.map_draw_mode, action_sampler) self.map_draw_example_indices = updater_params['map_draw_example_indices'] self.map_draw_timestep_indices",
"sess.run(self.targets, feed_dict = feed_dict) glstep = res['global_step'] res = self.postprocessor.postprocess(res, batch) return res,",
"np.array([batch.next_state['depths1']]) # return prepped['depths1'], prepped['objects1'], actions, action_ids, next_depths class ExperienceReplayPostprocessor: def __init__(self, big_save_keys",
"None and msg['msg']['action_type'] == 'OBJ_ACT' else 0 for msg in provider_recent['msg']] mean_per_provider.append(np.mean(looking_at_obj)) res['obj_freq']",
"res['batch'][desc] = val res['recent'] = batch['recent'] else: save_keys = self.little_save_keys res.update(dict(pair for pair",
"var_list = self.wm.act_var_list + self.wm.encode_var_list) self.targets['act_opt'] = act_opt if not freeze_um: num_not_frozen +=",
"val in batch.iteritems(): if desc not in ['recent', 'depths1', 'objects1', 'images1']: res['batch'][desc] =",
"= tf.constant_initializer(0,dtype = tf.int32)) self.um_lr_params, um_lr = get_learning_rate(self.global_step, ** learning_rate_params['uncertainty_model']) um_opt_params, um_opt =",
"# 'fut_loss' : self.wm.fut_loss, 'act_loss' : self.wm.act_loss, # 'estimated_world_loss' : self.um.estimated_world_loss, # ''",
"= batch['recent'][k] self.handles['msg'][self.start : end] = [json.dumps(msg) for msg in batch['recent']['msg']] self.start =",
"= self.state_desc feed_dict = { self.wm.states : batch[state_desc], self.wm.action : batch['action'], self.wm.obj_there :",
"self.map_draw_example_indices = updater_params['map_draw_example_indices'] self.map_draw_timestep_indices = updater_params['map_draw_timestep_indices'] self.map_draw_freq = updater_params['map_draw_freq'] def update(self, sess, visualize",
"wm_res_new res['global_step'] = res.pop('um_global_step') res = self.postprocessor.postprocess(wm_res_new, batch) return res class DamianWMUncertaintyUpdater: def",
"self.wm.act_loss, 'act_optimizer' : act_opt, 'um_optimizer' : um_opt, 'estimated_world_loss' : self.um.estimated_world_loss, 'um_loss' : self.um.uncertainty_loss,",
"tf.constant_initializer(0,dtype = tf.int32)) self.targets = {} self.state_desc = updater_params.get('state_desc', 'depths1') if not freeze_wm:",
"for other in batch['recent']['other']] action_sample = [other[2] for other in batch['recent']['other']] res['batch'] =",
"'estimated_world_loss' : self.um.estimated_world_loss, # '' # } #self.targets.update({'um_loss' : self.um.uncertainty_loss, 'um_lr' : um_lr,",
"self.global_step = self.global_step / 2 self.targets = {'act_pred' : self.wm.act_pred, 'act_loss' : self.wm.act_loss,",
"'action_post']: tosave = batch['recent'][k] if k in ['action', 'action_post']: tosave = tosave.astype(np.float32) self.handles[k][self.start",
"num_not_frozen == 0: self.targets['global_step'] = self.global_step self.targets['increment'] = tf.assign_add(self.global_step, 1) else: self.global_step =",
"None else np.zeros(obs['depths1'][-1].shape, dtype = obs['depths1'][-1].dtype) for timepoint in obs['depths1']] for obs in",
"assert 'um_increment' not in self.targets self.targets['um_increment'] = um_increment self.obj_there_supervision = updater_params.get('include_obj_there', False) #self.map_draw_mode",
"optimizer_params['world_model']['act_model'], var_list = self.wm.act_var_list + self.wm.encode_var_list) um_opt_params, um_opt = get_optimizer(um_lr, self.um.uncertainty_loss, self.global_step, optimizer_params['uncertainty_model'],",
"do one forward pass each index because action sampling is the 'batch.' self.action_sampler",
"state_desc = self.state_desc #depths, actions, actions_post, next_depth = postprocess_batch_depth(batch, state_desc) feed_dict = {",
": um_opt, 'global_step' : self.global_step} self.postprocessor = postprocessor def start(self, sess): self.data_provider.start_runner(sess) sess.run(tf.global_variables_initializer())",
"models, data_provider): self.um = models['uncertainty_model'] self.wm = models['world_model'] self.targets = {'um_loss' : self.um.uncertainty_loss,",
"self.um.true_loss, 'estimated_world_loss' : self.um.estimated_world_loss} self.dp = data_provider def run(self, sess): batch = self.dp.dequeue_batch()",
"def __init__(world_model, rl_model, data_provider, eta): self.data_provider = data_provider self.world_model = world_model self.rl_model =",
"= updater_params['map_draw_freq'] def update(self, sess, visualize = False): batch = {} for i,",
"batch[self.state_desc], self.wm.action : batch['action'], self.wm.action_post : batch ['action_post'] } if self.insert_objthere: feed_dict[self.wm.obj_there_via_msg] =",
": self.wm.encoding_f, 'fut_pred' : self.wm.fut_pred, 'act_pred' : self.wm.act_pred, 'act_optimizer' : act_opt, 'fut_optimizer' :",
"len(action_msg): # idx = int(action_msg[0]['id']) # action_ids_list.append(idx) # action_ids = np.array([action_ids_list]) # next_depths",
"tf.int32)) self.act_step = tf.get_variable('act_step', [], tf.int32, initializer = tf.constant_initializer(0,dtype = tf.int32)) self.fut_step =",
"batch['recent'] class ObjectThereValidater: def __init__(self, models, data_provider): self.um = models['uncertainty_model'] self.wm = models['world_model']",
"k in provider_batch: if k in batch: batch[k].append(provider_batch[k]) else: batch[k] = [provider_batch[k]] for",
"models['uncertainty_model'] self.wm = models['world_model'] self.targets = { 'act_pred' : self.wm.act_pred, 'fut_loss' : self.wm.fut_loss,",
"feed_dict) res.pop('um_increment') global_step = res['global_step'] #if self.map_draw_mode is not None and global_step %",
"[data_provider] self.wm = models['world_model'] self.um = models['uncertainty_model'] self.postprocessor = postprocessor self.global_step = tf.get_variable('global_step',",
"be changed for an online data provider, set to do nothing self.map_draw_mode =",
"** learning_rate_params['world_model']['act_model']) self.um_lr_params, um_lr = get_learning_rate(self.global_step, ** learning_rate_params['uncertainty_model']) act_opt_params, act_opt = get_optimizer(act_lr, self.wm.act_loss,",
"self.um.var_list) self.global_step = self.global_step / 2 self.targets = {'act_pred' : self.wm.act_pred, 'act_loss' :",
"self.global_step, optimizer_params['uncertainty_model'], var_list = self.um.var_list) self.global_step = self.global_step / 3 self.targets = {'encoding_i'",
"np.array([action_ids_list]) return depths_past, objects, actions, action_ids, depths_fut # def postprocess_batch_for_actionmap(batch): # prepped =",
"#self.map_draw_timestep_indices = updater_params['map_draw_timestep_indices'] #self.map_draw_freq = updater_params['map_draw_freq'] def update(self, sess, visualize = False): if",
"#res['map_draw'] = map_draw_res return res class ObjectThereUpdater: def __init__(self, world_model, uncertainty_model, data_provider, optimizer_params,",
": batch['action_post'], 'est_loss' : est_losses, 'action_sample' : action_sample} res['msg'] = batch['recent']['msg'] else: print('little",
"self.wm.fut_loss, 'act_loss' : self.wm.act_loss, # 'estimated_world_loss' : self.um.estimated_world_loss, # '' # } #self.targets.update({'um_loss'",
"initializer = tf.constant_initializer(0,dtype = tf.int32)) self.um_step = tf.get_variable('ext_uncertainty_step', [], tf.int32, initializer = tf.constant_initializer(0,dtype",
"['depths1', 'objects1']: # prepped[desc] = np.array([[timepoint if timepoint is not None else np.zeros(obs[desc][-1].shape,",
"'um_lr']) def postprocess(self, training_results, batch): global_step = training_results['global_step'] res = {} if (global_step)",
"feed_dict = feed_dict) class ActionUncertaintyValidator: def __init__(self, models, data_provider): self.um = um =",
"0: mean_per_provider = [] for provider_recent in batch['recent']: looking_at_obj = [1 if msg",
"provider_batch: if k in batch: batch[k].append(provider_batch[k]) else: batch[k] = [provider_batch[k]] for k in",
"batch['recent']['other']] action_sample = [other[2] for other in batch['recent']['other']] res['batch'] = {'obs' : batch['depths1'],",
"eta): self.data_provider = data_provider self.world_model = world_model self.rl_model = rl_model self.eta = eta",
"models['world_model'] self.um = models['uncertainty_model'] self.postprocessor = postprocessor self.global_step = tf.get_variable('global_step', [], tf.int32, initializer",
"models, data_provider, optimizer_params, learning_rate_params, postprocessor, updater_params): self.data_provider = data_provider \\ if isinstance(data_provider, list)",
"'learning_rate' : wm_learning_rate, 'optimizer' : wm_opt, 'prediction' : self.world_model.pred, 'tv' : self.world_model.tv} self.inc_step",
"#self.targets = { # 'fut_pred' : self.wm.fut_pred, 'act_pred' : self.wm.act_pred, # 'fut_loss' :",
"''' Assumes my_list[-1] is np array ''' return [np.zeros(my_list[-1].shape, dtype = my_list[-1].dtype) if",
"= res.pop('um_global_step') res = self.postprocessor.postprocess(wm_res_new, batch) return res class DamianWMUncertaintyUpdater: def __init__(self, world_model,",
"4.) cv2.imshow('processed0', world_model_res['given'][0, 0] / 4.) cv2.imshow('processed1', world_model_res['given'][0, 1] / 4.) cv2.waitKey(1) print('wm",
"up save loc') self.hdf5 = hdf5 = h5py.File(fn, mode = 'a') dt =",
"= act_lr self.targets['fut_lr'] = fut_lr if not freeze_um: um_lr_params, um_lr = get_learning_rate(self.um_step, **learning_rate_params['uncertainty_model'])",
"= tf.int32)) self.action = tf.placeholder = tf.placeholder(tf.float32, [None] + world_model.action_one_hot.get_shape().as_list()[1:]) self.adv = tf.placeholder(tf.float32,",
"self.um.uncertainty_loss, self.global_step, optimizer_params['uncertainty_model']) self.targets = {'um_loss' : self.um.uncertainty_loss, 'um_optimizer' : um_opt, 'global_step' :",
"get_learning_rate(self.um_step, **learning_rate_params['uncertainty_model']) um_opt_params, um_opt = get_optimizer(um_lr, self.um.uncertainty_loss, self.um_step, optimizer_params['uncertainty_model'], var_list = self.um.var_list) self.targets['um_opt']",
"models['world_model'] self.um = models['uncertainty_model'] freeze_wm = updater_params['freeze_wm'] freeze_um = updater_params['freeze_um'] self.postprocessor = postprocessor",
"k not in self.wm.save_to_gfs}) self.targets.update({k : v for k, v in self.um.readouts.items() if",
"= np.mean(mean_per_provider) res['obj_freq_per_provider_noprint'] = mean_per_provider return res class UncertaintyPostprocessor: def __init__(self, big_save_keys =",
"action_sampler = None): self.data_provider = data_provider \\ if isinstance(data_provider, list) else [data_provider] self.wm",
"None, state_descriptor = None): self.big_save_keys = big_save_keys self.little_save_keys = little_save_keys self.big_save_len = big_save_len",
"state_descriptor = None): self.big_save_keys = big_save_keys self.little_save_keys = little_save_keys self.big_save_len = big_save_len self.big_save_freq",
"is None else elt for elt in my_list] def postprocess_batch_depth(batch, state_desc): obs, msg,",
"self.state_descriptor = state_descriptor self.big_save_keys.append('map_draw') self.little_save_keys.append('map_draw') self.big_save_keys.extend(['act_lr', 'um_lr']) self.little_save_keys.extend(['act_lr', 'um_lr']) def postprocess(self, training_results, batch):",
"shape = (N, act_dim), dtype = np.float32)} print('save loc set up') self.start =",
"'tv' : self.world_model.tv} self.inc_step = self.global_step.assign_add(1) self.um_lr_params, um_learning_rate = get_learning_rate(self.global_step, **learning_rate_params['uncertainty_model']) self.um_lr_params, um_opt",
"None else timepoint for timepoint in batch.next_state['action']]]) # print('actions shape') # print(actions.shape) #",
"sess.run(self.targets, feed_dict = feed_dict) res['batch'] = batch return res class ActionUncertaintyValidatorWithReadouts: def __init__(self,",
"= get_learning_rate(self.act_step, **learning_rate_params['world_model']['act_model']) fut_lr_params, fut_lr = get_learning_rate(self.fut_step, **learning_rate_params['world_model']['fut_model']) act_opt_params, act_opt = get_optimizer(act_lr, self.wm.act_loss,",
"self.action_sampler is not None, (self.map_draw_mode, action_sampler) self.map_draw_example_indices = updater_params['map_draw_example_indices'] self.map_draw_timestep_indices = updater_params['map_draw_timestep_indices'] self.map_draw_freq",
"= models['uncertainty_model'] self.wm = wm = models['world_model'] self.targets = {'act_pred' : self.wm.act_pred, 'act_loss'",
"self.rl_loss = pi_loss + 0.5 * vf_loss - entropy * 0.01 rl_opt_params, rl_opt",
"self.dp = data_provider def run(self, sess): batch = self.dp.dequeue_batch() feed_dict = { self.wm.states",
"else: batch[k] = [provider_batch[k]] for k in ['action', 'action_post', 'depths1']: batch[k] = np.concatenate(batch[k],",
"= self.wm.fut_var_list) self.targets['act_opt'] = act_opt self.targets['fut_opt'] = fut_opt self.targets['act_lr'] = act_lr self.targets['fut_lr'] =",
"forward pass. #need to do one forward pass each index because action sampling",
"self.um.var_list) self.global_step = self.global_step / 3 self.targets = {'encoding_i' : self.wm.encoding_i, 'encoding_f' :",
"= self.um.oh_my_god self.state_desc = updater_params['state_desc'] def update(self, sess, visualize = False): batch =",
"self.targets['global_step'] = self.global_step res = sess.run(self.targets, feed_dict = feed_dict) glstep = res['global_step'] res",
"self.wm.states : batch[state_desc], self.wm.action : batch['action'], self.wm.action_post : batch['action_post'] } res = sess.run(self.targets,",
"self.handles = {'msg' : hdf5.require_dataset('msg', shape = (N,), dtype = dt), 'depths1' :",
": um_opt, 'global_step' : self.global_step, 'loss_per_example' : self.um.true_loss}) self.state_desc = updater_params['state_desc'] #checking that",
"-1] res['recent'] = batch['recent'] class ObjectThereValidater: def __init__(self, models, data_provider): self.um = models['uncertainty_model']",
"self.world_model = world_model self.rl_model = rl_model self.eta = eta self.global_step = tf.get_variable('global_step', [],",
"else np.zeros(obs[desc][-1].shape, dtype = obs[desc][-1].dtype) for timepoint in obs[desc]] for obs in batch.states])",
"= tf.get_variable('global_step', [], tf.int32, initializer = tf.constant_initializer(0,dtype = tf.int32)) self.act_step = tf.get_variable('act_step', [],",
"index because action sampling is the 'batch.' #self.action_sampler = action_sampler #assert self.map_draw_mode ==",
"global_step = res['global_step'] #if self.map_draw_mode is not None and global_step % self.map_draw_freq ==",
"if data_provider.num_objthere is None else True def run(self, sess): batch = self.dp.dequeue_batch() feed_dict",
"for idx in self.map_draw_example_indices: obs_for_actor = [batch[self.state_desc][idx][t] for t in self.map_draw_timestep_indices] action_samples =",
"(N, height, width, 3), dtype = np.uint8), 'objects1' : hdf5.require_dataset('objects1', shape = (N,",
"1) um_increment = tf.assign_add(self.um.step, 1) self.targets.update({'global_increment' : global_increment, 'um_increment' : um_increment}) self.targets.update(self.wm.readouts) self.targets.update(self.um.readouts)",
"index because action sampling is the 'batch.' self.action_sampler = action_sampler assert self.map_draw_mode ==",
"optimizer_params['world_model']['act_model'], var_list = self.wm.act_var_list + self.wm.encode_var_list) fut_opt_params, fut_opt = get_optimizer(fut_lr, self.wm.fut_loss, self.global_step, optimizer_params['world_model']['fut_model'],",
": action_sample} res['msg'] = batch['recent']['msg'] else: print('little time') save_keys = self.little_save_keys res.update(dict((k, v)",
"self.wm.act_pred, 'fut_loss' : self.wm.fut_loss, 'act_loss' : self.wm.act_loss, 'um_loss' : self.um.uncertainty_loss, 'estimated_world_loss' : self.um.estimated_world_loss,",
"self.um.uncertainty_loss, 'um_optimizer' : um_opt, 'global_step' : self.global_step, 'loss_per_example' : self.um.true_loss, 'estimated_world_loss' : self.um.estimated_world_loss,",
"= np.array(batch.actions) # next_depth = np.array([batch.next_state['depths1']]) # return depths, actions, next_depth def postprocess_batch_for_actionmap(batch,",
"4.) cv2.waitKey(1) print('wm loss: ' + str(world_model_res['loss'])) um_feed_dict = { self.um.s_i : depths,",
"self.targets['um_lr'] = um_lr self.targets['global_step'] = self.global_step global_increment = tf.assign_add(self.global_step, 1) um_increment = tf.assign_add(self.um.step,",
"= wm_feed_dict) if visualize: cv2.imshow('pred', world_model_res['prediction'][0] / 4.)#TODO clean up w colors cv2.imshow('tv',",
"0: self.targets['global_step'] = self.global_step self.targets['increment'] = tf.assign_add(self.global_step, 1) else: self.global_step = self.global_step /",
"self.wm = models['world_model'] self.targets = {'um_loss' : self.um.uncertainty_loss, 'loss_per_example' : self.um.true_loss, 'estimated_world_loss' :",
"self.state_desc) res = sess.run(self.targets, feed_dict = feed_dict) res.pop('um_increment') global_step = res['global_step'] #if self.map_draw_mode",
"* 0.01 rl_opt_params, rl_opt = get_optimizer(learning_rate, self.rl_loss, ) def replace_the_nones(my_list): ''' Assumes my_list[-1]",
"__init__(self, models, data_provider): self.um = models['uncertainty_model'] self.wm = models['world_model'] self.targets = { 'act_pred'",
"= batch prepped = {} depths = replace_the_nones(obs[state_desc]) depths_past = np.array([depths[:-1]]) depths_fut =",
"/ 4.) cv2.imshow('processed0', world_model_res['given'][0, 0] / 4.) cv2.imshow('processed1', world_model_res['given'][0, 1] / 4.) cv2.waitKey(1)",
"0: if self.map_draw_mode == 'specified_indices': map_draw_res = [] for idx in self.map_draw_example_indices: obs_for_actor",
"if k in save_keys)) #res['msg'] = batch['msg'][-1] entropies = [other[0] for other in",
"return res class ActionUncertaintyValidatorWithReadouts: def __init__(self, model, data_provider): self.dp = data_provider self.wm =",
"optimizer_params['uncertainty_model']) self.targets = {'um_loss' : self.um.uncertainty_loss, 'um_optimizer' : um_opt, 'global_step' : self.global_step, 'loss_per_example'",
"return [np.zeros(my_list[-1].shape, dtype = my_list[-1].dtype) if elt is None else elt for elt",
"in ['action', 'action_post']: tosave = tosave.astype(np.float32) self.handles[k][self.start : end] = batch['recent'][k] self.handles['msg'][self.start :",
"= data_provider.data_lengths['obs'].keys()[0] self.insert_objthere = False if data_provider.num_objthere is None else True def run(self,",
"num_not_frozen += 1 um_opt_params, um_opt = get_optimizer(um_lr, self.um.uncertainty_loss, self.global_step, optimizer_params['uncertainty_model'], var_list = self.um.var_list)",
"if (global_step) % self.big_save_freq < self.big_save_len: save_keys = self.big_save_keys #est_losses = [other[1] for",
"k not in self.um.save_to_gfs}) #this should be changed for an online data provider,",
"self.um.uncertainty_loss, self.global_step, optimizer_params['uncertainty_model']) self.um_targets = {'loss' : self.um.uncertainty_loss, 'learning_rate' : um_learning_rate, 'optimizer' :",
"self.map_draw_mode is not None and global_step % self.map_draw_freq == 0: # if self.map_draw_mode",
"sess.run(self.targets, feed_dict = feed_dict) #TODO case it for online res['recent'] = {} #if",
"replace_the_nones(obs[state_desc]) depths_past = np.array([depths[:-1]]) depths_fut = np.array([depths[:1]]) objects = np.array([replace_the_nones(obs[state_desc])[:-1]]) actions = np.array([replace_the_nones(act)])",
"self.um.save_to_gfs}) #this should be changed for an online data provider, set to do",
"self.um.s_i : batch[state_desc][:, :-1], self.um.action_sample : batch['action'][:, -1], self.um.true_loss : world_model_res['loss_per_example'] } um_res",
"tf.nn.log_softmax(rl_model.logits) prob_tf = tf.nn.softmax(rl_model.logits) pi_loss = -tf.reduce_sum(tf.reduce_sum(log_prob_tf * self.ac, [1]) * self.adv) vf_loss",
"obs_for_actor = [batch[self.state_desc][idx][t] for t in self.map_draw_timestep_indices] # action_samples = self.action_sampler.sample_actions() # action,",
"options, but for now just assuming one sort of specification self.state_desc = updater_params.get('state_desc',",
"msg['msg']['action_type'] == 'OBJ_ACT' else 0 for msg in provider_recent['msg']] mean_per_provider.append(np.mean(looking_at_obj)) res['obj_freq'] = np.mean(mean_per_provider)",
"for timepoint in batch.next_state['action']]]) # print('actions shape') # print(actions.shape) # print(len(batch.next_state['action'])) # action_ids_list",
"feed_dict = feed_dict) res['batch'] = {} for desc, val in batch.iteritems(): print(desc) if",
"= little_save_keys self.big_save_len = big_save_len self.big_save_freq = big_save_freq self.state_descriptor = state_descriptor self.big_save_keys.append('map_draw') self.little_save_keys.append('map_draw')",
"feed_dict = { self.wm.states : batch[self.state_desc], self.wm.action : batch['action'], self.wm.action_post : batch ['action_post']",
"prepped['depths1'], prepped['objects1'], actions, action_ids, next_depths class ExperienceReplayPostprocessor: def __init__(self, big_save_keys = None, little_save_keys",
"self.world_model.action : actions, self.world_model.action_id : action_ids, self.world_model.objects : objects } world_model_res = sess.run(self.world_model_targets,",
"have options, but for now just assuming one sort of specification self.state_desc =",
"desc in ['depths1', 'objects1']: # prepped[desc] = np.array([[timepoint if timepoint is not None",
"[] for provider_recent in batch['recent']: looking_at_obj = [1 if msg is not None",
"[], tf.int32, initializer = tf.constant_initializer(0,dtype = tf.int32)) self.fut_step = tf.get_variable('fut_step', [], tf.int32, initializer",
"initializer = tf.constant_initializer(0,dtype = tf.int32)) self.targets = {} self.state_desc = updater_params.get('state_desc', 'depths1') if",
"num_not_frozen self.targets['global_step'] = self.global_step self.targets.update({'act_lr' : act_lr, 'um_lr' : um_lr}) assert set(self.wm.readouts.keys()) !=",
": um_opt} assert set(self.wm.readouts.keys()) != set(self.um.readouts.keys()) self.targets.update(self.wm.readouts) self.targets.update(self.um.readouts) #self.targets = { # 'fut_pred'",
"= {} print('postprocessor deets') print(global_step) print(self.big_save_freq) print(self.big_save_len) if (global_step) % self.big_save_freq < self.big_save_len:",
"sess.run(self.targets, feed_dict = feed_dict) res.pop('um_increment') global_step = res['global_step'] #if self.map_draw_mode is not None",
"not None and msg['msg']['action_type'] == 'OBJ_ACT' else 0 for msg in batch['recent']['msg']] res['obj_freq']",
"in world_model_res.iteritems()) um_res_new = dict(('um_' + k, v) for k, v in um_res.iteritems())",
"step. This is probably where we can put parallelization. Not finished! ''' def",
"idx = int(action_msg[0]['id']) else: idx = -10000#just something that's not an id seen",
"feed_dict = wm_feed_dict) um_feed_dict = { self.um.s_i : batch[state_desc][:, :-1], self.um.action_sample : batch['action'][:,",
"= self.um.var_list) self.targets['um_opt'] = um_opt self.targets['um_lr'] = um_lr self.targets['global_step'] = self.global_step global_increment =",
"self.wm.action : batch['action'], self.wm.action_post : batch['action_post'] } self.targets['global_step'] = self.global_step res = sess.run(self.targets,",
"'um_lr' : um_lr, 'um_optimizer' : um_opt, 'global_step' : self.global_step, 'loss_per_example' : self.um.true_loss}) self.state_desc",
"return res class UncertaintyPostprocessor: def __init__(self, big_save_keys = None, little_save_keys = None, big_save_len",
"= [] # for i in range(2): # action_msg = batch.next_state['msg'][i]['msg']['actions'] if batch.next_state['msg'][i]",
"global_step % self.map_draw_freq == 0: # if self.map_draw_mode == 'specified_indices': # map_draw_res =",
"False): batch = {} for i, dp in enumerate(self.data_provider): provider_batch = dp.dequeue_batch() for",
": batch['action'], self.wm.action_post : batch ['action_post'] } if self.insert_objthere: feed_dict[self.wm.obj_there_via_msg] = batch['obj_there'] res",
"batch['obj_there'] res = sess.run(self.targets, feed_dict = feed_dict) #TODO case it for online res['recent']",
"= tf.get_variable('global_step', [], tf.int32, initializer = tf.constant_initializer(0,dtype = tf.int32)) self.action = tf.placeholder =",
"res = wm_res_new res['global_step'] = res.pop('um_global_step') res = self.postprocessor.postprocess(wm_res_new, batch) return res class",
"self.postprocessor.postprocess(res, batch) return res, glstep class LatentUncertaintyUpdater: def __init__(self, world_model, uncertainty_model, data_provider, optimizer_params,",
"feed_dict = wm_feed_dict) if visualize: cv2.imshow('pred', world_model_res['prediction'][0] / 4.)#TODO clean up w colors",
"rl_model, data_provider, eta): self.data_provider = data_provider self.world_model = world_model self.rl_model = rl_model self.eta",
"def __init__(self, models, data_provider): self.um = models['uncertainty_model'] self.wm = models['world_model'] self.targets = {",
"= um = models['uncertainty_model'] self.wm = wm = models['world_model'] self.targets = {'act_pred' :",
"self.global_step, optimizer_params['uncertainty_model'], var_list = self.um.var_list) self.global_step = self.global_step / 2 self.targets = {'act_pred'",
"'depths1' : batch[self.state_desc][idx], 'action' : batch['action'][idx], 'action_post' : batch['action_post'][idx]} map_draw_res.append(to_add) res['map_draw'] = map_draw_res",
"um_lr_params, um_lr = get_learning_rate(self.um_step, **learning_rate_params['uncertainty_model']) um_opt_params, um_opt = get_optimizer(um_lr, self.um.uncertainty_loss, self.um_step, optimizer_params['uncertainty_model'], var_list",
"'loss_per_example' : self.um.true_loss, 'act_loss_per_example' : self.wm.act_loss_per_example } self.dp = data_provider def run(self, sess):",
"optimizer_params, learning_rate_params, postprocessor): self.data_provider = data_provider self.world_model = world_model self.um = uncertainty_model self.global_step",
"self.postprocessor.postprocess(res, batch) return res, global_step class FreezeUpdater: def __init__(self, models, data_provider, optimizer_params, learning_rate_params,",
"'estimated_world_loss' : self.um.estimated_world_loss, 'ans' : self.um.ans, 'oh_my_god' : self.um.oh_my_god, 'model_parameters' : self.um.var_list} def",
"self.state_desc = data_provider.data_lengths['obs'].keys()[0] self.insert_objthere = False if data_provider.num_objthere is None else True def",
"val in batch.iteritems(): print(desc) if desc == 'obj_there': res['batch'][desc] = val elif desc",
"axis=0) state_desc = 'depths1' #depths, actions, actions_post, next_depth = postprocess_batch_depth(batch, state_desc) feed_dict =",
"self.um.uncertainty_loss, 'um_lr' : um_lr, 'um_optimizer' : um_opt, 'global_step' : self.global_step, 'loss_per_example' : self.um.true_loss})",
"self.um.action_sample : batch['action'][:, -1], self.um.true_loss : world_model_res['loss_per_example'] } um_res = sess.run(self.um_targets, feed_dict =",
"batch['action_post'], self.um.obj_there : batch['obj_there'] } res = sess.run(self.targets, feed_dict = feed_dict) res =",
"initializer = tf.constant_initializer(0,dtype = tf.int32)) self.act_step = tf.get_variable('act_step', [], tf.int32, initializer = tf.constant_initializer(0,dtype",
": act_opt, 'fut_optimizer' : fut_opt, 'act_lr' : act_lr, 'fut_lr' : fut_lr, 'fut_loss' :",
"um_lr, 'um_optimizer' : um_opt, 'global_step' : self.global_step, 'loss_per_example' : self.um.true_loss, 'estimated_world_loss' : self.um.estimated_world_loss",
"batch['action'], self.wm.action_post : batch['action_post'] } if self.obj_there_supervision: batch['obj_there'] = np.concatenate(batch['obj_there'], axis = 0)",
"self.world_model.states : batch[state_desc], self.world_model.action : batch['action'][:, -self.world_action_time : ] } world_model_res = sess.run(self.world_model_targets,",
"in provider_batch: if k in batch: batch[k].append(provider_batch[k]) else: batch[k] = [provider_batch[k]] for k",
"time') save_keys = self.big_save_keys est_losses = [other[1] for other in batch['recent']['other']] action_sample =",
"{'um_loss' : self.um.uncertainty_loss, 'um_lr' : um_lr, 'um_optimizer' : um_opt, 'global_step' : self.global_step, 'loss_per_example'",
"get_learning_rate(self.global_step, ** learning_rate_params['uncertainty_model']) um_opt_params, um_opt = get_optimizer(um_lr, self.um.uncertainty_loss, self.global_step, optimizer_params['uncertainty_model'], var_list = self.um.var_list)",
"optimizer_params['world_model']['fut_model'], var_list = self.wm.fut_var_list) um_opt_params, um_opt = get_optimizer(um_lr, self.um.uncertainty_loss, self.global_step, optimizer_params['uncertainty_model'], var_list =",
"in batch.iteritems(): print(desc) if desc == 'obj_there': res['batch'][desc] = val elif desc !=",
"''' Defines the training step. ''' import sys sys.path.append('tfutils') import tensorflow as tf",
"idx = int(action_msg[0]['id']) # action_ids_list.append(idx) # action_ids = np.array([action_ids_list]) # next_depths = np.array([batch.next_state['depths1']])",
"'global_step' : self.global_step, 'loss_per_example' : self.um.true_loss, 'estimated_world_loss' : self.um.estimated_world_loss, 'ans' : self.um.ans, 'oh_my_god'",
"sess.run(self.targets, feed_dict = feed_dict) res = self.postprocessor.postprocess(res, batch) return res class SquareForceMagUpdater: def",
"[json.dumps(msg) for msg in batch['recent']['msg']] self.start = end def close(self): self.hdf5.close() class LatentUncertaintyValidator:",
"updater_params): self.data_provider = data_provider self.wm = world_model self.um = uncertainty_model self.postprocessor = postprocessor",
"{'global_step' : self.global_step, 'um_optimizer' : um_opt} assert set(self.wm.readouts.keys()) != set(self.um.readouts.keys()) self.targets.update(self.wm.readouts) self.targets.update(self.um.readouts) #self.targets",
"None): self.data_provider = data_provider self.wm = world_model self.um = uncertainty_model self.postprocessor = postprocessor",
"data_provider, optimizer_params, learning_rate_params, postprocessor, updater_params, action_sampler = None): self.data_provider = data_provider \\ if",
"initializer = tf.constant_initializer(0,dtype = tf.int32)) self.wm_lr_params, wm_learning_rate = get_learning_rate(self.global_step, ** learning_rate_params['world_model']) self.wm_opt_params, wm_opt",
": actions, self.world_model.action_id : action_ids, self.world_model.objects : objects } world_model_res = sess.run(self.world_model_targets, feed_dict",
"= np.array([[timepoint if timepoint is not None else np.zeros(obs['depths1'][-1].shape, dtype = obs['depths1'][-1].dtype) for",
": um_opt, 'estimated_world_loss' : self.um.estimated_world_loss, 'um_loss' : self.um.uncertainty_loss, 'loss_per_example' : self.um.true_loss, 'global_step' :",
"**learning_rate_params['uncertainty_model']) self.um_lr_params, um_opt = get_optimizer(um_learning_rate, self.um.uncertainty_loss, self.global_step, optimizer_params['uncertainty_model']) self.global_step = self.global_step / 2",
"um_opt = get_optimizer(um_learning_rate, self.um.uncertainty_loss, self.global_step, optimizer_params['uncertainty_model']) self.global_step = self.global_step / 2 self.um_targets =",
"{'given' : self.world_model.processed_input, 'loss' : self.world_model.loss, 'learning_rate' : wm_learning_rate, 'optimizer' : wm_opt, 'prediction'",
"__init__(self, models, data_provider): self.um = um = models['uncertainty_model'] self.wm = wm = models['world_model']",
"pass each index because action sampling is the 'batch.' #self.action_sampler = action_sampler #assert",
"for other in batch['recent']['other']] entropies = np.mean(entropies) res['entropy'] = entropies looking_at_obj = [1",
"= 0 self.targets = {} self.state_desc = updater_params.get('state_desc', 'depths1') if not freeze_wm: num_not_frozen",
"self.little_save_keys = little_save_keys self.big_save_len = big_save_len self.big_save_freq = big_save_freq self.state_descriptor = state_descriptor self.big_save_keys.append('map_draw')",
"for pair in training_results.iteritems() if pair[0] in save_keys)) #if 'other' in batch['recent']: #",
"act_dim), dtype = np.float32)} print('save loc set up') self.start = 0 def update(self):",
"entropy, estimated_world_loss = self.um.act(sess, action_samples, obs_for_actor) to_add = {'example_id' : idx, 'action_sample' :",
"optimizer_params['world_model']['fut_model'], var_list = self.wm.fut_var_list) self.targets['act_opt'] = act_opt self.targets['fut_opt'] = fut_opt self.targets['act_lr'] = act_lr",
": batch['action_post'] } self.targets['global_step'] = self.global_step res = sess.run(self.targets, feed_dict = feed_dict) global_step",
": um_opt, 'global_step' : self.global_step, 'loss_per_example' : self.um.true_loss, 'estimated_world_loss' : self.um.estimated_world_loss } if",
"self.global_step = self.global_step / 3 self.targets = {'encoding_i' : self.wm.encoding_i, 'encoding_f' : self.wm.encoding_f,",
"fut_opt = get_optimizer(fut_lr, self.wm.fut_loss, self.fut_step, optimizer_params['world_model']['fut_model'], var_list = self.wm.fut_var_list) self.targets['act_opt'] = act_opt self.targets['fut_opt']",
"# print(len(batch.next_state['action'])) # action_ids_list = [] # for i in range(2): # action_msg",
"= self.global_step / 2 self.targets = {'act_pred' : self.wm.act_pred, 'act_loss' : self.wm.act_loss, 'act_optimizer'",
"= state_descriptor def postprocess(self, training_results, batch): global_step = training_results['global_step'] res = {} print('postprocessor",
"learning_rate_params['uncertainty_model']) act_opt_params, act_opt = get_optimizer(act_lr, self.wm.act_loss, self.global_step, optimizer_params['world_model']['act_model'], var_list = self.wm.act_var_list + self.wm.encode_var_list)",
"'act_optimizer' : act_opt, 'fut_optimizer' : fut_opt, 'act_lr' : act_lr, 'fut_lr' : fut_lr, 'fut_loss'",
"-1], self.um.true_loss : world_model_res['loss_per_example'] } um_res = sess.run(self.um_targets, feed_dict = um_feed_dict) wm_res_new =",
"visualize = False): batch = self.data_provider.dequeue_batch() depths, objects, actions, action_ids, next_depth = postprocess_batch_for_actionmap(batch)",
"__init__(self, data_provider, updater_params): self.data_provider = data_provider fn = updater_params['hdf5_filename'] N = updater_params['N_save'] height,",
"False): batch = self.data_provider.dequeue_batch() state_desc = self.state_desc feed_dict = { self.wm.states : batch[state_desc],",
"um_opt_params, um_opt = get_optimizer(um_lr, self.um.uncertainty_loss, self.global_step, optimizer_params['uncertainty_model']) self.targets = {'um_loss' : self.um.uncertainty_loss, 'um_optimizer'",
"msg[i] is not None else [] if len(action_msg): idx = int(action_msg[0]['id']) else: idx",
"self.um.estimated_world_loss } if self.um.exactly_whats_needed: self.targets['oh_my_god'] = self.um.oh_my_god self.state_desc = updater_params['state_desc'] def update(self, sess,",
": hdf5.require_dataset('depths1', shape = (N, height, width, 3), dtype = np.uint8), 'objects1' :",
"for (k, v) in training_results.iteritems() if k in save_keys)) #res['msg'] = batch['msg'][-1] entropies",
"action_ids, next_depth = postprocess_batch_for_actionmap(batch) wm_feed_dict = { self.world_model.s_i : depths, self.world_model.s_f : next_depth,",
"= models['uncertainty_model'] self.wm = models['world_model'] self.targets = { 'act_pred' : self.wm.act_pred, 'fut_loss' :",
"batch['recent']: # entropies = [other[0] for other in batch['recent']['other']] # entropies = np.mean(entropies)",
"batch['action_post'][idx]} # map_draw_res.append(to_add) # res['map_draw'] = map_draw_res res = self.postprocessor.postprocess(res, batch) return res,",
"self.postprocessor = postprocessor self.world_action_time = self.world_model.action.get_shape().as_list()[1] def start(self, sess): self.data_provider.start_runner(sess) sess.run(tf.global_variables_initializer()) def update(self,",
"self.targets = { 'act_pred' : self.wm.act_pred, 'fut_loss' : self.wm.fut_loss, 'act_loss' : self.wm.act_loss, 'um_loss'",
"0.01 rl_opt_params, rl_opt = get_optimizer(learning_rate, self.rl_loss, ) def replace_the_nones(my_list): ''' Assumes my_list[-1] is",
"dict(('wm_' + k, v) for k, v in world_model_res.iteritems()) um_res_new = dict(('um_' +",
"np.zeros(obs[desc][-1].shape, dtype = obs[desc][-1].dtype) for timepoint in obs[desc]] for obs in batch.states]) #",
"return obs_past, actions, actions_post, obs_fut # def postprocess_batch_depth(batch): # depths = np.array([[timepoint if",
"'specified_indices' #relies on there being just one obs type self.state_desc = data_provider.data_lengths['obs'].keys()[0] self.insert_objthere",
"= tf.int32)) self.fut_step = tf.get_variable('fut_step', [], tf.int32, initializer = tf.constant_initializer(0,dtype = tf.int32)) self.um_step",
"optimizer_params['uncertainty_model'], var_list = self.um.var_list) self.targets = {'global_step' : self.global_step, 'um_optimizer' : um_opt} assert",
"self.big_save_freq < self.big_save_len: print('big time') save_keys = self.big_save_keys est_losses = [other[1] for other",
"the training step. This is probably where we can put parallelization. Not finished!",
"map_draw_res = [] for idx in self.map_draw_example_indices: obs_for_actor = [batch[self.state_desc][idx][t] for t in",
"if msg is not None and msg['msg']['action_type'] == 'OBJ_ACT' else 0 for msg",
"import json class RawDepthDiscreteActionUpdater: ''' Provides the training step. This is probably where",
"initializer = tf.constant_initializer(0,dtype = tf.int32)) self.action = tf.placeholder = tf.placeholder(tf.float32, [None] + world_model.action_one_hot.get_shape().as_list()[1:])",
"not freeze_wm: num_not_frozen += 1 act_opt_params, act_opt = get_optimizer(act_lr, self.wm.act_loss, self.global_step, optimizer_params['world_model']['act_model'], var_list",
"= np.array([batch.next_state['depths1']]) # return prepped['depths1'], prepped['objects1'], actions, action_ids, next_depths class ExperienceReplayPostprocessor: def __init__(self,",
"h5py.special_dtype(vlen = str) self.handles = {'msg' : hdf5.require_dataset('msg', shape = (N,), dtype =",
": hdf5.require_dataset('msg', shape = (N,), dtype = dt), 'depths1' : hdf5.require_dataset('depths1', shape =",
"tf.placeholder(tf.float32, [None]) self.r = tf.placeholder(tf.float32, [None]) log_prob_tf = tf.nn.log_softmax(rl_model.logits) prob_tf = tf.nn.softmax(rl_model.logits) pi_loss",
"[batch[self.state_desc][idx][t] for t in self.map_draw_timestep_indices] action_samples = self.action_sampler.sample_actions() action, entropy, estimated_world_loss = self.um.act(sess,",
"sys.path.append('tfutils') import tensorflow as tf from tfutils.base import get_optimizer, get_learning_rate import numpy as",
"batch = self.dp.dequeue_batch() feed_dict = { self.wm.states : batch['depths1'], self.wm.action : batch['action'], self.wm.obj_there",
"um_opt = get_optimizer(um_lr, self.um.uncertainty_loss, self.global_step, optimizer_params['uncertainty_model'], var_list = self.um.var_list) self.targets = {'um_loss' :",
"{} self.state_desc = updater_params.get('state_desc', 'depths1') if not freeze_wm: act_lr_params, act_lr = get_learning_rate(self.act_step, **learning_rate_params['world_model']['act_model'])",
"uncertainty_model, data_provider, optimizer_params, learning_rate_params, postprocessor, updater_params = None): self.data_provider = data_provider self.wm =",
"self.adv) vf_loss = .5 * tf.reduce_sum(tf.square(rl_model.vf - self.r)) entropy = -tf.reduce_sum(prob_tf * log_prob_tf)",
"= self.postprocessor.postprocess(res, batch) return res, global_step class FreezeUpdater: def __init__(self, models, data_provider, optimizer_params,",
"'OBJ_ACT' else 0 for msg in provider_recent['msg']] mean_per_provider.append(np.mean(looking_at_obj)) res['obj_freq'] = np.mean(mean_per_provider) res['obj_freq_per_provider_noprint'] =",
"self.um.estimated_world_loss, 'um_loss' : self.um.uncertainty_loss, 'loss_per_example' : self.um.true_loss} self.dp = data_provider def run(self, sess):",
": self.world_model.tv} self.inc_step = self.global_step.assign_add(1) self.wm_lr_params, um_learning_rate = get_learning_rate(self.global_step, **learning_rate_params['uncertainty_model']) self.wm_lr_params, um_opt =",
"data_provider, optimizer_params, learning_rate_params, postprocessor, updater_params): self.dp = data_provider self.wm = models['world_model'] self.um =",
"res['obj_freq'] = np.mean(mean_per_provider) res['obj_freq_per_provider_noprint'] = mean_per_provider return res class UncertaintyPostprocessor: def __init__(self, big_save_keys",
"'act_loss_per_example' : self.wm.act_loss_per_example } self.dp = data_provider def run(self, sess): batch = self.dp.dequeue_batch()",
"= data_provider self.wm = models['world_model'] self.um = models['uncertainty_model'] self.postprocessor = postprocessor self.global_step =",
"import cv2 from curiosity.interaction import models import h5py import json class RawDepthDiscreteActionUpdater: '''",
": batch['obj_there'] } return sess.run(self.targets, feed_dict = feed_dict) class ActionUncertaintyValidator: def __init__(self, models,",
"= updater_params.get('state_desc', 'depths1') #self.map_draw_mode = updater_params['map_draw_mode'] #this specification specifices batch example indices for",
"== 'specified_indices' and self.action_sampler is not None, (self.map_draw_mode, action_sampler) #self.map_draw_example_indices = updater_params['map_draw_example_indices'] #self.map_draw_timestep_indices",
"tosave = batch['recent'][k] if k in ['action', 'action_post']: tosave = tosave.astype(np.float32) self.handles[k][self.start :",
"res class ActionUncertaintyValidatorWithReadouts: def __init__(self, model, data_provider): self.dp = data_provider self.wm = model['world_model']",
"(N, height, width, 3), dtype = np.uint8), 'action' : hdf5.require_dataset('action', shape = (N,",
"+ k, v) for k, v in um_res.iteritems()) wm_res_new.update(um_res_new) res['global_step'] = res.pop('um_global_step') res",
"tfutils.base import get_optimizer, get_learning_rate import numpy as np import cv2 from curiosity.interaction import",
": estimated_world_loss, # 'action_samples' : action_samples, 'depths1' : batch[self.state_desc][idx], # 'action' : batch['action'][idx],",
"state_descriptor def postprocess(self, training_results, batch): global_step = training_results['global_step'] res = {} print('postprocessor deets')",
"indices for which we do a forward pass. #need to do one forward",
"= data_provider self.wm = model['world_model'] self.um = model['uncertainty_model'] self.targets = {} self.targets.update({k :",
"= data_provider self.wm = world_model self.um = uncertainty_model self.postprocessor = postprocessor self.global_step =",
"for other in batch['other']] #action_sample = [other[2] for other in batch['other']] res['batch'] =",
"batch['action'][:, -1], self.um.true_loss : world_model_res['loss_per_example'] } um_res = sess.run(self.um_targets, feed_dict = um_feed_dict) wm_res_new",
"self.little_save_keys res.update(dict((k, v) for (k, v) in training_results.iteritems() if k in save_keys)) #res['msg']",
"sort of specification self.state_desc = updater_params.get('state_desc', 'depths1') self.map_draw_mode = updater_params['map_draw_mode'] #this specification specifices",
"'loss_per_example' : self.um.true_loss, 'global_step' : self.global_step} def update(self, sess, visualize = False): batch",
"sess, visualize = False): batch = self.data_provider.dequeue_batch() state_desc = self.state_desc #depths, actions, actions_post,",
"= (N, act_dim), dtype = np.float32)} print('save loc set up') self.start = 0",
"{ self.world_model.s_i : depths, self.world_model.s_f : next_depth, self.world_model.action : actions, self.world_model.action_id : action_ids,",
"= get_learning_rate(self.global_step, **learning_rate_params['uncertainty_model']) um_opt_params, um_opt = get_optimizer(um_lr, self.um.uncertainty_loss, self.global_step, optimizer_params['uncertainty_model']) self.targets = {'um_loss'",
": end] = batch['recent'][k] self.handles['msg'][self.start : end] = [json.dumps(msg) for msg in batch['recent']['msg']]",
"um_opt self.targets['um_lr'] = um_lr self.targets['global_step'] = self.global_step global_increment = tf.assign_add(self.global_step, 1) um_increment =",
"actions, action_ids, depths_fut # def postprocess_batch_for_actionmap(batch): # prepped = {} # for desc",
"+= 1 um_opt_params, um_opt = get_optimizer(um_lr, self.um.uncertainty_loss, self.global_step, optimizer_params['uncertainty_model'], var_list = self.um.var_list) self.targets['um_opt']",
"initializer = tf.constant_initializer(0,dtype = tf.int32)) self.fut_step = tf.get_variable('fut_step', [], tf.int32, initializer = tf.constant_initializer(0,dtype",
"hdf5 = h5py.File(fn, mode = 'a') dt = h5py.special_dtype(vlen = str) self.handles =",
"= self.global_step global_increment = tf.assign_add(self.global_step, 1) um_increment = tf.assign_add(self.um.step, 1) self.targets.update({'global_increment' : global_increment,",
"is not None and msg['msg']['action_type']['OBJ_ACT'] else 0 for msg in batch['recent']['msg']] res['obj_freq'] =",
"desc, val in batch.iteritems(): print(desc) if desc == 'obj_there': res['batch'][desc] = val elif",
"= obs['depths1'][-1].dtype) for timepoint in obs['depths1']] for obs in batch.states]) # actions =",
"feed_dict = feed_dict) res.pop('um_increment') res.pop('global_increment') global_step = res['global_step'] #if self.map_draw_mode is not None",
"/ 2 self.um_targets = {'loss' : self.um.uncertainty_loss, 'learning_rate' : um_learning_rate, 'optimizer' : um_opt,",
"action, 'estimated_world_loss' : estimated_world_loss, 'action_samples' : action_samples, 'depths1' : batch[self.state_desc][idx], 'action' : batch['action'][idx],",
"timepoint is None else timepoint for timepoint in batch.next_state['action']]]) # print('actions shape') #",
"sess.run(self.um_targets, feed_dict = um_feed_dict) wm_res_new = dict(('wm_' + k, v) for k, v",
"action_samples, obs_for_actor) to_add = {'example_id' : idx, 'action_sample' : action, 'estimated_world_loss' : estimated_world_loss,",
"= replace_the_nones(obs[state_desc]) obs_past = np.array([depths[:-1]]) obs_fut = np.array([depths[1:]]) actions = np.array([replace_the_nones(act)]) actions_post =",
"batch['recent'] else: save_keys = self.little_save_keys res.update(dict(pair for pair in training_results.iteritems() if pair[0] in",
"'loss' : self.world_model.loss, 'loss_per_example' : self.world_model.loss_per_example, 'learning_rate' : wm_learning_rate, 'optimizer' : wm_opt, 'prediction'",
"= [] for idx in self.map_draw_example_indices: obs_for_actor = [batch[self.state_desc][idx][t] for t in self.map_draw_timestep_indices]",
"self.obj_there_supervision: batch['obj_there'] = np.concatenate(batch['obj_there'], axis = 0) feed_dict[self.wm.obj_there_via_msg] = batch['obj_there'] print('state desc! '",
"self.wm.obj_there : batch['obj_there'] } res = sess.run(self.targets, feed_dict = feed_dict) res = self.postprocessor.postprocess(res,",
"data_provider def run(self, sess): batch = self.dp.dequeue_batch() feed_dict = { self.wm.states : batch['depths1'],",
"'est_loss' : est_losses, 'action_sample' : action_sample} res['msg'] = batch['recent']['msg'] else: print('little time') save_keys",
": batch['action'], self.wm.action_post : batch['action_post'] } res = sess.run(self.targets, feed_dict = feed_dict) res.pop('um_increment')",
"action_samples, 'depths1' : batch[self.state_desc][idx], 'action' : batch['action'][idx], 'action_post' : batch['action_post'][idx]} map_draw_res.append(to_add) res['map_draw'] =",
"[] for idx in self.map_draw_example_indices: obs_for_actor = [batch[self.state_desc][idx][t] for t in self.map_draw_timestep_indices] action_samples",
"self.world_model.action : batch['action'][:, -self.world_action_time : ] } world_model_res = sess.run(self.world_model_targets, feed_dict = wm_feed_dict)",
"batch['action'], self.wm.action_post : batch ['action_post'] } if self.insert_objthere: feed_dict[self.wm.obj_there_via_msg] = batch['obj_there'] res =",
"in self.map_draw_timestep_indices] # action_samples = self.action_sampler.sample_actions() # action, entropy, estimated_world_loss = self.um.act(sess, action_samples,",
"= big_save_freq self.state_descriptor = state_descriptor self.big_save_keys.append('map_draw') self.little_save_keys.append('map_draw') self.big_save_keys.extend(['act_lr', 'um_lr']) self.little_save_keys.extend(['act_lr', 'um_lr']) def postprocess(self,",
"res.pop('um_global_step') res = self.postprocessor.postprocess(wm_res_new, batch) return res class DamianWMUncertaintyUpdater: def __init__(self, world_model, uncertainty_model,",
"'action' : hdf5.require_dataset('action', shape = (N, act_dim), dtype = np.float32), 'action_post' : hdf5.require_dataset('action_post',",
": self.wm.act_loss, 'estimated_world_loss' : self.um.estimated_world_loss, 'um_loss' : self.um.uncertainty_loss, 'loss_per_example' : self.um.true_loss} self.dp =",
"k in save_keys)) #res['msg'] = batch['msg'][-1] entropies = [other[0] for other in batch['recent']['other']]",
"self.action_sampler.sample_actions() # action, entropy, estimated_world_loss = self.um.act(sess, action_samples, obs_for_actor) # to_add = {'example_id'",
"height, width, 3), dtype = np.uint8), 'images1': hdf5.require_dataset('images1', shape = (N, height, width,",
"tf from tfutils.base import get_optimizer, get_learning_rate import numpy as np import cv2 from",
"'loss_per_example' : self.um.true_loss, 'estimated_world_loss' : self.um.estimated_world_loss } self.state_desc = updater_params['state_desc'] def update(self, sess,",
"#self.state_desc = updater_params.get('state_desc', 'depths1') #self.map_draw_mode = updater_params['map_draw_mode'] #this specification specifices batch example indices",
"= res['global_step'] if self.map_draw_mode is not None and global_step % self.map_draw_freq == 0:",
"save loc') self.hdf5 = hdf5 = h5py.File(fn, mode = 'a') dt = h5py.special_dtype(vlen",
"= None #Map drawing. Meant to have options, but for now just assuming",
"'' # } #self.targets.update({'um_loss' : self.um.uncertainty_loss, 'um_lr' : um_lr, 'um_optimizer' : um_opt, #",
"batch[self.state_desc][idx], 'action' : batch['action'][idx], 'action_post' : batch['action_post'][idx]} map_draw_res.append(to_add) res['map_draw'] = map_draw_res res =",
"= get_optimizer(um_lr, self.um.uncertainty_loss, self.global_step, optimizer_params['uncertainty_model'], var_list = self.um.var_list) self.global_step = self.global_step / 2",
"learning_rate_params, postprocessor, updater_params, action_sampler = None): self.data_provider = data_provider \\ if isinstance(data_provider, list)",
"um_opt = get_optimizer(um_lr, self.um.uncertainty_loss, self.global_step, optimizer_params['uncertainty_model'], var_list = self.um.var_list) self.targets = {'global_step' :",
"def run(self, sess): batch = self.dp.dequeue_batch() feed_dict = { self.wm.states : batch['depths1'], self.wm.action",
"visualize = False): batch = self.data_provider.dequeue_batch() state_desc = self.state_desc feed_dict = { self.wm.states",
"batch = self.data_provider.dequeue_batch() state_desc = self.state_desc feed_dict = { self.wm.states : batch[state_desc], self.wm.action",
"= action_sampler assert self.map_draw_mode == 'specified_indices' and self.action_sampler is not None, (self.map_draw_mode, action_sampler)",
"= world_model self.rl_model = rl_model self.eta = eta self.global_step = tf.get_variable('global_step', [], tf.int32,",
"is not None else [] if len(action_msg): idx = int(action_msg[0]['id']) else: idx =",
"= {} # for desc in ['depths1', 'objects1']: # prepped[desc] = np.array([[timepoint if",
"self.rl_loss, ) def replace_the_nones(my_list): ''' Assumes my_list[-1] is np array ''' return [np.zeros(my_list[-1].shape,",
": self.um.ans, 'oh_my_god' : self.um.oh_my_god, 'model_parameters' : self.um.var_list} def update(self, sess): batch =",
"class RawDepthDiscreteActionUpdater: ''' Provides the training step. This is probably where we can",
"self.map_draw_mode == 'specified_indices': map_draw_res = [] for idx in self.map_draw_example_indices: obs_for_actor = [batch[self.state_desc][idx][t]",
"= [provider_batch[k]] for k in ['action', 'action_post', self.state_desc]: batch[k] = np.concatenate(batch[k], axis=0) feed_dict",
": self.um.estimated_world_loss, 'um_loss' : self.um.uncertainty_loss, 'loss_per_example' : self.um.true_loss, 'global_step' : self.global_step} def update(self,",
"self.act_lr_params, act_lr = get_learning_rate(self.global_step, ** learning_rate_params['world_model']['act_model']) self.um_lr_params, um_lr = get_learning_rate(self.global_step, ** learning_rate_params['uncertainty_model']) num_not_frozen",
"np.array(batch.actions) # next_depth = np.array([batch.next_state['depths1']]) # return depths, actions, next_depth def postprocess_batch_for_actionmap(batch, state_desc):",
"} if self.insert_objthere: feed_dict[self.wm.obj_there_via_msg] = batch['obj_there'] res = sess.run(self.targets, feed_dict = feed_dict) #TODO",
"vf_loss = .5 * tf.reduce_sum(tf.square(rl_model.vf - self.r)) entropy = -tf.reduce_sum(prob_tf * log_prob_tf) self.rl_loss",
"world_model_res['given'][0, 0] / 4.) cv2.imshow('processed1', world_model_res['given'][0, 1] / 4.) cv2.waitKey(1) print('wm loss: '",
"self.dp.dequeue_batch() feed_dict = { self.wm.states : batch[self.state_desc], self.wm.action : batch['action'], self.wm.action_post : batch",
"for which we do a forward pass. #need to do one forward pass",
"prob_tf = tf.nn.softmax(rl_model.logits) pi_loss = -tf.reduce_sum(tf.reduce_sum(log_prob_tf * self.ac, [1]) * self.adv) vf_loss =",
"= self.action_sampler.sample_actions() # action, entropy, estimated_world_loss = self.um.act(sess, action_samples, obs_for_actor) # to_add =",
"self.global_step, optimizer_params['world_model']['act_model'], var_list = self.wm.act_var_list + self.wm.encode_var_list) self.targets['act_opt'] = act_opt if not freeze_um:",
"self.um.uncertainty_loss, self.global_step, optimizer_params['uncertainty_model']) self.global_step = self.global_step / 2 self.um_targets = {'loss' : self.um.uncertainty_loss,",
"batch['recent']['other']] res['batch'] = {'obs' : batch['depths1'], 'act' : batch['action'], 'act_post' : batch['action_post'], 'est_loss'",
"self.targets.update({k : v for k, v in self.wm.readouts.items() if k not in self.wm.save_to_gfs})",
"self.postprocessor.postprocess(res, batch) return res, global_step class JustUncertaintyUpdater: def __init__(self, models, data_provider, optimizer_params, learning_rate_params,",
"import sys sys.path.append('tfutils') import tensorflow as tf from tfutils.base import get_optimizer, get_learning_rate import",
": act_lr, 'um_lr' : um_lr}) assert set(self.wm.readouts.keys()) != set(self.um.readouts.keys()) self.targets.update(self.wm.readouts) self.targets.update(self.um.readouts) um_increment =",
"self.targets self.targets['um_increment'] = um_increment self.obj_there_supervision = updater_params.get('include_obj_there', False) #self.map_draw_mode = None #Map drawing.",
"data_provider self.world_model = world_model self.rl_model = rl_model self.eta = eta self.global_step = tf.get_variable('global_step',",
"provider, set to do nothing self.map_draw_mode = 'specified_indices' #relies on there being just",
"optimizer_params['world_model']['act_model'], var_list = self.wm.act_var_list + self.wm.encode_var_list) fut_opt_params, fut_opt = get_optimizer(fut_lr, self.wm.fut_loss, self.fut_step, optimizer_params['world_model']['fut_model'],",
"= tf.nn.softmax(rl_model.logits) pi_loss = -tf.reduce_sum(tf.reduce_sum(log_prob_tf * self.ac, [1]) * self.adv) vf_loss = .5",
"time') save_keys = self.little_save_keys res.update(dict((k, v) for (k, v) in training_results.iteritems() if k",
": self.world_model.loss, 'loss_per_example' : self.world_model.loss_per_example, 'learning_rate' : wm_learning_rate, 'optimizer' : wm_opt, 'prediction' :",
"[], tf.int32, initializer = tf.constant_initializer(0,dtype = tf.int32)) self.wm_lr_params, wm_learning_rate = get_learning_rate(self.global_step, ** learning_rate_params['world_model'])",
"fut_lr = get_learning_rate(self.fut_step, **learning_rate_params['world_model']['fut_model']) act_opt_params, act_opt = get_optimizer(act_lr, self.wm.act_loss, self.act_step, optimizer_params['world_model']['act_model'], var_list =",
"#TODO case it for online res['recent'] = {} #if self.map_draw_mode == 'specified_indices': #",
"import get_optimizer, get_learning_rate import numpy as np import cv2 from curiosity.interaction import models",
"if visualize: cv2.imshow('pred', world_model_res['prediction'][0] / 4.)#TODO clean up w colors cv2.imshow('tv', world_model_res['tv'][0] /",
"print(global_step) print(self.big_save_freq) print(self.big_save_len) if (global_step) % self.big_save_freq < self.big_save_len: print('big time') save_keys =",
"fut_opt = get_optimizer(fut_lr, self.wm.fut_loss, self.global_step, optimizer_params['world_model']['fut_model'], var_list = self.wm.fut_var_list) um_opt_params, um_opt = get_optimizer(um_lr,",
"var_list = self.um.var_list) self.targets['um_opt'] = um_opt if num_not_frozen == 0: self.targets['global_step'] = self.global_step",
"# action, entropy, estimated_world_loss = self.um.act(sess, action_samples, obs_for_actor) # to_add = {'example_id' :",
"'loss_per_example' : self.um.true_loss}) self.state_desc = updater_params['state_desc'] #checking that we don't have repeat names",
"msg in batch['recent']['msg']] res['obj_freq'] = np.mean(looking_at_obj) return res class DataWriteUpdater: def __init__(self, data_provider,",
"= batch['obj_there'] res = sess.run(self.targets, feed_dict = feed_dict) #TODO case it for online",
": hdf5.require_dataset('objects1', shape = (N, height, width, 3), dtype = np.uint8), 'images1': hdf5.require_dataset('images1',",
"np array ''' return [np.zeros(my_list[-1].shape, dtype = my_list[-1].dtype) if elt is None else",
"if timepoint is not None else np.zeros(obs[desc][-1].shape, dtype = obs[desc][-1].dtype) for timepoint in",
"= get_optimizer(fut_lr, self.wm.fut_loss, self.global_step, optimizer_params['world_model']['fut_model'], var_list = self.wm.fut_var_list) um_opt_params, um_opt = get_optimizer(um_lr, self.um.uncertainty_loss,",
"return res class SquareForceMagUpdater: def __init__(self, models, data_provider, optimizer_params, learning_rate_params, postprocessor, updater_params): self.dp",
"batch) return res class DebuggingForceMagUpdater: def __init__(self, models, data_provider, optimizer_params, learning_rate_params, postprocessor, updater_params):",
": batch['action_post'] } if self.um.insert_obj_there: print('adding obj_there to feed dict') feed_dict[self.um.obj_there] = batch['obj_there']",
"4.) cv2.imshow('processed1', world_model_res['given'][0, 1] / 4.) cv2.waitKey(1) print('wm loss: ' + str(world_model_res['loss'])) um_feed_dict",
"res class UncertaintyUpdater: def __init__(self, world_model, uncertainty_model, data_provider, optimizer_params, learning_rate_params, postprocessor): self.data_provider =",
": batch['action'], self.wm.action_post : batch['action_post'] } if self.um.insert_obj_there: print('adding obj_there to feed dict')",
"'action_post']: tosave = tosave.astype(np.float32) self.handles[k][self.start : end] = batch['recent'][k] self.handles['msg'][self.start : end] =",
"= get_learning_rate(self.global_step, ** learning_rate_params['world_model']['act_model']) self.um_lr_params, um_lr = get_learning_rate(self.global_step, ** learning_rate_params['uncertainty_model']) num_not_frozen = 0",
"global_step class JustUncertaintyUpdater: def __init__(self, models, data_provider, optimizer_params, learning_rate_params, postprocessor, updater_params, action_sampler =",
"} self.targets['global_step'] = self.global_step res = sess.run(self.targets, feed_dict = feed_dict) glstep = res['global_step']",
"= data_provider fn = updater_params['hdf5_filename'] N = updater_params['N_save'] height, width = updater_params['image_shape'] act_dim",
"data_provider self.wm = model['world_model'] self.um = model['uncertainty_model'] self.targets = {} self.targets.update({k : v",
": self.global_step, 'loss_per_example' : self.um.true_loss, 'estimated_world_loss' : self.um.estimated_world_loss } if self.um.exactly_whats_needed: self.targets['oh_my_god'] =",
"self.um.var_list} def update(self, sess): batch = self.dp.dequeue_batch() feed_dict = { self.wm.action : batch['action'],",
"tf.int32)) self.act_lr_params, act_lr = get_learning_rate(self.global_step, ** learning_rate_params['world_model']['act_model']) self.fut_lr_params, fut_lr = get_learning_rate(self.global_step, ** learning_rate_params['world_model']['fut_model'])",
": self.um.estimated_world_loss, 'um_loss' : self.um.uncertainty_loss, 'loss_per_example' : self.um.true_loss} self.dp = data_provider def run(self,",
"models['uncertainty_model'] self.wm = wm = models['world_model'] self.targets = {'act_pred' : self.wm.act_pred, 'act_loss' :",
"self.world_model = world_model self.um = uncertainty_model self.global_step = tf.get_variable('global_step', [], tf.int32, initializer =",
"{'loss' : self.um.uncertainty_loss, 'learning_rate' : um_learning_rate, 'optimizer' : um_opt, 'global_step' : self.global_step} self.postprocessor",
"res['batch'][desc] = val elif desc != 'recent': res['batch'][desc] = val[:, -1] res['recent'] =",
"res['recent'] = batch['recent'] else: save_keys = self.little_save_keys res.update(dict(pair for pair in training_results.iteritems() if",
"= sess.run(self.targets, feed_dict = feed_dict) #TODO case it for online res['recent'] = {}",
"self.wm = models['world_model'] self.um = models['uncertainty_model'] self.postprocessor = postprocessor self.global_step = tf.get_variable('global_step', [],",
"batch = self.dp.dequeue_batch() feed_dict = { self.wm.states : batch[self.state_desc], self.wm.action : batch['action'], self.wm.action_post",
"= tf.int32)) self.act_lr_params, act_lr = get_learning_rate(self.global_step, ** learning_rate_params['world_model']['act_model']) self.um_lr_params, um_lr = get_learning_rate(self.global_step, **",
"but for now just assuming one sort of specification self.state_desc = updater_params.get('state_desc', 'depths1')",
"__init__(self, models, data_provider): self.um = models['uncertainty_model'] self.wm = models['world_model'] self.targets = {'um_loss' :",
"act_opt, 'um_optimizer' : um_opt, 'estimated_world_loss' : self.um.estimated_world_loss, 'um_loss' : self.um.uncertainty_loss, 'loss_per_example' : self.um.true_loss,",
"dtype = np.float32)} print('save loc set up') self.start = 0 def update(self): batch",
"self.wm.act_var_list + self.wm.encode_var_list) self.targets['act_opt'] = act_opt if not freeze_um: num_not_frozen += 1 um_opt_params,",
"= np.array([depths[:1]]) objects = np.array([replace_the_nones(obs[state_desc])[:-1]]) actions = np.array([replace_the_nones(act)]) action_ids_list = [] for i",
"'images1']: res['batch'][desc] = val res['recent'] = batch['recent'] else: save_keys = self.little_save_keys res.update(dict(pair for",
"feed_dict) res['batch'] = batch return res class ActionUncertaintyValidatorWithReadouts: def __init__(self, model, data_provider): self.dp",
"mode = 'a') dt = h5py.special_dtype(vlen = str) self.handles = {'msg' : hdf5.require_dataset('msg',",
"= [provider_batch[k]] for k in ['action', 'action_post', 'depths1']: batch[k] = np.concatenate(batch[k], axis=0) state_desc",
"= model['uncertainty_model'] self.targets = {} self.targets.update({k : v for k, v in self.wm.readouts.items()",
"self.um.estimated_world_loss, 'um_loss' : self.um.uncertainty_loss, 'loss_per_example' : self.um.true_loss, 'global_step' : self.global_step} def update(self, sess,",
"'depths1', 'objects1', 'images1']: res['batch'][desc] = val res['recent'] = batch['recent'] else: save_keys = self.little_save_keys",
"self.wm = world_model self.um = uncertainty_model self.postprocessor = postprocessor self.global_step = tf.get_variable('global_step', [],",
"self.wm.fut_pred, 'act_pred' : self.wm.act_pred, # 'fut_loss' : self.wm.fut_loss, 'act_loss' : self.wm.act_loss, # 'estimated_world_loss'",
"set(self.wm.readouts.keys()) != set(self.um.readouts.keys()) def update(self, sess, visualize = False): if self.um.just_random: print('Selecting action",
"self.targets['global_step'] = self.global_step res = sess.run(self.targets, feed_dict = feed_dict) global_step = res['global_step'] if",
"{ 'act_pred' : self.wm.act_pred, 'fut_loss' : self.wm.fut_loss, 'act_loss' : self.wm.act_loss, 'um_loss' : self.um.uncertainty_loss,",
"self.data_provider.dequeue_batch() bs = len(batch['recent']['msg']) end = self.start + bs for k in ['depths1',",
"self.targets = {'um_loss' : self.um.uncertainty_loss, 'um_lr' : um_lr, 'um_optimizer' : um_opt, 'global_step' :",
"models, data_provider): self.um = models['uncertainty_model'] self.wm = models['world_model'] self.targets = { 'act_pred' :",
"var_list = self.wm.act_var_list + self.wm.encode_var_list) fut_opt_params, fut_opt = get_optimizer(fut_lr, self.wm.fut_loss, self.fut_step, optimizer_params['world_model']['fut_model'], var_list",
"other in batch['other']] res['batch'] = {} for desc, val in batch.iteritems(): if desc",
"'batch.' self.action_sampler = action_sampler assert self.map_draw_mode == 'specified_indices' and self.action_sampler is not None,",
"fut_opt, 'act_lr' : act_lr, 'fut_lr' : fut_lr, 'fut_loss' : self.wm.fut_loss, 'act_loss' : self.wm.act_loss,",
"'act_loss' : self.wm.act_loss, # 'estimated_world_loss' : self.um.estimated_world_loss, # '' # } #self.targets.update({'um_loss' :",
"print('actions shape') # print(actions.shape) # print(len(batch.next_state['action'])) # action_ids_list = [] # for i",
": fut_lr, 'fut_loss' : self.wm.fut_loss, 'act_loss' : self.wm.act_loss, 'estimated_world_loss' : self.um.estimated_world_loss } self.targets.update({'um_loss'",
"if (global_step) % self.big_save_freq < self.big_save_len: print('big time') save_keys = self.big_save_keys est_losses =",
"self.global_step / num_not_frozen self.targets['global_step'] = self.global_step self.targets.update({'act_lr' : act_lr, 'um_lr' : um_lr}) assert",
"= tf.get_variable('fut_step', [], tf.int32, initializer = tf.constant_initializer(0,dtype = tf.int32)) self.um_step = tf.get_variable('ext_uncertainty_step', [],",
"not freeze_wm: act_lr_params, act_lr = get_learning_rate(self.act_step, **learning_rate_params['world_model']['act_model']) fut_lr_params, fut_lr = get_learning_rate(self.fut_step, **learning_rate_params['world_model']['fut_model']) act_opt_params,",
"save_keys = self.big_save_keys est_losses = [other[1] for other in batch['recent']['other']] action_sample = [other[2]",
"online data provider, set to do nothing self.map_draw_mode = 'specified_indices' #relies on there",
"= {'example_id' : idx, 'action_sample' : action, 'estimated_world_loss' : estimated_world_loss, # 'action_samples' :",
"feed_dict) res['batch'] = {} for desc, val in batch.iteritems(): print(desc) if desc ==",
"ObjectThereValidater: def __init__(self, models, data_provider): self.um = models['uncertainty_model'] self.wm = models['world_model'] self.targets =",
": batch['action'], self.wm.obj_there : batch['obj_there'] } return sess.run(self.targets, feed_dict = feed_dict) class ActionUncertaintyValidator:",
"'depths1' : batch[self.state_desc][idx], # 'action' : batch['action'][idx], 'action_post' : batch['action_post'][idx]} # map_draw_res.append(to_add) #",
"def __init__(self, models, data_provider, optimizer_params, learning_rate_params, postprocessor, updater_params): self.data_provider = data_provider\\ if isinstance(data_provider,",
": batch['action'], self.wm.action_post : batch['action_post'], self.um.obj_there : batch['obj_there'] } res = sess.run(self.targets, feed_dict",
"= get_optimizer(act_lr, self.wm.act_loss, self.global_step, optimizer_params['world_model']['act_model'], var_list = self.wm.act_var_list + self.wm.encode_var_list) fut_opt_params, fut_opt =",
"else 0 for msg in batch['recent']['msg']] res['obj_freq'] = np.mean(looking_at_obj) return res class DataWriteUpdater:",
"obs['depths1'][-1].dtype) for timepoint in obs['depths1']] for obs in batch.states]) # actions = np.array(batch.actions)",
"= self.dp.dequeue_batch() feed_dict = { self.wm.states : batch['depths1'], self.wm.action : batch['action'], self.wm.action_post :",
"self.global_step, optimizer_params['uncertainty_model'], var_list = self.um.var_list) self.targets = {'um_loss' : self.um.uncertainty_loss, 'um_lr' : um_lr,",
": self.global_step, 'loss_per_example' : self.um.true_loss}) self.state_desc = updater_params['state_desc'] #checking that we don't have",
"= self.global_step / num_not_frozen self.targets['global_step'] = self.global_step self.targets.update({'act_lr' : act_lr, 'um_lr' : um_lr})",
"freeze_wm: num_not_frozen += 1 act_opt_params, act_opt = get_optimizer(act_lr, self.wm.act_loss, self.global_step, optimizer_params['world_model']['act_model'], var_list =",
"num_not_frozen += 1 act_opt_params, act_opt = get_optimizer(act_lr, self.wm.act_loss, self.global_step, optimizer_params['world_model']['act_model'], var_list = self.wm.act_var_list",
"self.map_draw_freq = updater_params['map_draw_freq'] def update(self, sess, visualize = False): batch = {} for",
"for obs in batch.states]) # actions = np.array([[np.zeros(batch.next_state['action'][-1].shape, batch.next_state['action'][-1].dtype) if timepoint is None",
"um_learning_rate = get_learning_rate(self.global_step, **learning_rate_params['uncertainty_model']) self.wm_lr_params, um_opt = get_optimizer(um_learning_rate, self.um.uncertainty_loss, self.global_step, optimizer_params['uncertainty_model']) self.um_targets =",
"LatentUncertaintyUpdater: def __init__(self, world_model, uncertainty_model, data_provider, optimizer_params, learning_rate_params, postprocessor, updater_params = None): self.data_provider",
"self.map_draw_timestep_indices] # action_samples = self.action_sampler.sample_actions() # action, entropy, estimated_world_loss = self.um.act(sess, action_samples, obs_for_actor)"
] |
[
"def fake_client() -> Mock: \"\"\" Build a fake API client \"\"\" return Mock(get=Mock())",
"<filename>tests/conftest.py import pytest from unittest.mock import Mock @pytest.fixture def fake_client() -> Mock: \"\"\"",
"import pytest from unittest.mock import Mock @pytest.fixture def fake_client() -> Mock: \"\"\" Build",
"@pytest.fixture def fake_client() -> Mock: \"\"\" Build a fake API client \"\"\" return",
"from unittest.mock import Mock @pytest.fixture def fake_client() -> Mock: \"\"\" Build a fake",
"pytest from unittest.mock import Mock @pytest.fixture def fake_client() -> Mock: \"\"\" Build a",
"unittest.mock import Mock @pytest.fixture def fake_client() -> Mock: \"\"\" Build a fake API",
"import Mock @pytest.fixture def fake_client() -> Mock: \"\"\" Build a fake API client",
"Mock @pytest.fixture def fake_client() -> Mock: \"\"\" Build a fake API client \"\"\""
] |
[
"coding: utf-8 -*- class Oporation(): def __init__(self): pass def apply(self, img): pass if",
"-*- coding: utf-8 -*- class Oporation(): def __init__(self): pass def apply(self, img): pass",
"#!/usr/bin/env python # -*- coding: utf-8 -*- class Oporation(): def __init__(self): pass def",
"python # -*- coding: utf-8 -*- class Oporation(): def __init__(self): pass def apply(self,",
"utf-8 -*- class Oporation(): def __init__(self): pass def apply(self, img): pass if __name__",
"Oporation(): def __init__(self): pass def apply(self, img): pass if __name__ == \"__main__\": pass",
"class Oporation(): def __init__(self): pass def apply(self, img): pass if __name__ == \"__main__\":",
"-*- class Oporation(): def __init__(self): pass def apply(self, img): pass if __name__ ==",
"# -*- coding: utf-8 -*- class Oporation(): def __init__(self): pass def apply(self, img):",
"<gh_stars>0 #!/usr/bin/env python # -*- coding: utf-8 -*- class Oporation(): def __init__(self): pass"
] |
[
"= int(val) except ValueError: pass else: return val try: val = float(val) except",
"self.config.set(section, option, value) def __setitem__(self, indices, value): self.__put_item(indices, value) self.update_cfg_file() def update_cfg_file(self): with",
"try: val = int(val) except ValueError: pass else: return val try: val =",
"split(files[0])[0] if target_dir is None: target_dir = wn_dir if exists(target_dir): raise OSError('The target",
"option) try: val = int(val) except ValueError: pass else: return val try: val",
"value): indices = indices[0:2] value = str(value) section, option = indices if not",
"option in default_cfg[section]: self.__put_item([section, option], default_cfg[section][option]) self.read_cfg_file() def __getitem__(self, indices): indices = indices[0:2]",
"default_cfg[section]: self.__put_item([section, option], default_cfg[section][option]) self.read_cfg_file() def __getitem__(self, indices): indices = indices[0:2] section, option",
"self.config.options(section): self.config.set(section, option, value) def __setitem__(self, indices, value): self.__put_item(indices, value) self.update_cfg_file() def update_cfg_file(self):",
"fn), join(wn_dir, fn)) zf.close() def unzip_worknote(src_fn, target_dir = None): from zipfile import ZipFile,",
"__getitem__(self, indices): indices = indices[0:2] section, option = indices if not section in",
"with open(self.cfg_file, 'w') as outfile: self.config.write(outfile) def read_cfg_file(self): from os.path import exists if",
"indices, value): self.__put_item(indices, value) self.update_cfg_file() def update_cfg_file(self): with open(self.cfg_file, 'w') as outfile: self.config.write(outfile)",
"os.path import exists if exists(self.cfg_file): self.config.read(self.cfg_file) def get_sections(self): return self.config.sections() def get_options(self, section):",
"gettempdir try: with ZipFile(src_fn, 'r') as zipfile: files = zipfile.namelist() wn_dir = split(files[0])[0]",
"import parse_index return parse_index(index)[0:2] def gen_index(index): try: return u':'.join([str(i) for i in index[0:2]])",
"class Configuration(object): def __init__(self, cfg_file, default_cfg = None): from ConfigParser import SafeConfigParser self.cfg_file",
"self.cfg_file = cfg_file self.config = SafeConfigParser() if not default_cfg is None: for section",
"from os import makedirs, listdir from shutil import move from tempfile import gettempdir",
"val if val == 'False': return False elif val == 'True': return True",
"str(value) section, option = indices if not section in self.config.sections(): self.config.add_section(section) if not",
"wn_dir = split(files[0])[0] if target_dir is None: target_dir = wn_dir if exists(target_dir): raise",
"fn in listdir(join(tmpdir, wn_dir)): move(join(join(tmpdir, wn_dir), fn), target_dir) except BadZipfile, e: raise IOError(str(e))",
"os.path import split, exists, join from os import makedirs, listdir from shutil import",
"with ZipFile(src_fn, 'r') as zipfile: files = zipfile.namelist() wn_dir = split(files[0])[0] if target_dir",
"OSError('The target directory already exists') else: makedirs(target_dir) tmpdir = gettempdir() zipfile.extractall(tmpdir) for fn",
"= indices if not section in self.config.sections(): self.config.add_section(section) if not option in self.config.options(section):",
"import listdir from zipfile import ZipFile wn_dir = split(src_dir)[1] zf = ZipFile(target_fn, 'w')",
"fn), target_dir) except BadZipfile, e: raise IOError(str(e)) class Configuration(object): def __init__(self, cfg_file, default_cfg",
"import exists if exists(self.cfg_file): self.config.read(self.cfg_file) def get_sections(self): return self.config.sections() def get_options(self, section): return",
"== 'True': return True return val def __put_item(self, indices, value): indices = indices[0:2]",
"update_cfg_file(self): with open(self.cfg_file, 'w') as outfile: self.config.write(outfile) def read_cfg_file(self): from os.path import exists",
"not section in self.config.sections(): self.config.add_section(section) if not option in self.config.options(section): self.config.set(section, option, value)",
"as zipfile: files = zipfile.namelist() wn_dir = split(files[0])[0] if target_dir is None: target_dir",
"__setitem__(self, indices, value): self.__put_item(indices, value) self.update_cfg_file() def update_cfg_file(self): with open(self.cfg_file, 'w') as outfile:",
"-*- \"\"\" Created on Wed Sep 2 18:06:23 2015 @author: appel \"\"\" def",
"return unicode(index) def zip_worknote(src_dir, target_fn): from os.path import split, join from os import",
"ValueError: pass else: return val if val == 'False': return False elif val",
"os import makedirs, listdir from shutil import move from tempfile import gettempdir try:",
"'False': return False elif val == 'True': return True return val def __put_item(self,",
"unicode(index) def zip_worknote(src_dir, target_fn): from os.path import split, join from os import listdir",
"import split, exists, join from os import makedirs, listdir from shutil import move",
"from zipfile import ZipFile wn_dir = split(src_dir)[1] zf = ZipFile(target_fn, 'w') zf.write(src_dir, wn_dir)",
"default_cfg[section][option]) self.read_cfg_file() def __getitem__(self, indices): indices = indices[0:2] section, option = indices if",
"from ConfigParser import SafeConfigParser self.cfg_file = cfg_file self.config = SafeConfigParser() if not default_cfg",
"section, option = indices if not section in self.config.sections(): return None if not",
"parse_index(index): from worknote.items import parse_index return parse_index(index)[0:2] def gen_index(index): try: return u':'.join([str(i) for",
"listdir(join(tmpdir, wn_dir)): move(join(join(tmpdir, wn_dir), fn), target_dir) except BadZipfile, e: raise IOError(str(e)) class Configuration(object):",
"int(val) except ValueError: pass else: return val try: val = float(val) except ValueError:",
"None: target_dir = wn_dir if exists(target_dir): raise OSError('The target directory already exists') else:",
"self.update_cfg_file() def update_cfg_file(self): with open(self.cfg_file, 'w') as outfile: self.config.write(outfile) def read_cfg_file(self): from os.path",
"default_cfg = None): from ConfigParser import SafeConfigParser self.cfg_file = cfg_file self.config = SafeConfigParser()",
"import ZipFile wn_dir = split(src_dir)[1] zf = ZipFile(target_fn, 'w') zf.write(src_dir, wn_dir) for fn",
"return True return val def __put_item(self, indices, value): indices = indices[0:2] value =",
"from shutil import move from tempfile import gettempdir try: with ZipFile(src_fn, 'r') as",
"18:06:23 2015 @author: appel \"\"\" def parse_index(index): from worknote.items import parse_index return parse_index(index)[0:2]",
"makedirs, listdir from shutil import move from tempfile import gettempdir try: with ZipFile(src_fn,",
"exists') else: makedirs(target_dir) tmpdir = gettempdir() zipfile.extractall(tmpdir) for fn in listdir(join(tmpdir, wn_dir)): move(join(join(tmpdir,",
"indices[0:2] section, option = indices if not section in self.config.sections(): return None if",
"shutil import move from tempfile import gettempdir try: with ZipFile(src_fn, 'r') as zipfile:",
"if not section in self.config.sections(): self.config.add_section(section) if not option in self.config.options(section): self.config.set(section, option,",
"zip_worknote(src_dir, target_fn): from os.path import split, join from os import listdir from zipfile",
"listdir from shutil import move from tempfile import gettempdir try: with ZipFile(src_fn, 'r')",
"import gettempdir try: with ZipFile(src_fn, 'r') as zipfile: files = zipfile.namelist() wn_dir =",
"from worknote.items import parse_index return parse_index(index)[0:2] def gen_index(index): try: return u':'.join([str(i) for i",
"Configuration(object): def __init__(self, cfg_file, default_cfg = None): from ConfigParser import SafeConfigParser self.cfg_file =",
"BadZipfile, e: raise IOError(str(e)) class Configuration(object): def __init__(self, cfg_file, default_cfg = None): from",
"from os.path import split, join from os import listdir from zipfile import ZipFile",
"option in self.config.options(section): return None val = self.config.get(section, option) try: val = int(val)",
"val = float(val) except ValueError: pass else: return val if val == 'False':",
"self.__put_item([section, option], default_cfg[section][option]) self.read_cfg_file() def __getitem__(self, indices): indices = indices[0:2] section, option =",
"self.config.write(outfile) def read_cfg_file(self): from os.path import exists if exists(self.cfg_file): self.config.read(self.cfg_file) def get_sections(self): return",
"def parse_index(index): from worknote.items import parse_index return parse_index(index)[0:2] def gen_index(index): try: return u':'.join([str(i)",
"zf.write(join(src_dir, fn), join(wn_dir, fn)) zf.close() def unzip_worknote(src_fn, target_dir = None): from zipfile import",
"if not option in self.config.options(section): return None val = self.config.get(section, option) try: val",
"indices = indices[0:2] value = str(value) section, option = indices if not section",
"section, option = indices if not section in self.config.sections(): self.config.add_section(section) if not option",
"def unzip_worknote(src_fn, target_dir = None): from zipfile import ZipFile, BadZipfile from os.path import",
"already exists') else: makedirs(target_dir) tmpdir = gettempdir() zipfile.extractall(tmpdir) for fn in listdir(join(tmpdir, wn_dir)):",
"except BadZipfile, e: raise IOError(str(e)) class Configuration(object): def __init__(self, cfg_file, default_cfg = None):",
"tempfile import gettempdir try: with ZipFile(src_fn, 'r') as zipfile: files = zipfile.namelist() wn_dir",
"target_dir) except BadZipfile, e: raise IOError(str(e)) class Configuration(object): def __init__(self, cfg_file, default_cfg =",
"= self.config.get(section, option) try: val = int(val) except ValueError: pass else: return val",
"option = indices if not section in self.config.sections(): self.config.add_section(section) if not option in",
"try: with ZipFile(src_fn, 'r') as zipfile: files = zipfile.namelist() wn_dir = split(files[0])[0] if",
"unzip_worknote(src_fn, target_dir = None): from zipfile import ZipFile, BadZipfile from os.path import split,",
"is None: for section in default_cfg: for option in default_cfg[section]: self.__put_item([section, option], default_cfg[section][option])",
"section in self.config.sections(): self.config.add_section(section) if not option in self.config.options(section): self.config.set(section, option, value) def",
"utf-8 -*- \"\"\" Created on Wed Sep 2 18:06:23 2015 @author: appel \"\"\"",
"makedirs(target_dir) tmpdir = gettempdir() zipfile.extractall(tmpdir) for fn in listdir(join(tmpdir, wn_dir)): move(join(join(tmpdir, wn_dir), fn),",
"worknote.items import parse_index return parse_index(index)[0:2] def gen_index(index): try: return u':'.join([str(i) for i in",
"in listdir(src_dir): zf.write(join(src_dir, fn), join(wn_dir, fn)) zf.close() def unzip_worknote(src_fn, target_dir = None): from",
"cfg_file, default_cfg = None): from ConfigParser import SafeConfigParser self.cfg_file = cfg_file self.config =",
"def __put_item(self, indices, value): indices = indices[0:2] value = str(value) section, option =",
"= indices[0:2] value = str(value) section, option = indices if not section in",
"= gettempdir() zipfile.extractall(tmpdir) for fn in listdir(join(tmpdir, wn_dir)): move(join(join(tmpdir, wn_dir), fn), target_dir) except",
"indices if not section in self.config.sections(): return None if not option in self.config.options(section):",
"else: return val if val == 'False': return False elif val == 'True':",
"value) self.update_cfg_file() def update_cfg_file(self): with open(self.cfg_file, 'w') as outfile: self.config.write(outfile) def read_cfg_file(self): from",
"not option in self.config.options(section): return None val = self.config.get(section, option) try: val =",
"val def __put_item(self, indices, value): indices = indices[0:2] value = str(value) section, option",
"if not option in self.config.options(section): self.config.set(section, option, value) def __setitem__(self, indices, value): self.__put_item(indices,",
"TypeError: return unicode(index) def zip_worknote(src_dir, target_fn): from os.path import split, join from os",
"in default_cfg: for option in default_cfg[section]: self.__put_item([section, option], default_cfg[section][option]) self.read_cfg_file() def __getitem__(self, indices):",
"fn)) zf.close() def unzip_worknote(src_fn, target_dir = None): from zipfile import ZipFile, BadZipfile from",
"zf.close() def unzip_worknote(src_fn, target_dir = None): from zipfile import ZipFile, BadZipfile from os.path",
"ZipFile(src_fn, 'r') as zipfile: files = zipfile.namelist() wn_dir = split(files[0])[0] if target_dir is",
"index[0:2]]) except TypeError: return unicode(index) def zip_worknote(src_dir, target_fn): from os.path import split, join",
"Sep 2 18:06:23 2015 @author: appel \"\"\" def parse_index(index): from worknote.items import parse_index",
"outfile: self.config.write(outfile) def read_cfg_file(self): from os.path import exists if exists(self.cfg_file): self.config.read(self.cfg_file) def get_sections(self):",
"target directory already exists') else: makedirs(target_dir) tmpdir = gettempdir() zipfile.extractall(tmpdir) for fn in",
"from os.path import exists if exists(self.cfg_file): self.config.read(self.cfg_file) def get_sections(self): return self.config.sections() def get_options(self,",
"val = self.config.get(section, option) try: val = int(val) except ValueError: pass else: return",
"target_dir is None: target_dir = wn_dir if exists(target_dir): raise OSError('The target directory already",
"in index[0:2]]) except TypeError: return unicode(index) def zip_worknote(src_dir, target_fn): from os.path import split,",
"None: for section in default_cfg: for option in default_cfg[section]: self.__put_item([section, option], default_cfg[section][option]) self.read_cfg_file()",
"u':'.join([str(i) for i in index[0:2]]) except TypeError: return unicode(index) def zip_worknote(src_dir, target_fn): from",
"= float(val) except ValueError: pass else: return val if val == 'False': return",
"coding: utf-8 -*- \"\"\" Created on Wed Sep 2 18:06:23 2015 @author: appel",
"gen_index(index): try: return u':'.join([str(i) for i in index[0:2]]) except TypeError: return unicode(index) def",
"val try: val = float(val) except ValueError: pass else: return val if val",
"def gen_index(index): try: return u':'.join([str(i) for i in index[0:2]]) except TypeError: return unicode(index)",
"def update_cfg_file(self): with open(self.cfg_file, 'w') as outfile: self.config.write(outfile) def read_cfg_file(self): from os.path import",
"return None if not option in self.config.options(section): return None val = self.config.get(section, option)",
"# -*- coding: utf-8 -*- \"\"\" Created on Wed Sep 2 18:06:23 2015",
"join(wn_dir, fn)) zf.close() def unzip_worknote(src_fn, target_dir = None): from zipfile import ZipFile, BadZipfile",
"return val try: val = float(val) except ValueError: pass else: return val if",
"= split(files[0])[0] if target_dir is None: target_dir = wn_dir if exists(target_dir): raise OSError('The",
"Created on Wed Sep 2 18:06:23 2015 @author: appel \"\"\" def parse_index(index): from",
"None val = self.config.get(section, option) try: val = int(val) except ValueError: pass else:",
"zf = ZipFile(target_fn, 'w') zf.write(src_dir, wn_dir) for fn in listdir(src_dir): zf.write(join(src_dir, fn), join(wn_dir,",
"None): from ConfigParser import SafeConfigParser self.cfg_file = cfg_file self.config = SafeConfigParser() if not",
"IOError(str(e)) class Configuration(object): def __init__(self, cfg_file, default_cfg = None): from ConfigParser import SafeConfigParser",
"in default_cfg[section]: self.__put_item([section, option], default_cfg[section][option]) self.read_cfg_file() def __getitem__(self, indices): indices = indices[0:2] section,",
"val == 'True': return True return val def __put_item(self, indices, value): indices =",
"ZipFile, BadZipfile from os.path import split, exists, join from os import makedirs, listdir",
"in self.config.sections(): return None if not option in self.config.options(section): return None val =",
"try: val = float(val) except ValueError: pass else: return val if val ==",
"= wn_dir if exists(target_dir): raise OSError('The target directory already exists') else: makedirs(target_dir) tmpdir",
"split, exists, join from os import makedirs, listdir from shutil import move from",
"move(join(join(tmpdir, wn_dir), fn), target_dir) except BadZipfile, e: raise IOError(str(e)) class Configuration(object): def __init__(self,",
"def __getitem__(self, indices): indices = indices[0:2] section, option = indices if not section",
"e: raise IOError(str(e)) class Configuration(object): def __init__(self, cfg_file, default_cfg = None): from ConfigParser",
"val = int(val) except ValueError: pass else: return val try: val = float(val)",
"self.config.sections(): self.config.add_section(section) if not option in self.config.options(section): self.config.set(section, option, value) def __setitem__(self, indices,",
"None if not option in self.config.options(section): return None val = self.config.get(section, option) try:",
"option in self.config.options(section): self.config.set(section, option, value) def __setitem__(self, indices, value): self.__put_item(indices, value) self.update_cfg_file()",
"exists if exists(self.cfg_file): self.config.read(self.cfg_file) def get_sections(self): return self.config.sections() def get_options(self, section): return self.config.options(section)",
"exists(target_dir): raise OSError('The target directory already exists') else: makedirs(target_dir) tmpdir = gettempdir() zipfile.extractall(tmpdir)",
"zipfile: files = zipfile.namelist() wn_dir = split(files[0])[0] if target_dir is None: target_dir =",
"default_cfg is None: for section in default_cfg: for option in default_cfg[section]: self.__put_item([section, option],",
"= indices[0:2] section, option = indices if not section in self.config.sections(): return None",
"from os import listdir from zipfile import ZipFile wn_dir = split(src_dir)[1] zf =",
"return val if val == 'False': return False elif val == 'True': return",
"from tempfile import gettempdir try: with ZipFile(src_fn, 'r') as zipfile: files = zipfile.namelist()",
"join from os import listdir from zipfile import ZipFile wn_dir = split(src_dir)[1] zf",
"indices[0:2] value = str(value) section, option = indices if not section in self.config.sections():",
"target_fn): from os.path import split, join from os import listdir from zipfile import",
"read_cfg_file(self): from os.path import exists if exists(self.cfg_file): self.config.read(self.cfg_file) def get_sections(self): return self.config.sections() def",
"return False elif val == 'True': return True return val def __put_item(self, indices,",
"try: return u':'.join([str(i) for i in index[0:2]]) except TypeError: return unicode(index) def zip_worknote(src_dir,",
"as outfile: self.config.write(outfile) def read_cfg_file(self): from os.path import exists if exists(self.cfg_file): self.config.read(self.cfg_file) def",
"parse_index return parse_index(index)[0:2] def gen_index(index): try: return u':'.join([str(i) for i in index[0:2]]) except",
"for option in default_cfg[section]: self.__put_item([section, option], default_cfg[section][option]) self.read_cfg_file() def __getitem__(self, indices): indices =",
"zipfile.namelist() wn_dir = split(files[0])[0] if target_dir is None: target_dir = wn_dir if exists(target_dir):",
"from os.path import split, exists, join from os import makedirs, listdir from shutil",
"parse_index(index)[0:2] def gen_index(index): try: return u':'.join([str(i) for i in index[0:2]]) except TypeError: return",
"def zip_worknote(src_dir, target_fn): from os.path import split, join from os import listdir from",
"wn_dir), fn), target_dir) except BadZipfile, e: raise IOError(str(e)) class Configuration(object): def __init__(self, cfg_file,",
"= indices if not section in self.config.sections(): return None if not option in",
"zipfile import ZipFile, BadZipfile from os.path import split, exists, join from os import",
"= None): from ConfigParser import SafeConfigParser self.cfg_file = cfg_file self.config = SafeConfigParser() if",
"SafeConfigParser self.cfg_file = cfg_file self.config = SafeConfigParser() if not default_cfg is None: for",
"elif val == 'True': return True return val def __put_item(self, indices, value): indices",
"default_cfg: for option in default_cfg[section]: self.__put_item([section, option], default_cfg[section][option]) self.read_cfg_file() def __getitem__(self, indices): indices",
"= SafeConfigParser() if not default_cfg is None: for section in default_cfg: for option",
"zipfile.extractall(tmpdir) for fn in listdir(join(tmpdir, wn_dir)): move(join(join(tmpdir, wn_dir), fn), target_dir) except BadZipfile, e:",
"= ZipFile(target_fn, 'w') zf.write(src_dir, wn_dir) for fn in listdir(src_dir): zf.write(join(src_dir, fn), join(wn_dir, fn))",
"option = indices if not section in self.config.sections(): return None if not option",
"'w') as outfile: self.config.write(outfile) def read_cfg_file(self): from os.path import exists if exists(self.cfg_file): self.config.read(self.cfg_file)",
"target_dir = None): from zipfile import ZipFile, BadZipfile from os.path import split, exists,",
"__put_item(self, indices, value): indices = indices[0:2] value = str(value) section, option = indices",
"wn_dir if exists(target_dir): raise OSError('The target directory already exists') else: makedirs(target_dir) tmpdir =",
"raise IOError(str(e)) class Configuration(object): def __init__(self, cfg_file, default_cfg = None): from ConfigParser import",
"if val == 'False': return False elif val == 'True': return True return",
"self.config.add_section(section) if not option in self.config.options(section): self.config.set(section, option, value) def __setitem__(self, indices, value):",
"return u':'.join([str(i) for i in index[0:2]]) except TypeError: return unicode(index) def zip_worknote(src_dir, target_fn):",
"os.path import split, join from os import listdir from zipfile import ZipFile wn_dir",
"target_dir = wn_dir if exists(target_dir): raise OSError('The target directory already exists') else: makedirs(target_dir)",
"False elif val == 'True': return True return val def __put_item(self, indices, value):",
"<reponame>JanKrAppel/worknoteBook # -*- coding: utf-8 -*- \"\"\" Created on Wed Sep 2 18:06:23",
"@author: appel \"\"\" def parse_index(index): from worknote.items import parse_index return parse_index(index)[0:2] def gen_index(index):",
"import ZipFile, BadZipfile from os.path import split, exists, join from os import makedirs,",
"for section in default_cfg: for option in default_cfg[section]: self.__put_item([section, option], default_cfg[section][option]) self.read_cfg_file() def",
"for fn in listdir(src_dir): zf.write(join(src_dir, fn), join(wn_dir, fn)) zf.close() def unzip_worknote(src_fn, target_dir =",
"zipfile import ZipFile wn_dir = split(src_dir)[1] zf = ZipFile(target_fn, 'w') zf.write(src_dir, wn_dir) for",
"exists, join from os import makedirs, listdir from shutil import move from tempfile",
"self.config.sections(): return None if not option in self.config.options(section): return None val = self.config.get(section,",
"self.__put_item(indices, value) self.update_cfg_file() def update_cfg_file(self): with open(self.cfg_file, 'w') as outfile: self.config.write(outfile) def read_cfg_file(self):",
"wn_dir = split(src_dir)[1] zf = ZipFile(target_fn, 'w') zf.write(src_dir, wn_dir) for fn in listdir(src_dir):",
"split, join from os import listdir from zipfile import ZipFile wn_dir = split(src_dir)[1]",
"gettempdir() zipfile.extractall(tmpdir) for fn in listdir(join(tmpdir, wn_dir)): move(join(join(tmpdir, wn_dir), fn), target_dir) except BadZipfile,",
"__init__(self, cfg_file, default_cfg = None): from ConfigParser import SafeConfigParser self.cfg_file = cfg_file self.config",
"os import listdir from zipfile import ZipFile wn_dir = split(src_dir)[1] zf = ZipFile(target_fn,",
"value = str(value) section, option = indices if not section in self.config.sections(): self.config.add_section(section)",
"= split(src_dir)[1] zf = ZipFile(target_fn, 'w') zf.write(src_dir, wn_dir) for fn in listdir(src_dir): zf.write(join(src_dir,",
"BadZipfile from os.path import split, exists, join from os import makedirs, listdir from",
"ZipFile(target_fn, 'w') zf.write(src_dir, wn_dir) for fn in listdir(src_dir): zf.write(join(src_dir, fn), join(wn_dir, fn)) zf.close()",
"if target_dir is None: target_dir = wn_dir if exists(target_dir): raise OSError('The target directory",
"from zipfile import ZipFile, BadZipfile from os.path import split, exists, join from os",
"section in self.config.sections(): return None if not option in self.config.options(section): return None val",
"value) def __setitem__(self, indices, value): self.__put_item(indices, value) self.update_cfg_file() def update_cfg_file(self): with open(self.cfg_file, 'w')",
"for i in index[0:2]]) except TypeError: return unicode(index) def zip_worknote(src_dir, target_fn): from os.path",
"-*- coding: utf-8 -*- \"\"\" Created on Wed Sep 2 18:06:23 2015 @author:",
"\"\"\" def parse_index(index): from worknote.items import parse_index return parse_index(index)[0:2] def gen_index(index): try: return",
"= None): from zipfile import ZipFile, BadZipfile from os.path import split, exists, join",
"in listdir(join(tmpdir, wn_dir)): move(join(join(tmpdir, wn_dir), fn), target_dir) except BadZipfile, e: raise IOError(str(e)) class",
"fn in listdir(src_dir): zf.write(join(src_dir, fn), join(wn_dir, fn)) zf.close() def unzip_worknote(src_fn, target_dir = None):",
"listdir(src_dir): zf.write(join(src_dir, fn), join(wn_dir, fn)) zf.close() def unzip_worknote(src_fn, target_dir = None): from zipfile",
"if not default_cfg is None: for section in default_cfg: for option in default_cfg[section]:",
"return None val = self.config.get(section, option) try: val = int(val) except ValueError: pass",
"2 18:06:23 2015 @author: appel \"\"\" def parse_index(index): from worknote.items import parse_index return",
"float(val) except ValueError: pass else: return val if val == 'False': return False",
"ZipFile wn_dir = split(src_dir)[1] zf = ZipFile(target_fn, 'w') zf.write(src_dir, wn_dir) for fn in",
"in self.config.options(section): return None val = self.config.get(section, option) try: val = int(val) except",
"split(src_dir)[1] zf = ZipFile(target_fn, 'w') zf.write(src_dir, wn_dir) for fn in listdir(src_dir): zf.write(join(src_dir, fn),",
"'r') as zipfile: files = zipfile.namelist() wn_dir = split(files[0])[0] if target_dir is None:",
"'True': return True return val def __put_item(self, indices, value): indices = indices[0:2] value",
"open(self.cfg_file, 'w') as outfile: self.config.write(outfile) def read_cfg_file(self): from os.path import exists if exists(self.cfg_file):",
"import split, join from os import listdir from zipfile import ZipFile wn_dir =",
"for fn in listdir(join(tmpdir, wn_dir)): move(join(join(tmpdir, wn_dir), fn), target_dir) except BadZipfile, e: raise",
"def __setitem__(self, indices, value): self.__put_item(indices, value) self.update_cfg_file() def update_cfg_file(self): with open(self.cfg_file, 'w') as",
"not option in self.config.options(section): self.config.set(section, option, value) def __setitem__(self, indices, value): self.__put_item(indices, value)",
"value): self.__put_item(indices, value) self.update_cfg_file() def update_cfg_file(self): with open(self.cfg_file, 'w') as outfile: self.config.write(outfile) def",
"SafeConfigParser() if not default_cfg is None: for section in default_cfg: for option in",
"def __init__(self, cfg_file, default_cfg = None): from ConfigParser import SafeConfigParser self.cfg_file = cfg_file",
"import SafeConfigParser self.cfg_file = cfg_file self.config = SafeConfigParser() if not default_cfg is None:",
"cfg_file self.config = SafeConfigParser() if not default_cfg is None: for section in default_cfg:",
"option], default_cfg[section][option]) self.read_cfg_file() def __getitem__(self, indices): indices = indices[0:2] section, option = indices",
"not section in self.config.sections(): return None if not option in self.config.options(section): return None",
"except ValueError: pass else: return val try: val = float(val) except ValueError: pass",
"return parse_index(index)[0:2] def gen_index(index): try: return u':'.join([str(i) for i in index[0:2]]) except TypeError:",
"indices = indices[0:2] section, option = indices if not section in self.config.sections(): return",
"if not section in self.config.sections(): return None if not option in self.config.options(section): return",
"zf.write(src_dir, wn_dir) for fn in listdir(src_dir): zf.write(join(src_dir, fn), join(wn_dir, fn)) zf.close() def unzip_worknote(src_fn,",
"i in index[0:2]]) except TypeError: return unicode(index) def zip_worknote(src_dir, target_fn): from os.path import",
"self.config.get(section, option) try: val = int(val) except ValueError: pass else: return val try:",
"val == 'False': return False elif val == 'True': return True return val",
"else: return val try: val = float(val) except ValueError: pass else: return val",
"return val def __put_item(self, indices, value): indices = indices[0:2] value = str(value) section,",
"'w') zf.write(src_dir, wn_dir) for fn in listdir(src_dir): zf.write(join(src_dir, fn), join(wn_dir, fn)) zf.close() def",
"2015 @author: appel \"\"\" def parse_index(index): from worknote.items import parse_index return parse_index(index)[0:2] def",
"else: makedirs(target_dir) tmpdir = gettempdir() zipfile.extractall(tmpdir) for fn in listdir(join(tmpdir, wn_dir)): move(join(join(tmpdir, wn_dir),",
"section in default_cfg: for option in default_cfg[section]: self.__put_item([section, option], default_cfg[section][option]) self.read_cfg_file() def __getitem__(self,",
"on Wed Sep 2 18:06:23 2015 @author: appel \"\"\" def parse_index(index): from worknote.items",
"join from os import makedirs, listdir from shutil import move from tempfile import",
"import makedirs, listdir from shutil import move from tempfile import gettempdir try: with",
"wn_dir) for fn in listdir(src_dir): zf.write(join(src_dir, fn), join(wn_dir, fn)) zf.close() def unzip_worknote(src_fn, target_dir",
"None): from zipfile import ZipFile, BadZipfile from os.path import split, exists, join from",
"import move from tempfile import gettempdir try: with ZipFile(src_fn, 'r') as zipfile: files",
"tmpdir = gettempdir() zipfile.extractall(tmpdir) for fn in listdir(join(tmpdir, wn_dir)): move(join(join(tmpdir, wn_dir), fn), target_dir)",
"wn_dir)): move(join(join(tmpdir, wn_dir), fn), target_dir) except BadZipfile, e: raise IOError(str(e)) class Configuration(object): def",
"= zipfile.namelist() wn_dir = split(files[0])[0] if target_dir is None: target_dir = wn_dir if",
"move from tempfile import gettempdir try: with ZipFile(src_fn, 'r') as zipfile: files =",
"not default_cfg is None: for section in default_cfg: for option in default_cfg[section]: self.__put_item([section,",
"listdir from zipfile import ZipFile wn_dir = split(src_dir)[1] zf = ZipFile(target_fn, 'w') zf.write(src_dir,",
"indices if not section in self.config.sections(): self.config.add_section(section) if not option in self.config.options(section): self.config.set(section,",
"option, value) def __setitem__(self, indices, value): self.__put_item(indices, value) self.update_cfg_file() def update_cfg_file(self): with open(self.cfg_file,",
"def read_cfg_file(self): from os.path import exists if exists(self.cfg_file): self.config.read(self.cfg_file) def get_sections(self): return self.config.sections()",
"pass else: return val try: val = float(val) except ValueError: pass else: return",
"except ValueError: pass else: return val if val == 'False': return False elif",
"appel \"\"\" def parse_index(index): from worknote.items import parse_index return parse_index(index)[0:2] def gen_index(index): try:",
"except TypeError: return unicode(index) def zip_worknote(src_dir, target_fn): from os.path import split, join from",
"directory already exists') else: makedirs(target_dir) tmpdir = gettempdir() zipfile.extractall(tmpdir) for fn in listdir(join(tmpdir,",
"indices): indices = indices[0:2] section, option = indices if not section in self.config.sections():",
"ValueError: pass else: return val try: val = float(val) except ValueError: pass else:",
"in self.config.options(section): self.config.set(section, option, value) def __setitem__(self, indices, value): self.__put_item(indices, value) self.update_cfg_file() def",
"is None: target_dir = wn_dir if exists(target_dir): raise OSError('The target directory already exists')",
"self.config = SafeConfigParser() if not default_cfg is None: for section in default_cfg: for",
"files = zipfile.namelist() wn_dir = split(files[0])[0] if target_dir is None: target_dir = wn_dir",
"== 'False': return False elif val == 'True': return True return val def",
"\"\"\" Created on Wed Sep 2 18:06:23 2015 @author: appel \"\"\" def parse_index(index):",
"ConfigParser import SafeConfigParser self.cfg_file = cfg_file self.config = SafeConfigParser() if not default_cfg is",
"self.read_cfg_file() def __getitem__(self, indices): indices = indices[0:2] section, option = indices if not",
"self.config.options(section): return None val = self.config.get(section, option) try: val = int(val) except ValueError:",
"indices, value): indices = indices[0:2] value = str(value) section, option = indices if",
"in self.config.sections(): self.config.add_section(section) if not option in self.config.options(section): self.config.set(section, option, value) def __setitem__(self,",
"pass else: return val if val == 'False': return False elif val ==",
"if exists(target_dir): raise OSError('The target directory already exists') else: makedirs(target_dir) tmpdir = gettempdir()",
"= cfg_file self.config = SafeConfigParser() if not default_cfg is None: for section in",
"= str(value) section, option = indices if not section in self.config.sections(): self.config.add_section(section) if",
"raise OSError('The target directory already exists') else: makedirs(target_dir) tmpdir = gettempdir() zipfile.extractall(tmpdir) for",
"Wed Sep 2 18:06:23 2015 @author: appel \"\"\" def parse_index(index): from worknote.items import",
"True return val def __put_item(self, indices, value): indices = indices[0:2] value = str(value)"
] |
[
"Returns: :obj:`int` \"\"\" # Scale features so they fit inside grid bounds num_data",
"inside grid bounds min_val = x.min() max_val = x.max() diff = max_val -",
": (j + 1) * grid_size ** i, :i].copy_(prev_points) prev_points = grid_data[: grid_size",
"(float) Returns: :obj:`torch.Tensor` \"\"\" # Scale features so they fit inside grid bounds",
"* grid_size ** i, i].fill_(grid[j, i]) if prev_points is not None: grid_data[j *",
"max_val = x.max() diff = max_val - min_val x = (x - min_val)",
"upper_bound): \"\"\" Scale the input data so that it lies in between the",
"= torch.zeros(int(pow(grid_size, grid_dim)), grid_dim, device=grid.device) prev_points = None for i in range(grid_dim): for",
"diff) + 0.95 * lower_bound return x def choose_grid_size(train_inputs, ratio=1.0): \"\"\" Given some",
"features so they fit inside grid bounds num_data = train_inputs.numel() if train_inputs.dim() ==",
"the input data so that it lies in between the lower and upper",
"they fit inside grid bounds min_val = x.min() max_val = x.max() diff =",
"max_val - min_val x = (x - min_val) * (0.95 * (upper_bound -",
"so they fit inside grid bounds num_data = train_inputs.numel() if train_inputs.dim() == 1",
"determine a good grid size for KISS-GP. Args: :attr:`train_inputs` (Tensor `n` or `n",
"a good grid size for KISS-GP. Args: :attr:`train_inputs` (Tensor `n` or `n x",
"grid points to the amount of data (default: 1.) Returns: :obj:`int` \"\"\" #",
"* grid_size ** i : (j + 1) * grid_size ** i, :i].copy_(prev_points)",
"range(grid_dim): for j in range(grid_size): grid_data[j * grid_size ** i : (j +",
"else train_inputs.size(-2) num_dim = 1 if train_inputs.dim() == 1 else train_inputs.size(-1) return int(ratio",
"int(ratio * math.pow(num_data, 1.0 / num_dim)) def create_data_from_grid(grid): grid_size = grid.size(-2) grid_dim =",
"grid_size ** i : (j + 1) * grid_size ** i, i].fill_(grid[j, i])",
"grid bounds min_val = x.min() max_val = x.max() diff = max_val - min_val",
"range(grid_size): grid_data[j * grid_size ** i : (j + 1) * grid_size **",
"(Tensor `n` or `n x d` or `b x n x d`): training",
":attr:`train_inputs` (Tensor `n` or `n x d` or `b x n x d`):",
"d`): training data :attr:`ratio` (float, optional): Ratio - number of grid points to",
"lower_bound, upper_bound): \"\"\" Scale the input data so that it lies in between",
"in range(grid_dim): for j in range(grid_size): grid_data[j * grid_size ** i : (j",
"the input :attr:`lower_bound` (float) :attr:`upper_bound` (float) Returns: :obj:`torch.Tensor` \"\"\" # Scale features so",
"good grid size for KISS-GP. Args: :attr:`train_inputs` (Tensor `n` or `n x d`",
"`b x n x d`): training data :attr:`ratio` (float, optional): Ratio - number",
"grid_data[j * grid_size ** i : (j + 1) * grid_size ** i,",
"number of grid points to the amount of data (default: 1.) Returns: :obj:`int`",
"+ 1) * grid_size ** i, :i].copy_(prev_points) prev_points = grid_data[: grid_size ** (i",
": (j + 1) * grid_size ** i, i].fill_(grid[j, i]) if prev_points is",
"grid size for KISS-GP. Args: :attr:`train_inputs` (Tensor `n` or `n x d` or",
"x d`): training data :attr:`ratio` (float, optional): Ratio - number of grid points",
"* grid_size ** i, :i].copy_(prev_points) prev_points = grid_data[: grid_size ** (i + 1),",
"x.min() max_val = x.max() diff = max_val - min_val x = (x -",
"so they fit inside grid bounds min_val = x.min() max_val = x.max() diff",
"bounds. Args: :attr:`x` (Tensor `n` or `b x n`): the input :attr:`lower_bound` (float)",
"grid_dim = grid.size(-1) grid_data = torch.zeros(int(pow(grid_size, grid_dim)), grid_dim, device=grid.device) prev_points = None for",
"prev_points = None for i in range(grid_dim): for j in range(grid_size): grid_data[j *",
"create_data_from_grid(grid): grid_size = grid.size(-2) grid_dim = grid.size(-1) grid_data = torch.zeros(int(pow(grid_size, grid_dim)), grid_dim, device=grid.device)",
"fit inside grid bounds num_data = train_inputs.numel() if train_inputs.dim() == 1 else train_inputs.size(-2)",
":obj:`int` \"\"\" # Scale features so they fit inside grid bounds num_data =",
"+ 1) * grid_size ** i, i].fill_(grid[j, i]) if prev_points is not None:",
"for KISS-GP. Args: :attr:`train_inputs` (Tensor `n` or `n x d` or `b x",
"if train_inputs.dim() == 1 else train_inputs.size(-1) return int(ratio * math.pow(num_data, 1.0 / num_dim))",
"num_dim = 1 if train_inputs.dim() == 1 else train_inputs.size(-1) return int(ratio * math.pow(num_data,",
"torch def scale_to_bounds(x, lower_bound, upper_bound): \"\"\" Scale the input data so that it",
"`n` or `n x d` or `b x n x d`): training data",
"i in range(grid_dim): for j in range(grid_size): grid_data[j * grid_size ** i :",
":i].copy_(prev_points) prev_points = grid_data[: grid_size ** (i + 1), : (i + 1)]",
"* grid_size ** i : (j + 1) * grid_size ** i, i].fill_(grid[j,",
"inputs, determine a good grid size for KISS-GP. Args: :attr:`train_inputs` (Tensor `n` or",
"None for i in range(grid_dim): for j in range(grid_size): grid_data[j * grid_size **",
"bounds min_val = x.min() max_val = x.max() diff = max_val - min_val x",
"= (x - min_val) * (0.95 * (upper_bound - lower_bound) / diff) +",
"= 1 if train_inputs.dim() == 1 else train_inputs.size(-1) return int(ratio * math.pow(num_data, 1.0",
"x = (x - min_val) * (0.95 * (upper_bound - lower_bound) / diff)",
"* (0.95 * (upper_bound - lower_bound) / diff) + 0.95 * lower_bound return",
"of grid points to the amount of data (default: 1.) Returns: :obj:`int` \"\"\"",
"1 else train_inputs.size(-2) num_dim = 1 if train_inputs.dim() == 1 else train_inputs.size(-1) return",
"= None for i in range(grid_dim): for j in range(grid_size): grid_data[j * grid_size",
"grid_size ** i, :i].copy_(prev_points) prev_points = grid_data[: grid_size ** (i + 1), :",
"min_val x = (x - min_val) * (0.95 * (upper_bound - lower_bound) /",
"#!/usr/bin/env python3 import math import torch def scale_to_bounds(x, lower_bound, upper_bound): \"\"\" Scale the",
"amount of data (default: 1.) Returns: :obj:`int` \"\"\" # Scale features so they",
"points to the amount of data (default: 1.) Returns: :obj:`int` \"\"\" # Scale",
"training inputs, determine a good grid size for KISS-GP. Args: :attr:`train_inputs` (Tensor `n`",
"Scale features so they fit inside grid bounds min_val = x.min() max_val =",
"# Scale features so they fit inside grid bounds num_data = train_inputs.numel() if",
"\"\"\" # Scale features so they fit inside grid bounds num_data = train_inputs.numel()",
":attr:`x` (Tensor `n` or `b x n`): the input :attr:`lower_bound` (float) :attr:`upper_bound` (float)",
"to the amount of data (default: 1.) Returns: :obj:`int` \"\"\" # Scale features",
":attr:`ratio` (float, optional): Ratio - number of grid points to the amount of",
"data so that it lies in between the lower and upper bounds. Args:",
"grid_dim, device=grid.device) prev_points = None for i in range(grid_dim): for j in range(grid_size):",
"= grid_data[: grid_size ** (i + 1), : (i + 1)] return grid_data",
"1 if train_inputs.dim() == 1 else train_inputs.size(-1) return int(ratio * math.pow(num_data, 1.0 /",
"math.pow(num_data, 1.0 / num_dim)) def create_data_from_grid(grid): grid_size = grid.size(-2) grid_dim = grid.size(-1) grid_data",
"or `b x n`): the input :attr:`lower_bound` (float) :attr:`upper_bound` (float) Returns: :obj:`torch.Tensor` \"\"\"",
"\"\"\" Given some training inputs, determine a good grid size for KISS-GP. Args:",
"1.) Returns: :obj:`int` \"\"\" # Scale features so they fit inside grid bounds",
"1 else train_inputs.size(-1) return int(ratio * math.pow(num_data, 1.0 / num_dim)) def create_data_from_grid(grid): grid_size",
"* (upper_bound - lower_bound) / diff) + 0.95 * lower_bound return x def",
"inside grid bounds num_data = train_inputs.numel() if train_inputs.dim() == 1 else train_inputs.size(-2) num_dim",
"if train_inputs.dim() == 1 else train_inputs.size(-2) num_dim = 1 if train_inputs.dim() == 1",
"lies in between the lower and upper bounds. Args: :attr:`x` (Tensor `n` or",
"Args: :attr:`x` (Tensor `n` or `b x n`): the input :attr:`lower_bound` (float) :attr:`upper_bound`",
"KISS-GP. Args: :attr:`train_inputs` (Tensor `n` or `n x d` or `b x n",
"(float, optional): Ratio - number of grid points to the amount of data",
"train_inputs.dim() == 1 else train_inputs.size(-1) return int(ratio * math.pow(num_data, 1.0 / num_dim)) def",
"grid_size = grid.size(-2) grid_dim = grid.size(-1) grid_data = torch.zeros(int(pow(grid_size, grid_dim)), grid_dim, device=grid.device) prev_points",
"= max_val - min_val x = (x - min_val) * (0.95 * (upper_bound",
"in between the lower and upper bounds. Args: :attr:`x` (Tensor `n` or `b",
"upper bounds. Args: :attr:`x` (Tensor `n` or `b x n`): the input :attr:`lower_bound`",
"x n x d`): training data :attr:`ratio` (float, optional): Ratio - number of",
"(j + 1) * grid_size ** i, :i].copy_(prev_points) prev_points = grid_data[: grid_size **",
"lower_bound return x def choose_grid_size(train_inputs, ratio=1.0): \"\"\" Given some training inputs, determine a",
"(j + 1) * grid_size ** i, i].fill_(grid[j, i]) if prev_points is not",
"so that it lies in between the lower and upper bounds. Args: :attr:`x`",
"(default: 1.) Returns: :obj:`int` \"\"\" # Scale features so they fit inside grid",
"is not None: grid_data[j * grid_size ** i : (j + 1) *",
"= train_inputs.numel() if train_inputs.dim() == 1 else train_inputs.size(-2) num_dim = 1 if train_inputs.dim()",
"== 1 else train_inputs.size(-2) num_dim = 1 if train_inputs.dim() == 1 else train_inputs.size(-1)",
"(0.95 * (upper_bound - lower_bound) / diff) + 0.95 * lower_bound return x",
"i].fill_(grid[j, i]) if prev_points is not None: grid_data[j * grid_size ** i :",
"i, :i].copy_(prev_points) prev_points = grid_data[: grid_size ** (i + 1), : (i +",
"return x def choose_grid_size(train_inputs, ratio=1.0): \"\"\" Given some training inputs, determine a good",
"that it lies in between the lower and upper bounds. Args: :attr:`x` (Tensor",
"n`): the input :attr:`lower_bound` (float) :attr:`upper_bound` (float) Returns: :obj:`torch.Tensor` \"\"\" # Scale features",
"<filename>gpytorch/utils/grid.py<gh_stars>0 #!/usr/bin/env python3 import math import torch def scale_to_bounds(x, lower_bound, upper_bound): \"\"\" Scale",
"def create_data_from_grid(grid): grid_size = grid.size(-2) grid_dim = grid.size(-1) grid_data = torch.zeros(int(pow(grid_size, grid_dim)), grid_dim,",
"d` or `b x n x d`): training data :attr:`ratio` (float, optional): Ratio",
"* lower_bound return x def choose_grid_size(train_inputs, ratio=1.0): \"\"\" Given some training inputs, determine",
"python3 import math import torch def scale_to_bounds(x, lower_bound, upper_bound): \"\"\" Scale the input",
"(Tensor `n` or `b x n`): the input :attr:`lower_bound` (float) :attr:`upper_bound` (float) Returns:",
"bounds num_data = train_inputs.numel() if train_inputs.dim() == 1 else train_inputs.size(-2) num_dim = 1",
"x n`): the input :attr:`lower_bound` (float) :attr:`upper_bound` (float) Returns: :obj:`torch.Tensor` \"\"\" # Scale",
"Returns: :obj:`torch.Tensor` \"\"\" # Scale features so they fit inside grid bounds min_val",
"n x d`): training data :attr:`ratio` (float, optional): Ratio - number of grid",
"else train_inputs.size(-1) return int(ratio * math.pow(num_data, 1.0 / num_dim)) def create_data_from_grid(grid): grid_size =",
"not None: grid_data[j * grid_size ** i : (j + 1) * grid_size",
"`b x n`): the input :attr:`lower_bound` (float) :attr:`upper_bound` (float) Returns: :obj:`torch.Tensor` \"\"\" #",
"(float) :attr:`upper_bound` (float) Returns: :obj:`torch.Tensor` \"\"\" # Scale features so they fit inside",
"Given some training inputs, determine a good grid size for KISS-GP. Args: :attr:`train_inputs`",
"torch.zeros(int(pow(grid_size, grid_dim)), grid_dim, device=grid.device) prev_points = None for i in range(grid_dim): for j",
"train_inputs.size(-1) return int(ratio * math.pow(num_data, 1.0 / num_dim)) def create_data_from_grid(grid): grid_size = grid.size(-2)",
"i, i].fill_(grid[j, i]) if prev_points is not None: grid_data[j * grid_size ** i",
"None: grid_data[j * grid_size ** i : (j + 1) * grid_size **",
"grid_size ** i : (j + 1) * grid_size ** i, :i].copy_(prev_points) prev_points",
"input :attr:`lower_bound` (float) :attr:`upper_bound` (float) Returns: :obj:`torch.Tensor` \"\"\" # Scale features so they",
"diff = max_val - min_val x = (x - min_val) * (0.95 *",
"i : (j + 1) * grid_size ** i, i].fill_(grid[j, i]) if prev_points",
"Ratio - number of grid points to the amount of data (default: 1.)",
"- min_val) * (0.95 * (upper_bound - lower_bound) / diff) + 0.95 *",
":attr:`upper_bound` (float) Returns: :obj:`torch.Tensor` \"\"\" # Scale features so they fit inside grid",
"grid_dim)), grid_dim, device=grid.device) prev_points = None for i in range(grid_dim): for j in",
"if prev_points is not None: grid_data[j * grid_size ** i : (j +",
"1) * grid_size ** i, i].fill_(grid[j, i]) if prev_points is not None: grid_data[j",
"math import torch def scale_to_bounds(x, lower_bound, upper_bound): \"\"\" Scale the input data so",
"lower_bound) / diff) + 0.95 * lower_bound return x def choose_grid_size(train_inputs, ratio=1.0): \"\"\"",
"(x - min_val) * (0.95 * (upper_bound - lower_bound) / diff) + 0.95",
"Args: :attr:`train_inputs` (Tensor `n` or `n x d` or `b x n x",
"device=grid.device) prev_points = None for i in range(grid_dim): for j in range(grid_size): grid_data[j",
"num_dim)) def create_data_from_grid(grid): grid_size = grid.size(-2) grid_dim = grid.size(-1) grid_data = torch.zeros(int(pow(grid_size, grid_dim)),",
"for i in range(grid_dim): for j in range(grid_size): grid_data[j * grid_size ** i",
"import math import torch def scale_to_bounds(x, lower_bound, upper_bound): \"\"\" Scale the input data",
"size for KISS-GP. Args: :attr:`train_inputs` (Tensor `n` or `n x d` or `b",
"i : (j + 1) * grid_size ** i, :i].copy_(prev_points) prev_points = grid_data[:",
"lower and upper bounds. Args: :attr:`x` (Tensor `n` or `b x n`): the",
"0.95 * lower_bound return x def choose_grid_size(train_inputs, ratio=1.0): \"\"\" Given some training inputs,",
"ratio=1.0): \"\"\" Given some training inputs, determine a good grid size for KISS-GP.",
"\"\"\" Scale the input data so that it lies in between the lower",
"- lower_bound) / diff) + 0.95 * lower_bound return x def choose_grid_size(train_inputs, ratio=1.0):",
"`n x d` or `b x n x d`): training data :attr:`ratio` (float,",
"1.0 / num_dim)) def create_data_from_grid(grid): grid_size = grid.size(-2) grid_dim = grid.size(-1) grid_data =",
"grid_data = torch.zeros(int(pow(grid_size, grid_dim)), grid_dim, device=grid.device) prev_points = None for i in range(grid_dim):",
"for j in range(grid_size): grid_data[j * grid_size ** i : (j + 1)",
"= grid.size(-1) grid_data = torch.zeros(int(pow(grid_size, grid_dim)), grid_dim, device=grid.device) prev_points = None for i",
"train_inputs.dim() == 1 else train_inputs.size(-2) num_dim = 1 if train_inputs.dim() == 1 else",
"`n` or `b x n`): the input :attr:`lower_bound` (float) :attr:`upper_bound` (float) Returns: :obj:`torch.Tensor`",
"choose_grid_size(train_inputs, ratio=1.0): \"\"\" Given some training inputs, determine a good grid size for",
"def scale_to_bounds(x, lower_bound, upper_bound): \"\"\" Scale the input data so that it lies",
"min_val = x.min() max_val = x.max() diff = max_val - min_val x =",
"= x.max() diff = max_val - min_val x = (x - min_val) *",
"optional): Ratio - number of grid points to the amount of data (default:",
":attr:`lower_bound` (float) :attr:`upper_bound` (float) Returns: :obj:`torch.Tensor` \"\"\" # Scale features so they fit",
"min_val) * (0.95 * (upper_bound - lower_bound) / diff) + 0.95 * lower_bound",
"prev_points is not None: grid_data[j * grid_size ** i : (j + 1)",
"/ num_dim)) def create_data_from_grid(grid): grid_size = grid.size(-2) grid_dim = grid.size(-1) grid_data = torch.zeros(int(pow(grid_size,",
"Scale the input data so that it lies in between the lower and",
"of data (default: 1.) Returns: :obj:`int` \"\"\" # Scale features so they fit",
"fit inside grid bounds min_val = x.min() max_val = x.max() diff = max_val",
"import torch def scale_to_bounds(x, lower_bound, upper_bound): \"\"\" Scale the input data so that",
"grid.size(-2) grid_dim = grid.size(-1) grid_data = torch.zeros(int(pow(grid_size, grid_dim)), grid_dim, device=grid.device) prev_points = None",
"/ diff) + 0.95 * lower_bound return x def choose_grid_size(train_inputs, ratio=1.0): \"\"\" Given",
"return int(ratio * math.pow(num_data, 1.0 / num_dim)) def create_data_from_grid(grid): grid_size = grid.size(-2) grid_dim",
"1) * grid_size ** i, :i].copy_(prev_points) prev_points = grid_data[: grid_size ** (i +",
"prev_points = grid_data[: grid_size ** (i + 1), : (i + 1)] return",
"it lies in between the lower and upper bounds. Args: :attr:`x` (Tensor `n`",
"in range(grid_size): grid_data[j * grid_size ** i : (j + 1) * grid_size",
":obj:`torch.Tensor` \"\"\" # Scale features so they fit inside grid bounds min_val =",
"grid bounds num_data = train_inputs.numel() if train_inputs.dim() == 1 else train_inputs.size(-2) num_dim =",
"** i, :i].copy_(prev_points) prev_points = grid_data[: grid_size ** (i + 1), : (i",
"train_inputs.size(-2) num_dim = 1 if train_inputs.dim() == 1 else train_inputs.size(-1) return int(ratio *",
"input data so that it lies in between the lower and upper bounds.",
"x d` or `b x n x d`): training data :attr:`ratio` (float, optional):",
"grid.size(-1) grid_data = torch.zeros(int(pow(grid_size, grid_dim)), grid_dim, device=grid.device) prev_points = None for i in",
"data :attr:`ratio` (float, optional): Ratio - number of grid points to the amount",
"= grid.size(-2) grid_dim = grid.size(-1) grid_data = torch.zeros(int(pow(grid_size, grid_dim)), grid_dim, device=grid.device) prev_points =",
"data (default: 1.) Returns: :obj:`int` \"\"\" # Scale features so they fit inside",
"grid_size ** i, i].fill_(grid[j, i]) if prev_points is not None: grid_data[j * grid_size",
"num_data = train_inputs.numel() if train_inputs.dim() == 1 else train_inputs.size(-2) num_dim = 1 if",
"j in range(grid_size): grid_data[j * grid_size ** i : (j + 1) *",
"they fit inside grid bounds num_data = train_inputs.numel() if train_inputs.dim() == 1 else",
"+ 0.95 * lower_bound return x def choose_grid_size(train_inputs, ratio=1.0): \"\"\" Given some training",
"and upper bounds. Args: :attr:`x` (Tensor `n` or `b x n`): the input",
"= x.min() max_val = x.max() diff = max_val - min_val x = (x",
"x.max() diff = max_val - min_val x = (x - min_val) * (0.95",
"the amount of data (default: 1.) Returns: :obj:`int` \"\"\" # Scale features so",
"the lower and upper bounds. Args: :attr:`x` (Tensor `n` or `b x n`):",
"some training inputs, determine a good grid size for KISS-GP. Args: :attr:`train_inputs` (Tensor",
"or `b x n x d`): training data :attr:`ratio` (float, optional): Ratio -",
"- min_val x = (x - min_val) * (0.95 * (upper_bound - lower_bound)",
"Scale features so they fit inside grid bounds num_data = train_inputs.numel() if train_inputs.dim()",
"i]) if prev_points is not None: grid_data[j * grid_size ** i : (j",
"** i : (j + 1) * grid_size ** i, i].fill_(grid[j, i]) if",
"def choose_grid_size(train_inputs, ratio=1.0): \"\"\" Given some training inputs, determine a good grid size",
"training data :attr:`ratio` (float, optional): Ratio - number of grid points to the",
"scale_to_bounds(x, lower_bound, upper_bound): \"\"\" Scale the input data so that it lies in",
"between the lower and upper bounds. Args: :attr:`x` (Tensor `n` or `b x",
"\"\"\" # Scale features so they fit inside grid bounds min_val = x.min()",
"- number of grid points to the amount of data (default: 1.) Returns:",
"== 1 else train_inputs.size(-1) return int(ratio * math.pow(num_data, 1.0 / num_dim)) def create_data_from_grid(grid):",
"** i, i].fill_(grid[j, i]) if prev_points is not None: grid_data[j * grid_size **",
"or `n x d` or `b x n x d`): training data :attr:`ratio`",
"features so they fit inside grid bounds min_val = x.min() max_val = x.max()",
"** i : (j + 1) * grid_size ** i, :i].copy_(prev_points) prev_points =",
"* math.pow(num_data, 1.0 / num_dim)) def create_data_from_grid(grid): grid_size = grid.size(-2) grid_dim = grid.size(-1)",
"train_inputs.numel() if train_inputs.dim() == 1 else train_inputs.size(-2) num_dim = 1 if train_inputs.dim() ==",
"(upper_bound - lower_bound) / diff) + 0.95 * lower_bound return x def choose_grid_size(train_inputs,",
"x def choose_grid_size(train_inputs, ratio=1.0): \"\"\" Given some training inputs, determine a good grid",
"# Scale features so they fit inside grid bounds min_val = x.min() max_val"
] |
[
"try: print('3' * 15) print('result={}'.format(result)) a = f.send(result) print('4' * 15) apply_async(a.func, a.args,",
"StopIteration: break return wrapper def add(x, y): return x + y @inlined_async def",
"inlined_async(func): @wraps(func) def wrapper(*args): f = func(*args) result_queue = Queue() result_queue.put(None) while True:",
"def test(): print('start'.center(20, '=')) r = yield Async(add, (2, 3)) print('last={}'.format(r)) r =",
"('hello', 'world')) print('last={}'.format(r)) # for n in range(10): # r = yield Async(add,",
"Async(add, ('hello', 'world')) print('last={}'.format(r)) # for n in range(10): # r = yield",
"r = yield Async(add, (n, n)) # print(r) # print('Goodbye') print('end'.center(20, '=')) if",
"def __init__(self, func, args): self.func = func self.args = args def inlined_async(func): @wraps(func)",
"a = f.send(result) print('4' * 15) apply_async(a.func, a.args, callback=result_queue.put) print('5' * 15) except",
"for n in range(10): # r = yield Async(add, (n, n)) # print(r)",
"class Async: def __init__(self, func, args): self.func = func self.args = args def",
"self.args = args def inlined_async(func): @wraps(func) def wrapper(*args): f = func(*args) result_queue =",
"a.args, callback=result_queue.put) print('5' * 15) except StopIteration: break return wrapper def add(x, y):",
"wrapper(*args): f = func(*args) result_queue = Queue() result_queue.put(None) while True: print('1' * 15)",
"<reponame>Xiao-jiuguan/python3-cookbook #!/usr/bin/env python # -*- encoding: utf-8 -*- \"\"\" Topic: 内联回调函数 Desc :",
"result_queue.get() print('2' * 15) try: print('3' * 15) print('result={}'.format(result)) a = f.send(result) print('4'",
"= result_queue.get() print('2' * 15) try: print('3' * 15) print('result={}'.format(result)) a = f.send(result)",
"\"\"\" from queue import Queue from functools import wraps def apply_async(func, args, *,",
"@wraps(func) def wrapper(*args): f = func(*args) result_queue = Queue() result_queue.put(None) while True: print('1'",
"self.func = func self.args = args def inlined_async(func): @wraps(func) def wrapper(*args): f =",
"15) try: print('3' * 15) print('result={}'.format(result)) a = f.send(result) print('4' * 15) apply_async(a.func,",
"import Queue from functools import wraps def apply_async(func, args, *, callback): # Compute",
"Queue from functools import wraps def apply_async(func, args, *, callback): # Compute the",
"yield Async(add, (2, 3)) print('last={}'.format(r)) r = yield Async(add, ('hello', 'world')) print('last={}'.format(r)) #",
"result result = func(*args) # Invoke the callback with the result callback(result) class",
"True: print('1' * 15) result = result_queue.get() print('2' * 15) try: print('3' *",
"func self.args = args def inlined_async(func): @wraps(func) def wrapper(*args): f = func(*args) result_queue",
"y @inlined_async def test(): print('start'.center(20, '=')) r = yield Async(add, (2, 3)) print('last={}'.format(r))",
"(2, 3)) print('last={}'.format(r)) r = yield Async(add, ('hello', 'world')) print('last={}'.format(r)) # for n",
"= func self.args = args def inlined_async(func): @wraps(func) def wrapper(*args): f = func(*args)",
"'world')) print('last={}'.format(r)) # for n in range(10): # r = yield Async(add, (n,",
"* 15) try: print('3' * 15) print('result={}'.format(result)) a = f.send(result) print('4' * 15)",
"def wrapper(*args): f = func(*args) result_queue = Queue() result_queue.put(None) while True: print('1' *",
"15) except StopIteration: break return wrapper def add(x, y): return x + y",
"-*- \"\"\" Topic: 内联回调函数 Desc : \"\"\" from queue import Queue from functools",
"# Invoke the callback with the result callback(result) class Async: def __init__(self, func,",
"+ y @inlined_async def test(): print('start'.center(20, '=')) r = yield Async(add, (2, 3))",
"print('5' * 15) except StopIteration: break return wrapper def add(x, y): return x",
"utf-8 -*- \"\"\" Topic: 内联回调函数 Desc : \"\"\" from queue import Queue from",
"callback): # Compute the result result = func(*args) # Invoke the callback with",
"@inlined_async def test(): print('start'.center(20, '=')) r = yield Async(add, (2, 3)) print('last={}'.format(r)) r",
"callback=result_queue.put) print('5' * 15) except StopIteration: break return wrapper def add(x, y): return",
"f.send(result) print('4' * 15) apply_async(a.func, a.args, callback=result_queue.put) print('5' * 15) except StopIteration: break",
"def apply_async(func, args, *, callback): # Compute the result result = func(*args) #",
"result callback(result) class Async: def __init__(self, func, args): self.func = func self.args =",
"# r = yield Async(add, (n, n)) # print(r) # print('Goodbye') print('end'.center(20, '='))",
"# Compute the result result = func(*args) # Invoke the callback with the",
"encoding: utf-8 -*- \"\"\" Topic: 内联回调函数 Desc : \"\"\" from queue import Queue",
"= func(*args) result_queue = Queue() result_queue.put(None) while True: print('1' * 15) result =",
"x + y @inlined_async def test(): print('start'.center(20, '=')) r = yield Async(add, (2,",
"-*- encoding: utf-8 -*- \"\"\" Topic: 内联回调函数 Desc : \"\"\" from queue import",
"15) print('result={}'.format(result)) a = f.send(result) print('4' * 15) apply_async(a.func, a.args, callback=result_queue.put) print('5' *",
"r = yield Async(add, ('hello', 'world')) print('last={}'.format(r)) # for n in range(10): #",
"wrapper def add(x, y): return x + y @inlined_async def test(): print('start'.center(20, '='))",
"'=')) r = yield Async(add, (2, 3)) print('last={}'.format(r)) r = yield Async(add, ('hello',",
"y): return x + y @inlined_async def test(): print('start'.center(20, '=')) r = yield",
"print('4' * 15) apply_async(a.func, a.args, callback=result_queue.put) print('5' * 15) except StopIteration: break return",
"with the result callback(result) class Async: def __init__(self, func, args): self.func = func",
"# for n in range(10): # r = yield Async(add, (n, n)) #",
"test(): print('start'.center(20, '=')) r = yield Async(add, (2, 3)) print('last={}'.format(r)) r = yield",
"while True: print('1' * 15) result = result_queue.get() print('2' * 15) try: print('3'",
"= yield Async(add, ('hello', 'world')) print('last={}'.format(r)) # for n in range(10): # r",
"python # -*- encoding: utf-8 -*- \"\"\" Topic: 内联回调函数 Desc : \"\"\" from",
"15) apply_async(a.func, a.args, callback=result_queue.put) print('5' * 15) except StopIteration: break return wrapper def",
"func(*args) # Invoke the callback with the result callback(result) class Async: def __init__(self,",
"the callback with the result callback(result) class Async: def __init__(self, func, args): self.func",
"the result callback(result) class Async: def __init__(self, func, args): self.func = func self.args",
"from queue import Queue from functools import wraps def apply_async(func, args, *, callback):",
"__init__(self, func, args): self.func = func self.args = args def inlined_async(func): @wraps(func) def",
"callback(result) class Async: def __init__(self, func, args): self.func = func self.args = args",
"add(x, y): return x + y @inlined_async def test(): print('start'.center(20, '=')) r =",
"result_queue.put(None) while True: print('1' * 15) result = result_queue.get() print('2' * 15) try:",
"apply_async(func, args, *, callback): # Compute the result result = func(*args) # Invoke",
"args, *, callback): # Compute the result result = func(*args) # Invoke the",
"内联回调函数 Desc : \"\"\" from queue import Queue from functools import wraps def",
"Topic: 内联回调函数 Desc : \"\"\" from queue import Queue from functools import wraps",
"args def inlined_async(func): @wraps(func) def wrapper(*args): f = func(*args) result_queue = Queue() result_queue.put(None)",
"return wrapper def add(x, y): return x + y @inlined_async def test(): print('start'.center(20,",
"print('last={}'.format(r)) r = yield Async(add, ('hello', 'world')) print('last={}'.format(r)) # for n in range(10):",
"args): self.func = func self.args = args def inlined_async(func): @wraps(func) def wrapper(*args): f",
"from functools import wraps def apply_async(func, args, *, callback): # Compute the result",
"* 15) apply_async(a.func, a.args, callback=result_queue.put) print('5' * 15) except StopIteration: break return wrapper",
": \"\"\" from queue import Queue from functools import wraps def apply_async(func, args,",
"print('2' * 15) try: print('3' * 15) print('result={}'.format(result)) a = f.send(result) print('4' *",
"Async(add, (n, n)) # print(r) # print('Goodbye') print('end'.center(20, '=')) if __name__ == '__main__':",
"functools import wraps def apply_async(func, args, *, callback): # Compute the result result",
"15) result = result_queue.get() print('2' * 15) try: print('3' * 15) print('result={}'.format(result)) a",
"\"\"\" Topic: 内联回调函数 Desc : \"\"\" from queue import Queue from functools import",
"= Queue() result_queue.put(None) while True: print('1' * 15) result = result_queue.get() print('2' *",
"Compute the result result = func(*args) # Invoke the callback with the result",
"def inlined_async(func): @wraps(func) def wrapper(*args): f = func(*args) result_queue = Queue() result_queue.put(None) while",
"result_queue = Queue() result_queue.put(None) while True: print('1' * 15) result = result_queue.get() print('2'",
"print('1' * 15) result = result_queue.get() print('2' * 15) try: print('3' * 15)",
"wraps def apply_async(func, args, *, callback): # Compute the result result = func(*args)",
"print('start'.center(20, '=')) r = yield Async(add, (2, 3)) print('last={}'.format(r)) r = yield Async(add,",
"print('result={}'.format(result)) a = f.send(result) print('4' * 15) apply_async(a.func, a.args, callback=result_queue.put) print('5' * 15)",
"the result result = func(*args) # Invoke the callback with the result callback(result)",
"Invoke the callback with the result callback(result) class Async: def __init__(self, func, args):",
"yield Async(add, ('hello', 'world')) print('last={}'.format(r)) # for n in range(10): # r =",
"# -*- encoding: utf-8 -*- \"\"\" Topic: 内联回调函数 Desc : \"\"\" from queue",
"= yield Async(add, (2, 3)) print('last={}'.format(r)) r = yield Async(add, ('hello', 'world')) print('last={}'.format(r))",
"*, callback): # Compute the result result = func(*args) # Invoke the callback",
"queue import Queue from functools import wraps def apply_async(func, args, *, callback): #",
"apply_async(a.func, a.args, callback=result_queue.put) print('5' * 15) except StopIteration: break return wrapper def add(x,",
"callback with the result callback(result) class Async: def __init__(self, func, args): self.func =",
"func(*args) result_queue = Queue() result_queue.put(None) while True: print('1' * 15) result = result_queue.get()",
"= args def inlined_async(func): @wraps(func) def wrapper(*args): f = func(*args) result_queue = Queue()",
"* 15) result = result_queue.get() print('2' * 15) try: print('3' * 15) print('result={}'.format(result))",
"Async(add, (2, 3)) print('last={}'.format(r)) r = yield Async(add, ('hello', 'world')) print('last={}'.format(r)) # for",
"print('last={}'.format(r)) # for n in range(10): # r = yield Async(add, (n, n))",
"= f.send(result) print('4' * 15) apply_async(a.func, a.args, callback=result_queue.put) print('5' * 15) except StopIteration:",
"n in range(10): # r = yield Async(add, (n, n)) # print(r) #",
"func, args): self.func = func self.args = args def inlined_async(func): @wraps(func) def wrapper(*args):",
"def add(x, y): return x + y @inlined_async def test(): print('start'.center(20, '=')) r",
"r = yield Async(add, (2, 3)) print('last={}'.format(r)) r = yield Async(add, ('hello', 'world'))",
"(n, n)) # print(r) # print('Goodbye') print('end'.center(20, '=')) if __name__ == '__main__': test()",
"#!/usr/bin/env python # -*- encoding: utf-8 -*- \"\"\" Topic: 内联回调函数 Desc : \"\"\"",
"range(10): # r = yield Async(add, (n, n)) # print(r) # print('Goodbye') print('end'.center(20,",
"import wraps def apply_async(func, args, *, callback): # Compute the result result =",
"= func(*args) # Invoke the callback with the result callback(result) class Async: def",
"f = func(*args) result_queue = Queue() result_queue.put(None) while True: print('1' * 15) result",
"in range(10): # r = yield Async(add, (n, n)) # print(r) # print('Goodbye')",
"except StopIteration: break return wrapper def add(x, y): return x + y @inlined_async",
"3)) print('last={}'.format(r)) r = yield Async(add, ('hello', 'world')) print('last={}'.format(r)) # for n in",
"break return wrapper def add(x, y): return x + y @inlined_async def test():",
"result = result_queue.get() print('2' * 15) try: print('3' * 15) print('result={}'.format(result)) a =",
"Desc : \"\"\" from queue import Queue from functools import wraps def apply_async(func,",
"print('3' * 15) print('result={}'.format(result)) a = f.send(result) print('4' * 15) apply_async(a.func, a.args, callback=result_queue.put)",
"Async: def __init__(self, func, args): self.func = func self.args = args def inlined_async(func):",
"= yield Async(add, (n, n)) # print(r) # print('Goodbye') print('end'.center(20, '=')) if __name__",
"return x + y @inlined_async def test(): print('start'.center(20, '=')) r = yield Async(add,",
"Queue() result_queue.put(None) while True: print('1' * 15) result = result_queue.get() print('2' * 15)",
"yield Async(add, (n, n)) # print(r) # print('Goodbye') print('end'.center(20, '=')) if __name__ ==",
"* 15) print('result={}'.format(result)) a = f.send(result) print('4' * 15) apply_async(a.func, a.args, callback=result_queue.put) print('5'",
"* 15) except StopIteration: break return wrapper def add(x, y): return x +",
"result = func(*args) # Invoke the callback with the result callback(result) class Async:"
] |
[
"re.subn(\"<.*/>\", x[1], x[0])[0]), \"axis\":1})) return self def with_capitalisation_by_ner(self): self.transformations.append((\"apply\", {\"func\": (lambda x: self._capitalisation_by_ner(x))}))",
"# lowercase text \"no_line_breaks\":True, # fully strip line breaks as opposed to only",
"def __getitem__(self, idx): item = {key: torch.tensor(val[idx]) for key, val in self.x_train.items()} item['labels']",
"def PreprocessorBuilder(): return Preprocessor() def __init__(self): self.transformations = [] self.text_processor = TextPreProcessor( fix_html=True,",
"with a special token \"no_emails\":False, # replace all email addresses with a special",
"\"no_phone_numbers\":False, # replace all phone numbers with a special token \"no_numbers\":False, # replace",
"edited_row.append(tok.text) else: edited_row.append(tok.text.lower()) return ' '.join(edited_row) def with_word_replacement(self): self.transformations.append((\"apply\", {\"func\": (lambda x: re.subn(\"<.*/>\",",
"(?P<one>\\w*'\\w+)\", \"repl\": (lambda x: x.group(\"one\"))})) return self def with_spell_check(self): self.transformations.append((\"apply\", {\"func\": (lambda x:",
"Preprocessor: @staticmethod def PreprocessorBuilder(): return Preprocessor() def __init__(self): self.transformations = [] self.text_processor =",
"(can't -> can not) spell_correct=True, # spell correction for elongated words ) self.punct",
"with_capitalisation_by_ner(self): self.transformations.append((\"apply\", {\"func\": (lambda x: self._capitalisation_by_ner(x))})) return self def with_joining_contraction_tokens(self): self.transformations.append((\"str.replace\", {\"pat\": \"",
"spacy.load('en_core_web_sm') class Task1Dataset(Dataset): def __init__(self, train_data, labels): self.x_train = train_data self.y_train = labels",
"torch.tensor(self.y_train[idx], dtype=torch.float) return item class Preprocessor: @staticmethod def PreprocessorBuilder(): return Preprocessor() def __init__(self):",
"a special token \"no_currency_symbols\":True, # replace all currency symbols with a special token",
"with_word_replacement(self): self.transformations.append((\"apply\", {\"func\": (lambda x: re.subn(\"<.*/>\", x[1], x[0])[0]), \"axis\":1})) return self def with_capitalisation_by_ner(self):",
"all email addresses with a special token \"no_phone_numbers\":False, # replace all phone numbers",
"class Preprocessor: @staticmethod def PreprocessorBuilder(): return Preprocessor() def __init__(self): self.transformations = [] self.text_processor",
"x: self.text_processor.pre_process_doc(x))})) return self def with_space_after_hashtags(self): self.transformations.append((\"str.replace\", {\"pat\": \"#\", \"repl\": \"# \"})) return",
"\"no_numbers\":False, # replace all numbers with a special token \"no_digits\":False, # replace all",
"in entities: edited_row.append(tok.text) else: edited_row.append(tok.text.lower()) return ' '.join(edited_row) def with_word_replacement(self): self.transformations.append((\"apply\", {\"func\": (lambda",
"token \"no_emails\":False, # replace all email addresses with a special token \"no_phone_numbers\":False, #",
"def build(self): return self def preprocess(self, df, clean_col_name='edited_sentence'): _df = pd.DataFrame(index=df.index, columns=[clean_col_name, 'meanGrade'])",
"used # for spell correction corrector=\"english\", unpack_hashtags=False, # perform word segmentation on hashtags",
"self.text_processor.pre_process_doc(x))})) return self def with_space_after_hashtags(self): self.transformations.append((\"str.replace\", {\"pat\": \"#\", \"repl\": \"# \"})) return self",
"'meanGrade']) _df['meanGrade'] = df.meanGrade transformed_cols = df[['original', 'edit']] for (func, params) in self.transformations:",
"import Dataset # Params for clean_text_param = { \"lower\":False, # lowercase text \"no_line_breaks\":True,",
"return self def preprocess(self, df, clean_col_name='edited_sentence'): _df = pd.DataFrame(index=df.index, columns=[clean_col_name, 'meanGrade']) _df['meanGrade'] =",
"nlp = spacy.load('en_core_web_sm') class Task1Dataset(Dataset): def __init__(self, train_data, labels): self.x_train = train_data self.y_train",
"def _capitalisation_by_ner(self, sentence, entities=['GPE', 'ORG', 'NORP', 'PERSON']): edited_row = [] trial_doc = self.nlp(sentence)",
"breaks as opposed to only normalizing them \"no_urls\":False, # replace all URLs with",
"spell correction for elongated words ) self.punct = \"[\\.,:;\\(\\)\\[\\]@\\-\\$£]\" nltk.download('stopwords') self.stops = stopwords.words('english')",
"{key: torch.tensor(val[idx]) for key, val in self.x_train.items()} item['labels'] = torch.tensor(self.y_train[idx], dtype=torch.float) return item",
"Task1Dataset(Dataset): def __init__(self, train_data, labels): self.x_train = train_data self.y_train = labels def __len__(self):",
"from which the word statistics are going to be used # for word",
"perform word segmentation on hashtags unpack_contractions=False, # Unpack contractions (can't -> can not)",
"= self.nlp(sentence) for tok in trial_doc: if tok.ent_type_ in entities: edited_row.append(tok.text) else: edited_row.append(tok.text.lower())",
"with a special token \"no_digits\":False, # replace all digits with a special token",
"transformed_cols for f in func.split(\".\"): print(f) func_to_apply = getattr(func_to_apply, f) transformed_cols = func_to_apply(**params)",
"# corpus from which the word statistics are going to be used #",
"removing punctuations you may replace them \"replace_with_number\":\"\", \"replace_with_digit\":\"\", \"replace_with_currency_symbol\":\"\", \"lang\":\"en\" # set to",
"return self def with_spell_check(self): self.transformations.append((\"apply\", {\"func\": (lambda x: self.text_processor.pre_process_doc(x))})) return self def with_space_after_hashtags(self):",
"def with_joining_contraction_tokens(self): self.transformations.append((\"str.replace\", {\"pat\": \" (?P<one>\\w*'\\w+)\", \"repl\": (lambda x: x.group(\"one\"))})) return self def",
"all URLs with a special token \"no_emails\":False, # replace all email addresses with",
"(lambda x: self._capitalisation_by_ner(x))})) return self def with_joining_contraction_tokens(self): self.transformations.append((\"str.replace\", {\"pat\": \" (?P<one>\\w*'\\w+)\", \"repl\": (lambda",
"replace them \"replace_with_number\":\"\", \"replace_with_digit\":\"\", \"replace_with_currency_symbol\":\"\", \"lang\":\"en\" # set to 'de' for German special",
"set to 'de' for German special handling } nlp = spacy.load('en_core_web_sm') class Task1Dataset(Dataset):",
"statistics are going to be used # for word segmentation segmenter=\"english\", # corpus",
"self.transformations.append((\"str.replace\", {\"pat\": \"'s\", \"repl\": \"\"})) return self def with_punct_removal(self): self.transformations.append((\"str.replace\", {\"pat\": self.punct, \"repl\":",
"\"no_punct\":True, # remove punctuations \"replace_with_punct\":\"\", # instead of removing punctuations you may replace",
"\"lang\":\"en\" # set to 'de' for German special handling } nlp = spacy.load('en_core_web_sm')",
"f in func.split(\".\"): print(f) func_to_apply = getattr(func_to_apply, f) transformed_cols = func_to_apply(**params) _df[clean_col_name] =",
"= pd.DataFrame(index=df.index, columns=[clean_col_name, 'meanGrade']) _df['meanGrade'] = df.meanGrade transformed_cols = df[['original', 'edit']] for (func,",
"self.punct, \"repl\": \"'\"})) return self def with_digit_removal(self): self.transformations.append((\"str.replace\", {\"pat\": \"[0-9]\", \"repl\": \"\"})) return",
"self def with_ascii_quotes_replacement(self): self.transformations.append((\"str.replace\", {\"pat\": \"[‘’]\", \"repl\": \"'\"})) return self def with_possessive_elimination(self): self.transformations.append((\"str.replace\",",
"# Unpack contractions (can't -> can not) spell_correct=True, # spell correction for elongated",
"df[['original', 'edit']] for (func, params) in self.transformations: func_to_apply = transformed_cols for f in",
"Dataset # Params for clean_text_param = { \"lower\":False, # lowercase text \"no_line_breaks\":True, #",
"currency symbols with a special token \"no_punct\":True, # remove punctuations \"replace_with_punct\":\"\", # instead",
"'ORG', 'NORP', 'PERSON']): edited_row = [] trial_doc = self.nlp(sentence) for tok in trial_doc:",
"\".join([w for w in x.split(\" \") if w not in self.stops]))})) return self",
"with a special token \"no_punct\":True, # remove punctuations \"replace_with_punct\":\"\", # instead of removing",
"w not in self.stops]))})) return self def build(self): return self def preprocess(self, df,",
"token \"no_numbers\":False, # replace all numbers with a special token \"no_digits\":False, # replace",
"all currency symbols with a special token \"no_punct\":True, # remove punctuations \"replace_with_punct\":\"\", #",
"torch.tensor(val[idx]) for key, val in self.x_train.items()} item['labels'] = torch.tensor(self.y_train[idx], dtype=torch.float) return item class",
"\"[\\.,:;\\(\\)\\[\\]@\\-\\$£]\" nltk.download('stopwords') self.stops = stopwords.words('english') self.nlp = spacy.load('en_core_web_lg') def _capitalisation_by_ner(self, sentence, entities=['GPE', 'ORG',",
"self._capitalisation_by_ner(x))})) return self def with_joining_contraction_tokens(self): self.transformations.append((\"str.replace\", {\"pat\": \" (?P<one>\\w*'\\w+)\", \"repl\": (lambda x: x.group(\"one\"))}))",
"(lambda x: \" \".join([w for w in x.split(\" \") if w not in",
"return len(self.y_train) def __getitem__(self, idx): item = {key: torch.tensor(val[idx]) for key, val in",
"self.punct = \"[\\.,:;\\(\\)\\[\\]@\\-\\$£]\" nltk.download('stopwords') self.stops = stopwords.words('english') self.nlp = spacy.load('en_core_web_lg') def _capitalisation_by_ner(self, sentence,",
"in trial_doc: if tok.ent_type_ in entities: edited_row.append(tok.text) else: edited_row.append(tok.text.lower()) return ' '.join(edited_row) def",
"word statistics are going to be used # for spell correction corrector=\"english\", unpack_hashtags=False,",
"# fully strip line breaks as opposed to only normalizing them \"no_urls\":False, #",
"val in self.x_train.items()} item['labels'] = torch.tensor(self.y_train[idx], dtype=torch.float) return item class Preprocessor: @staticmethod def",
"segmenter=\"english\", # corpus from which the word statistics are going to be used",
"print(f) func_to_apply = getattr(func_to_apply, f) transformed_cols = func_to_apply(**params) _df[clean_col_name] = transformed_cols return _df,",
"item class Preprocessor: @staticmethod def PreprocessorBuilder(): return Preprocessor() def __init__(self): self.transformations = []",
"{\"func\": (lambda x: re.subn(\"<.*/>\", x[1], x[0])[0]), \"axis\":1})) return self def with_capitalisation_by_ner(self): self.transformations.append((\"apply\", {\"func\":",
"transformed_cols = df[['original', 'edit']] for (func, params) in self.transformations: func_to_apply = transformed_cols for",
"# replace all URLs with a special token \"no_emails\":False, # replace all email",
"segmentation on hashtags unpack_contractions=False, # Unpack contractions (can't -> can not) spell_correct=True, #",
"in self.x_train.items()} item['labels'] = torch.tensor(self.y_train[idx], dtype=torch.float) return item class Preprocessor: @staticmethod def PreprocessorBuilder():",
"'PERSON']): edited_row = [] trial_doc = self.nlp(sentence) for tok in trial_doc: if tok.ent_type_",
"spacy.load('en_core_web_lg') def _capitalisation_by_ner(self, sentence, entities=['GPE', 'ORG', 'NORP', 'PERSON']): edited_row = [] trial_doc =",
"# replace all currency symbols with a special token \"no_punct\":True, # remove punctuations",
"\"\"})) return self def with_punct_removal(self): self.transformations.append((\"str.replace\", {\"pat\": self.punct, \"repl\": \"'\"})) return self def",
"to be used # for word segmentation segmenter=\"english\", # corpus from which the",
"them \"replace_with_number\":\"\", \"replace_with_digit\":\"\", \"replace_with_currency_symbol\":\"\", \"lang\":\"en\" # set to 'de' for German special handling",
"all numbers with a special token \"no_digits\":False, # replace all digits with a",
"{ \"lower\":False, # lowercase text \"no_line_breaks\":True, # fully strip line breaks as opposed",
"len(self.y_train) def __getitem__(self, idx): item = {key: torch.tensor(val[idx]) for key, val in self.x_train.items()}",
"= {key: torch.tensor(val[idx]) for key, val in self.x_train.items()} item['labels'] = torch.tensor(self.y_train[idx], dtype=torch.float) return",
"instead of removing punctuations you may replace them \"replace_with_number\":\"\", \"replace_with_digit\":\"\", \"replace_with_currency_symbol\":\"\", \"lang\":\"en\" #",
"used # for word segmentation segmenter=\"english\", # corpus from which the word statistics",
"self.stops = stopwords.words('english') self.nlp = spacy.load('en_core_web_lg') def _capitalisation_by_ner(self, sentence, entities=['GPE', 'ORG', 'NORP', 'PERSON']):",
"'edit']] for (func, params) in self.transformations: func_to_apply = transformed_cols for f in func.split(\".\"):",
"train_data self.y_train = labels def __len__(self): return len(self.y_train) def __getitem__(self, idx): item =",
"(lambda x: x.group(\"one\"))})) return self def with_spell_check(self): self.transformations.append((\"apply\", {\"func\": (lambda x: self.text_processor.pre_process_doc(x))})) return",
"\"#\", \"repl\": \"# \"})) return self def with_ascii_quotes_replacement(self): self.transformations.append((\"str.replace\", {\"pat\": \"[‘’]\", \"repl\": \"'\"}))",
"return self def build(self): return self def preprocess(self, df, clean_col_name='edited_sentence'): _df = pd.DataFrame(index=df.index,",
"{\"pat\": \"'s\", \"repl\": \"\"})) return self def with_punct_removal(self): self.transformations.append((\"str.replace\", {\"pat\": self.punct, \"repl\": \"'\"}))",
"def with_digit_removal(self): self.transformations.append((\"str.replace\", {\"pat\": \"[0-9]\", \"repl\": \"\"})) return self def with_stopwords_removal(self): self.transformations.append((\"apply\", {\"func\":",
"\") if w not in self.stops]))})) return self def build(self): return self def",
"key, val in self.x_train.items()} item['labels'] = torch.tensor(self.y_train[idx], dtype=torch.float) return item class Preprocessor: @staticmethod",
"from cleantext import clean from ekphrasis.classes.preprocessor import TextPreProcessor from torch.utils.data import Dataset #",
"token \"no_digits\":False, # replace all digits with a special token \"no_currency_symbols\":True, # replace",
") self.punct = \"[\\.,:;\\(\\)\\[\\]@\\-\\$£]\" nltk.download('stopwords') self.stops = stopwords.words('english') self.nlp = spacy.load('en_core_web_lg') def _capitalisation_by_ner(self,",
"segmentation segmenter=\"english\", # corpus from which the word statistics are going to be",
"the word statistics are going to be used # for spell correction corrector=\"english\",",
"self def with_stopwords_removal(self): self.transformations.append((\"apply\", {\"func\": (lambda x: \" \".join([w for w in x.split(\"",
"elongated words ) self.punct = \"[\\.,:;\\(\\)\\[\\]@\\-\\$£]\" nltk.download('stopwords') self.stops = stopwords.words('english') self.nlp = spacy.load('en_core_web_lg')",
"\"replace_with_number\":\"\", \"replace_with_digit\":\"\", \"replace_with_currency_symbol\":\"\", \"lang\":\"en\" # set to 'de' for German special handling }",
"\"})) return self def with_ascii_quotes_replacement(self): self.transformations.append((\"str.replace\", {\"pat\": \"[‘’]\", \"repl\": \"'\"})) return self def",
"{\"pat\": \"#\", \"repl\": \"# \"})) return self def with_ascii_quotes_replacement(self): self.transformations.append((\"str.replace\", {\"pat\": \"[‘’]\", \"repl\":",
"x: x.group(\"one\"))})) return self def with_spell_check(self): self.transformations.append((\"apply\", {\"func\": (lambda x: self.text_processor.pre_process_doc(x))})) return self",
"a special token \"no_digits\":False, # replace all digits with a special token \"no_currency_symbols\":True,",
"which the word statistics are going to be used # for spell correction",
"lowercase text \"no_line_breaks\":True, # fully strip line breaks as opposed to only normalizing",
"def __init__(self): self.transformations = [] self.text_processor = TextPreProcessor( fix_html=True, # fix HTML tokens",
"in self.transformations: func_to_apply = transformed_cols for f in func.split(\".\"): print(f) func_to_apply = getattr(func_to_apply,",
"from nltk.corpus import stopwords from cleantext import clean from ekphrasis.classes.preprocessor import TextPreProcessor from",
"for German special handling } nlp = spacy.load('en_core_web_sm') class Task1Dataset(Dataset): def __init__(self, train_data,",
"\" (?P<one>\\w*'\\w+)\", \"repl\": (lambda x: x.group(\"one\"))})) return self def with_spell_check(self): self.transformations.append((\"apply\", {\"func\": (lambda",
"# Params for clean_text_param = { \"lower\":False, # lowercase text \"no_line_breaks\":True, # fully",
"self def with_spell_check(self): self.transformations.append((\"apply\", {\"func\": (lambda x: self.text_processor.pre_process_doc(x))})) return self def with_space_after_hashtags(self): self.transformations.append((\"str.replace\",",
"special handling } nlp = spacy.load('en_core_web_sm') class Task1Dataset(Dataset): def __init__(self, train_data, labels): self.x_train",
"x: re.subn(\"<.*/>\", x[1], x[0])[0]), \"axis\":1})) return self def with_capitalisation_by_ner(self): self.transformations.append((\"apply\", {\"func\": (lambda x:",
"in func.split(\".\"): print(f) func_to_apply = getattr(func_to_apply, f) transformed_cols = func_to_apply(**params) _df[clean_col_name] = transformed_cols",
"df, clean_col_name='edited_sentence'): _df = pd.DataFrame(index=df.index, columns=[clean_col_name, 'meanGrade']) _df['meanGrade'] = df.meanGrade transformed_cols = df[['original',",
"x.group(\"one\"))})) return self def with_spell_check(self): self.transformations.append((\"apply\", {\"func\": (lambda x: self.text_processor.pre_process_doc(x))})) return self def",
"clean_text_param = { \"lower\":False, # lowercase text \"no_line_breaks\":True, # fully strip line breaks",
"Unpack contractions (can't -> can not) spell_correct=True, # spell correction for elongated words",
"self.transformations.append((\"str.replace\", {\"pat\": \" (?P<one>\\w*'\\w+)\", \"repl\": (lambda x: x.group(\"one\"))})) return self def with_spell_check(self): self.transformations.append((\"apply\",",
"self.nlp = spacy.load('en_core_web_lg') def _capitalisation_by_ner(self, sentence, entities=['GPE', 'ORG', 'NORP', 'PERSON']): edited_row = []",
"Params for clean_text_param = { \"lower\":False, # lowercase text \"no_line_breaks\":True, # fully strip",
"ekphrasis.classes.preprocessor import TextPreProcessor from torch.utils.data import Dataset # Params for clean_text_param = {",
"\"no_currency_symbols\":True, # replace all currency symbols with a special token \"no_punct\":True, # remove",
"idx): item = {key: torch.tensor(val[idx]) for key, val in self.x_train.items()} item['labels'] = torch.tensor(self.y_train[idx],",
"@staticmethod def PreprocessorBuilder(): return Preprocessor() def __init__(self): self.transformations = [] self.text_processor = TextPreProcessor(",
"\"'\"})) return self def with_digit_removal(self): self.transformations.append((\"str.replace\", {\"pat\": \"[0-9]\", \"repl\": \"\"})) return self def",
"self.x_train = train_data self.y_train = labels def __len__(self): return len(self.y_train) def __getitem__(self, idx):",
"torch from nltk.corpus import stopwords from cleantext import clean from ekphrasis.classes.preprocessor import TextPreProcessor",
"a special token \"no_phone_numbers\":False, # replace all phone numbers with a special token",
"from torch.utils.data import Dataset # Params for clean_text_param = { \"lower\":False, # lowercase",
"you may replace them \"replace_with_number\":\"\", \"replace_with_digit\":\"\", \"replace_with_currency_symbol\":\"\", \"lang\":\"en\" # set to 'de' for",
"correction for elongated words ) self.punct = \"[\\.,:;\\(\\)\\[\\]@\\-\\$£]\" nltk.download('stopwords') self.stops = stopwords.words('english') self.nlp",
"= \"[\\.,:;\\(\\)\\[\\]@\\-\\$£]\" nltk.download('stopwords') self.stops = stopwords.words('english') self.nlp = spacy.load('en_core_web_lg') def _capitalisation_by_ner(self, sentence, entities=['GPE',",
"\"no_line_breaks\":True, # fully strip line breaks as opposed to only normalizing them \"no_urls\":False,",
"self.transformations.append((\"apply\", {\"func\": (lambda x: re.subn(\"<.*/>\", x[1], x[0])[0]), \"axis\":1})) return self def with_capitalisation_by_ner(self): self.transformations.append((\"apply\",",
"self def with_possessive_elimination(self): self.transformations.append((\"str.replace\", {\"pat\": \"'s\", \"repl\": \"\"})) return self def with_punct_removal(self): self.transformations.append((\"str.replace\",",
"# remove punctuations \"replace_with_punct\":\"\", # instead of removing punctuations you may replace them",
"labels def __len__(self): return len(self.y_train) def __getitem__(self, idx): item = {key: torch.tensor(val[idx]) for",
"only normalizing them \"no_urls\":False, # replace all URLs with a special token \"no_emails\":False,",
"for spell correction corrector=\"english\", unpack_hashtags=False, # perform word segmentation on hashtags unpack_contractions=False, #",
"# for word segmentation segmenter=\"english\", # corpus from which the word statistics are",
"# fix HTML tokens # corpus from which the word statistics are going",
"_capitalisation_by_ner(self, sentence, entities=['GPE', 'ORG', 'NORP', 'PERSON']): edited_row = [] trial_doc = self.nlp(sentence) for",
"special token \"no_punct\":True, # remove punctuations \"replace_with_punct\":\"\", # instead of removing punctuations you",
"def __len__(self): return len(self.y_train) def __getitem__(self, idx): item = {key: torch.tensor(val[idx]) for key,",
"punctuations \"replace_with_punct\":\"\", # instead of removing punctuations you may replace them \"replace_with_number\":\"\", \"replace_with_digit\":\"\",",
"# spell correction for elongated words ) self.punct = \"[\\.,:;\\(\\)\\[\\]@\\-\\$£]\" nltk.download('stopwords') self.stops =",
"trial_doc = self.nlp(sentence) for tok in trial_doc: if tok.ent_type_ in entities: edited_row.append(tok.text) else:",
"words ) self.punct = \"[\\.,:;\\(\\)\\[\\]@\\-\\$£]\" nltk.download('stopwords') self.stops = stopwords.words('english') self.nlp = spacy.load('en_core_web_lg') def",
"special token \"no_phone_numbers\":False, # replace all phone numbers with a special token \"no_numbers\":False,",
"x.split(\" \") if w not in self.stops]))})) return self def build(self): return self",
"_df['meanGrade'] = df.meanGrade transformed_cols = df[['original', 'edit']] for (func, params) in self.transformations: func_to_apply",
"special token \"no_digits\":False, # replace all digits with a special token \"no_currency_symbols\":True, #",
"(lambda x: re.subn(\"<.*/>\", x[1], x[0])[0]), \"axis\":1})) return self def with_capitalisation_by_ner(self): self.transformations.append((\"apply\", {\"func\": (lambda",
"\"no_urls\":False, # replace all URLs with a special token \"no_emails\":False, # replace all",
"entities: edited_row.append(tok.text) else: edited_row.append(tok.text.lower()) return ' '.join(edited_row) def with_word_replacement(self): self.transformations.append((\"apply\", {\"func\": (lambda x:",
"{\"func\": (lambda x: \" \".join([w for w in x.split(\" \") if w not",
"sentence, entities=['GPE', 'ORG', 'NORP', 'PERSON']): edited_row = [] trial_doc = self.nlp(sentence) for tok",
"return self def with_digit_removal(self): self.transformations.append((\"str.replace\", {\"pat\": \"[0-9]\", \"repl\": \"\"})) return self def with_stopwords_removal(self):",
"\"repl\": \"\"})) return self def with_punct_removal(self): self.transformations.append((\"str.replace\", {\"pat\": self.punct, \"repl\": \"'\"})) return self",
"a special token \"no_numbers\":False, # replace all numbers with a special token \"no_digits\":False,",
"\"'s\", \"repl\": \"\"})) return self def with_punct_removal(self): self.transformations.append((\"str.replace\", {\"pat\": self.punct, \"repl\": \"'\"})) return",
"token \"no_currency_symbols\":True, # replace all currency symbols with a special token \"no_punct\":True, #",
"def with_word_replacement(self): self.transformations.append((\"apply\", {\"func\": (lambda x: re.subn(\"<.*/>\", x[1], x[0])[0]), \"axis\":1})) return self def",
"as pd import re import nltk import spacy import torch from nltk.corpus import",
"which the word statistics are going to be used # for word segmentation",
"= stopwords.words('english') self.nlp = spacy.load('en_core_web_lg') def _capitalisation_by_ner(self, sentence, entities=['GPE', 'ORG', 'NORP', 'PERSON']): edited_row",
"statistics are going to be used # for spell correction corrector=\"english\", unpack_hashtags=False, #",
"tok.ent_type_ in entities: edited_row.append(tok.text) else: edited_row.append(tok.text.lower()) return ' '.join(edited_row) def with_word_replacement(self): self.transformations.append((\"apply\", {\"func\":",
"are going to be used # for word segmentation segmenter=\"english\", # corpus from",
"entities=['GPE', 'ORG', 'NORP', 'PERSON']): edited_row = [] trial_doc = self.nlp(sentence) for tok in",
"nltk.corpus import stopwords from cleantext import clean from ekphrasis.classes.preprocessor import TextPreProcessor from torch.utils.data",
"with_joining_contraction_tokens(self): self.transformations.append((\"str.replace\", {\"pat\": \" (?P<one>\\w*'\\w+)\", \"repl\": (lambda x: x.group(\"one\"))})) return self def with_spell_check(self):",
"\"replace_with_digit\":\"\", \"replace_with_currency_symbol\":\"\", \"lang\":\"en\" # set to 'de' for German special handling } nlp",
"remove punctuations \"replace_with_punct\":\"\", # instead of removing punctuations you may replace them \"replace_with_number\":\"\",",
"trial_doc: if tok.ent_type_ in entities: edited_row.append(tok.text) else: edited_row.append(tok.text.lower()) return ' '.join(edited_row) def with_word_replacement(self):",
"on hashtags unpack_contractions=False, # Unpack contractions (can't -> can not) spell_correct=True, # spell",
"\"no_emails\":False, # replace all email addresses with a special token \"no_phone_numbers\":False, # replace",
"[] trial_doc = self.nlp(sentence) for tok in trial_doc: if tok.ent_type_ in entities: edited_row.append(tok.text)",
"{\"pat\": \"[0-9]\", \"repl\": \"\"})) return self def with_stopwords_removal(self): self.transformations.append((\"apply\", {\"func\": (lambda x: \"",
"self.transformations: func_to_apply = transformed_cols for f in func.split(\".\"): print(f) func_to_apply = getattr(func_to_apply, f)",
"to 'de' for German special handling } nlp = spacy.load('en_core_web_sm') class Task1Dataset(Dataset): def",
"for clean_text_param = { \"lower\":False, # lowercase text \"no_line_breaks\":True, # fully strip line",
"from ekphrasis.classes.preprocessor import TextPreProcessor from torch.utils.data import Dataset # Params for clean_text_param =",
"= df.meanGrade transformed_cols = df[['original', 'edit']] for (func, params) in self.transformations: func_to_apply =",
"may replace them \"replace_with_number\":\"\", \"replace_with_digit\":\"\", \"replace_with_currency_symbol\":\"\", \"lang\":\"en\" # set to 'de' for German",
"fully strip line breaks as opposed to only normalizing them \"no_urls\":False, # replace",
"all phone numbers with a special token \"no_numbers\":False, # replace all numbers with",
"in x.split(\" \") if w not in self.stops]))})) return self def build(self): return",
"import stopwords from cleantext import clean from ekphrasis.classes.preprocessor import TextPreProcessor from torch.utils.data import",
"return ' '.join(edited_row) def with_word_replacement(self): self.transformations.append((\"apply\", {\"func\": (lambda x: re.subn(\"<.*/>\", x[1], x[0])[0]), \"axis\":1}))",
"_df = pd.DataFrame(index=df.index, columns=[clean_col_name, 'meanGrade']) _df['meanGrade'] = df.meanGrade transformed_cols = df[['original', 'edit']] for",
"special token \"no_emails\":False, # replace all email addresses with a special token \"no_phone_numbers\":False,",
"# replace all digits with a special token \"no_currency_symbols\":True, # replace all currency",
"replace all numbers with a special token \"no_digits\":False, # replace all digits with",
"stopwords.words('english') self.nlp = spacy.load('en_core_web_lg') def _capitalisation_by_ner(self, sentence, entities=['GPE', 'ORG', 'NORP', 'PERSON']): edited_row =",
"text \"no_line_breaks\":True, # fully strip line breaks as opposed to only normalizing them",
"build(self): return self def preprocess(self, df, clean_col_name='edited_sentence'): _df = pd.DataFrame(index=df.index, columns=[clean_col_name, 'meanGrade']) _df['meanGrade']",
"spacy import torch from nltk.corpus import stopwords from cleantext import clean from ekphrasis.classes.preprocessor",
"__init__(self, train_data, labels): self.x_train = train_data self.y_train = labels def __len__(self): return len(self.y_train)",
"[] self.text_processor = TextPreProcessor( fix_html=True, # fix HTML tokens # corpus from which",
"opposed to only normalizing them \"no_urls\":False, # replace all URLs with a special",
"self def with_space_after_hashtags(self): self.transformations.append((\"str.replace\", {\"pat\": \"#\", \"repl\": \"# \"})) return self def with_ascii_quotes_replacement(self):",
"\"replace_with_punct\":\"\", # instead of removing punctuations you may replace them \"replace_with_number\":\"\", \"replace_with_digit\":\"\", \"replace_with_currency_symbol\":\"\",",
"{\"pat\": \" (?P<one>\\w*'\\w+)\", \"repl\": (lambda x: x.group(\"one\"))})) return self def with_spell_check(self): self.transformations.append((\"apply\", {\"func\":",
"{\"pat\": self.punct, \"repl\": \"'\"})) return self def with_digit_removal(self): self.transformations.append((\"str.replace\", {\"pat\": \"[0-9]\", \"repl\": \"\"}))",
"\"no_digits\":False, # replace all digits with a special token \"no_currency_symbols\":True, # replace all",
"def with_ascii_quotes_replacement(self): self.transformations.append((\"str.replace\", {\"pat\": \"[‘’]\", \"repl\": \"'\"})) return self def with_possessive_elimination(self): self.transformations.append((\"str.replace\", {\"pat\":",
"German special handling } nlp = spacy.load('en_core_web_sm') class Task1Dataset(Dataset): def __init__(self, train_data, labels):",
"with a special token \"no_phone_numbers\":False, # replace all phone numbers with a special",
"punctuations you may replace them \"replace_with_number\":\"\", \"replace_with_digit\":\"\", \"replace_with_currency_symbol\":\"\", \"lang\":\"en\" # set to 'de'",
"self.transformations.append((\"str.replace\", {\"pat\": self.punct, \"repl\": \"'\"})) return self def with_digit_removal(self): self.transformations.append((\"str.replace\", {\"pat\": \"[0-9]\", \"repl\":",
"return self def with_stopwords_removal(self): self.transformations.append((\"apply\", {\"func\": (lambda x: \" \".join([w for w in",
"self def with_digit_removal(self): self.transformations.append((\"str.replace\", {\"pat\": \"[0-9]\", \"repl\": \"\"})) return self def with_stopwords_removal(self): self.transformations.append((\"apply\",",
"class Task1Dataset(Dataset): def __init__(self, train_data, labels): self.x_train = train_data self.y_train = labels def",
"\"axis\":1})) return self def with_capitalisation_by_ner(self): self.transformations.append((\"apply\", {\"func\": (lambda x: self._capitalisation_by_ner(x))})) return self def",
"be used # for word segmentation segmenter=\"english\", # corpus from which the word",
"replace all URLs with a special token \"no_emails\":False, # replace all email addresses",
"(func, params) in self.transformations: func_to_apply = transformed_cols for f in func.split(\".\"): print(f) func_to_apply",
"self.stops]))})) return self def build(self): return self def preprocess(self, df, clean_col_name='edited_sentence'): _df =",
"TextPreProcessor from torch.utils.data import Dataset # Params for clean_text_param = { \"lower\":False, #",
"\"replace_with_currency_symbol\":\"\", \"lang\":\"en\" # set to 'de' for German special handling } nlp =",
"nltk import spacy import torch from nltk.corpus import stopwords from cleantext import clean",
"return self def with_ascii_quotes_replacement(self): self.transformations.append((\"str.replace\", {\"pat\": \"[‘’]\", \"repl\": \"'\"})) return self def with_possessive_elimination(self):",
"return self def with_possessive_elimination(self): self.transformations.append((\"str.replace\", {\"pat\": \"'s\", \"repl\": \"\"})) return self def with_punct_removal(self):",
"replace all email addresses with a special token \"no_phone_numbers\":False, # replace all phone",
"\"[0-9]\", \"repl\": \"\"})) return self def with_stopwords_removal(self): self.transformations.append((\"apply\", {\"func\": (lambda x: \" \".join([w",
"self.x_train.items()} item['labels'] = torch.tensor(self.y_train[idx], dtype=torch.float) return item class Preprocessor: @staticmethod def PreprocessorBuilder(): return",
"func_to_apply = getattr(func_to_apply, f) transformed_cols = func_to_apply(**params) _df[clean_col_name] = transformed_cols return _df, clean_col_name",
"be used # for spell correction corrector=\"english\", unpack_hashtags=False, # perform word segmentation on",
"\"# \"})) return self def with_ascii_quotes_replacement(self): self.transformations.append((\"str.replace\", {\"pat\": \"[‘’]\", \"repl\": \"'\"})) return self",
"PreprocessorBuilder(): return Preprocessor() def __init__(self): self.transformations = [] self.text_processor = TextPreProcessor( fix_html=True, #",
"def preprocess(self, df, clean_col_name='edited_sentence'): _df = pd.DataFrame(index=df.index, columns=[clean_col_name, 'meanGrade']) _df['meanGrade'] = df.meanGrade transformed_cols",
"-> can not) spell_correct=True, # spell correction for elongated words ) self.punct =",
"= df[['original', 'edit']] for (func, params) in self.transformations: func_to_apply = transformed_cols for f",
"with a special token \"no_numbers\":False, # replace all numbers with a special token",
"to only normalizing them \"no_urls\":False, # replace all URLs with a special token",
"train_data, labels): self.x_train = train_data self.y_train = labels def __len__(self): return len(self.y_train) def",
"replace all digits with a special token \"no_currency_symbols\":True, # replace all currency symbols",
"self def with_joining_contraction_tokens(self): self.transformations.append((\"str.replace\", {\"pat\": \" (?P<one>\\w*'\\w+)\", \"repl\": (lambda x: x.group(\"one\"))})) return self",
"clean_col_name='edited_sentence'): _df = pd.DataFrame(index=df.index, columns=[clean_col_name, 'meanGrade']) _df['meanGrade'] = df.meanGrade transformed_cols = df[['original', 'edit']]",
"if tok.ent_type_ in entities: edited_row.append(tok.text) else: edited_row.append(tok.text.lower()) return ' '.join(edited_row) def with_word_replacement(self): self.transformations.append((\"apply\",",
"params) in self.transformations: func_to_apply = transformed_cols for f in func.split(\".\"): print(f) func_to_apply =",
"corrector=\"english\", unpack_hashtags=False, # perform word segmentation on hashtags unpack_contractions=False, # Unpack contractions (can't",
"with_possessive_elimination(self): self.transformations.append((\"str.replace\", {\"pat\": \"'s\", \"repl\": \"\"})) return self def with_punct_removal(self): self.transformations.append((\"str.replace\", {\"pat\": self.punct,",
"preprocess(self, df, clean_col_name='edited_sentence'): _df = pd.DataFrame(index=df.index, columns=[clean_col_name, 'meanGrade']) _df['meanGrade'] = df.meanGrade transformed_cols =",
"of removing punctuations you may replace them \"replace_with_number\":\"\", \"replace_with_digit\":\"\", \"replace_with_currency_symbol\":\"\", \"lang\":\"en\" # set",
"self.nlp(sentence) for tok in trial_doc: if tok.ent_type_ in entities: edited_row.append(tok.text) else: edited_row.append(tok.text.lower()) return",
"{\"pat\": \"[‘’]\", \"repl\": \"'\"})) return self def with_possessive_elimination(self): self.transformations.append((\"str.replace\", {\"pat\": \"'s\", \"repl\": \"\"}))",
"unpack_hashtags=False, # perform word segmentation on hashtags unpack_contractions=False, # Unpack contractions (can't ->",
"Preprocessor() def __init__(self): self.transformations = [] self.text_processor = TextPreProcessor( fix_html=True, # fix HTML",
"import torch from nltk.corpus import stopwords from cleantext import clean from ekphrasis.classes.preprocessor import",
"with_space_after_hashtags(self): self.transformations.append((\"str.replace\", {\"pat\": \"#\", \"repl\": \"# \"})) return self def with_ascii_quotes_replacement(self): self.transformations.append((\"str.replace\", {\"pat\":",
"= spacy.load('en_core_web_sm') class Task1Dataset(Dataset): def __init__(self, train_data, labels): self.x_train = train_data self.y_train =",
"can not) spell_correct=True, # spell correction for elongated words ) self.punct = \"[\\.,:;\\(\\)\\[\\]@\\-\\$£]\"",
"return self def with_capitalisation_by_ner(self): self.transformations.append((\"apply\", {\"func\": (lambda x: self._capitalisation_by_ner(x))})) return self def with_joining_contraction_tokens(self):",
"\"\"})) return self def with_stopwords_removal(self): self.transformations.append((\"apply\", {\"func\": (lambda x: \" \".join([w for w",
"__len__(self): return len(self.y_train) def __getitem__(self, idx): item = {key: torch.tensor(val[idx]) for key, val",
"not) spell_correct=True, # spell correction for elongated words ) self.punct = \"[\\.,:;\\(\\)\\[\\]@\\-\\$£]\" nltk.download('stopwords')",
"in self.stops]))})) return self def build(self): return self def preprocess(self, df, clean_col_name='edited_sentence'): _df",
"def with_spell_check(self): self.transformations.append((\"apply\", {\"func\": (lambda x: self.text_processor.pre_process_doc(x))})) return self def with_space_after_hashtags(self): self.transformations.append((\"str.replace\", {\"pat\":",
"import TextPreProcessor from torch.utils.data import Dataset # Params for clean_text_param = { \"lower\":False,",
"' '.join(edited_row) def with_word_replacement(self): self.transformations.append((\"apply\", {\"func\": (lambda x: re.subn(\"<.*/>\", x[1], x[0])[0]), \"axis\":1})) return",
"= transformed_cols for f in func.split(\".\"): print(f) func_to_apply = getattr(func_to_apply, f) transformed_cols =",
"= torch.tensor(self.y_train[idx], dtype=torch.float) return item class Preprocessor: @staticmethod def PreprocessorBuilder(): return Preprocessor() def",
"HTML tokens # corpus from which the word statistics are going to be",
"for (func, params) in self.transformations: func_to_apply = transformed_cols for f in func.split(\".\"): print(f)",
"hashtags unpack_contractions=False, # Unpack contractions (can't -> can not) spell_correct=True, # spell correction",
"{\"func\": (lambda x: self.text_processor.pre_process_doc(x))})) return self def with_space_after_hashtags(self): self.transformations.append((\"str.replace\", {\"pat\": \"#\", \"repl\": \"#",
"fix_html=True, # fix HTML tokens # corpus from which the word statistics are",
"self def preprocess(self, df, clean_col_name='edited_sentence'): _df = pd.DataFrame(index=df.index, columns=[clean_col_name, 'meanGrade']) _df['meanGrade'] = df.meanGrade",
"# replace all numbers with a special token \"no_digits\":False, # replace all digits",
"\"lower\":False, # lowercase text \"no_line_breaks\":True, # fully strip line breaks as opposed to",
"with a special token \"no_currency_symbols\":True, # replace all currency symbols with a special",
"as opposed to only normalizing them \"no_urls\":False, # replace all URLs with a",
"return self def with_joining_contraction_tokens(self): self.transformations.append((\"str.replace\", {\"pat\": \" (?P<one>\\w*'\\w+)\", \"repl\": (lambda x: x.group(\"one\"))})) return",
"nltk.download('stopwords') self.stops = stopwords.words('english') self.nlp = spacy.load('en_core_web_lg') def _capitalisation_by_ner(self, sentence, entities=['GPE', 'ORG', 'NORP',",
"numbers with a special token \"no_digits\":False, # replace all digits with a special",
"{\"func\": (lambda x: self._capitalisation_by_ner(x))})) return self def with_joining_contraction_tokens(self): self.transformations.append((\"str.replace\", {\"pat\": \" (?P<one>\\w*'\\w+)\", \"repl\":",
"word statistics are going to be used # for word segmentation segmenter=\"english\", #",
"self.transformations.append((\"str.replace\", {\"pat\": \"[‘’]\", \"repl\": \"'\"})) return self def with_possessive_elimination(self): self.transformations.append((\"str.replace\", {\"pat\": \"'s\", \"repl\":",
"x: \" \".join([w for w in x.split(\" \") if w not in self.stops]))}))",
"going to be used # for spell correction corrector=\"english\", unpack_hashtags=False, # perform word",
"func.split(\".\"): print(f) func_to_apply = getattr(func_to_apply, f) transformed_cols = func_to_apply(**params) _df[clean_col_name] = transformed_cols return",
"df.meanGrade transformed_cols = df[['original', 'edit']] for (func, params) in self.transformations: func_to_apply = transformed_cols",
"(lambda x: self.text_processor.pre_process_doc(x))})) return self def with_space_after_hashtags(self): self.transformations.append((\"str.replace\", {\"pat\": \"#\", \"repl\": \"# \"}))",
"tokens # corpus from which the word statistics are going to be used",
"addresses with a special token \"no_phone_numbers\":False, # replace all phone numbers with a",
"__getitem__(self, idx): item = {key: torch.tensor(val[idx]) for key, val in self.x_train.items()} item['labels'] =",
"w in x.split(\" \") if w not in self.stops]))})) return self def build(self):",
"x: self._capitalisation_by_ner(x))})) return self def with_joining_contraction_tokens(self): self.transformations.append((\"str.replace\", {\"pat\": \" (?P<one>\\w*'\\w+)\", \"repl\": (lambda x:",
"special token \"no_numbers\":False, # replace all numbers with a special token \"no_digits\":False, #",
"spell_correct=True, # spell correction for elongated words ) self.punct = \"[\\.,:;\\(\\)\\[\\]@\\-\\$£]\" nltk.download('stopwords') self.stops",
"def with_space_after_hashtags(self): self.transformations.append((\"str.replace\", {\"pat\": \"#\", \"repl\": \"# \"})) return self def with_ascii_quotes_replacement(self): self.transformations.append((\"str.replace\",",
"x[0])[0]), \"axis\":1})) return self def with_capitalisation_by_ner(self): self.transformations.append((\"apply\", {\"func\": (lambda x: self._capitalisation_by_ner(x))})) return self",
"columns=[clean_col_name, 'meanGrade']) _df['meanGrade'] = df.meanGrade transformed_cols = df[['original', 'edit']] for (func, params) in",
"corpus from which the word statistics are going to be used # for",
"digits with a special token \"no_currency_symbols\":True, # replace all currency symbols with a",
"for word segmentation segmenter=\"english\", # corpus from which the word statistics are going",
"= [] trial_doc = self.nlp(sentence) for tok in trial_doc: if tok.ent_type_ in entities:",
"spell correction corrector=\"english\", unpack_hashtags=False, # perform word segmentation on hashtags unpack_contractions=False, # Unpack",
"import clean from ekphrasis.classes.preprocessor import TextPreProcessor from torch.utils.data import Dataset # Params for",
"self.text_processor = TextPreProcessor( fix_html=True, # fix HTML tokens # corpus from which the",
"replace all currency symbols with a special token \"no_punct\":True, # remove punctuations \"replace_with_punct\":\"\",",
"token \"no_punct\":True, # remove punctuations \"replace_with_punct\":\"\", # instead of removing punctuations you may",
"with_spell_check(self): self.transformations.append((\"apply\", {\"func\": (lambda x: self.text_processor.pre_process_doc(x))})) return self def with_space_after_hashtags(self): self.transformations.append((\"str.replace\", {\"pat\": \"#\",",
"def with_stopwords_removal(self): self.transformations.append((\"apply\", {\"func\": (lambda x: \" \".join([w for w in x.split(\" \")",
"self.transformations.append((\"str.replace\", {\"pat\": \"#\", \"repl\": \"# \"})) return self def with_ascii_quotes_replacement(self): self.transformations.append((\"str.replace\", {\"pat\": \"[‘’]\",",
"self.y_train = labels def __len__(self): return len(self.y_train) def __getitem__(self, idx): item = {key:",
"'.join(edited_row) def with_word_replacement(self): self.transformations.append((\"apply\", {\"func\": (lambda x: re.subn(\"<.*/>\", x[1], x[0])[0]), \"axis\":1})) return self",
"\"repl\": \"\"})) return self def with_stopwords_removal(self): self.transformations.append((\"apply\", {\"func\": (lambda x: \" \".join([w for",
"# set to 'de' for German special handling } nlp = spacy.load('en_core_web_sm') class",
"def __init__(self, train_data, labels): self.x_train = train_data self.y_train = labels def __len__(self): return",
"for elongated words ) self.punct = \"[\\.,:;\\(\\)\\[\\]@\\-\\$£]\" nltk.download('stopwords') self.stops = stopwords.words('english') self.nlp =",
"for w in x.split(\" \") if w not in self.stops]))})) return self def",
"= { \"lower\":False, # lowercase text \"no_line_breaks\":True, # fully strip line breaks as",
"line breaks as opposed to only normalizing them \"no_urls\":False, # replace all URLs",
"'NORP', 'PERSON']): edited_row = [] trial_doc = self.nlp(sentence) for tok in trial_doc: if",
"return Preprocessor() def __init__(self): self.transformations = [] self.text_processor = TextPreProcessor( fix_html=True, # fix",
"with_digit_removal(self): self.transformations.append((\"str.replace\", {\"pat\": \"[0-9]\", \"repl\": \"\"})) return self def with_stopwords_removal(self): self.transformations.append((\"apply\", {\"func\": (lambda",
"'de' for German special handling } nlp = spacy.load('en_core_web_sm') class Task1Dataset(Dataset): def __init__(self,",
"= labels def __len__(self): return len(self.y_train) def __getitem__(self, idx): item = {key: torch.tensor(val[idx])",
"stopwords from cleantext import clean from ekphrasis.classes.preprocessor import TextPreProcessor from torch.utils.data import Dataset",
"phone numbers with a special token \"no_numbers\":False, # replace all numbers with a",
"for tok in trial_doc: if tok.ent_type_ in entities: edited_row.append(tok.text) else: edited_row.append(tok.text.lower()) return '",
"import re import nltk import spacy import torch from nltk.corpus import stopwords from",
"self.transformations.append((\"apply\", {\"func\": (lambda x: self._capitalisation_by_ner(x))})) return self def with_joining_contraction_tokens(self): self.transformations.append((\"str.replace\", {\"pat\": \" (?P<one>\\w*'\\w+)\",",
"cleantext import clean from ekphrasis.classes.preprocessor import TextPreProcessor from torch.utils.data import Dataset # Params",
"strip line breaks as opposed to only normalizing them \"no_urls\":False, # replace all",
"symbols with a special token \"no_punct\":True, # remove punctuations \"replace_with_punct\":\"\", # instead of",
"a special token \"no_punct\":True, # remove punctuations \"replace_with_punct\":\"\", # instead of removing punctuations",
"# replace all phone numbers with a special token \"no_numbers\":False, # replace all",
"a special token \"no_emails\":False, # replace all email addresses with a special token",
"going to be used # for word segmentation segmenter=\"english\", # corpus from which",
"self.transformations.append((\"apply\", {\"func\": (lambda x: \" \".join([w for w in x.split(\" \") if w",
"with_punct_removal(self): self.transformations.append((\"str.replace\", {\"pat\": self.punct, \"repl\": \"'\"})) return self def with_digit_removal(self): self.transformations.append((\"str.replace\", {\"pat\": \"[0-9]\",",
"self def with_punct_removal(self): self.transformations.append((\"str.replace\", {\"pat\": self.punct, \"repl\": \"'\"})) return self def with_digit_removal(self): self.transformations.append((\"str.replace\",",
"for f in func.split(\".\"): print(f) func_to_apply = getattr(func_to_apply, f) transformed_cols = func_to_apply(**params) _df[clean_col_name]",
"correction corrector=\"english\", unpack_hashtags=False, # perform word segmentation on hashtags unpack_contractions=False, # Unpack contractions",
"} nlp = spacy.load('en_core_web_sm') class Task1Dataset(Dataset): def __init__(self, train_data, labels): self.x_train = train_data",
"for key, val in self.x_train.items()} item['labels'] = torch.tensor(self.y_train[idx], dtype=torch.float) return item class Preprocessor:",
"pd.DataFrame(index=df.index, columns=[clean_col_name, 'meanGrade']) _df['meanGrade'] = df.meanGrade transformed_cols = df[['original', 'edit']] for (func, params)",
"not in self.stops]))})) return self def build(self): return self def preprocess(self, df, clean_col_name='edited_sentence'):",
"word segmentation on hashtags unpack_contractions=False, # Unpack contractions (can't -> can not) spell_correct=True,",
"pd import re import nltk import spacy import torch from nltk.corpus import stopwords",
"the word statistics are going to be used # for word segmentation segmenter=\"english\",",
"are going to be used # for spell correction corrector=\"english\", unpack_hashtags=False, # perform",
"unpack_contractions=False, # Unpack contractions (can't -> can not) spell_correct=True, # spell correction for",
"edited_row = [] trial_doc = self.nlp(sentence) for tok in trial_doc: if tok.ent_type_ in",
"edited_row.append(tok.text.lower()) return ' '.join(edited_row) def with_word_replacement(self): self.transformations.append((\"apply\", {\"func\": (lambda x: re.subn(\"<.*/>\", x[1], x[0])[0]),",
"__init__(self): self.transformations = [] self.text_processor = TextPreProcessor( fix_html=True, # fix HTML tokens #",
"= spacy.load('en_core_web_lg') def _capitalisation_by_ner(self, sentence, entities=['GPE', 'ORG', 'NORP', 'PERSON']): edited_row = [] trial_doc",
"def with_punct_removal(self): self.transformations.append((\"str.replace\", {\"pat\": self.punct, \"repl\": \"'\"})) return self def with_digit_removal(self): self.transformations.append((\"str.replace\", {\"pat\":",
"\"repl\": \"'\"})) return self def with_digit_removal(self): self.transformations.append((\"str.replace\", {\"pat\": \"[0-9]\", \"repl\": \"\"})) return self",
"\"repl\": \"# \"})) return self def with_ascii_quotes_replacement(self): self.transformations.append((\"str.replace\", {\"pat\": \"[‘’]\", \"repl\": \"'\"})) return",
"# for spell correction corrector=\"english\", unpack_hashtags=False, # perform word segmentation on hashtags unpack_contractions=False,",
"them \"no_urls\":False, # replace all URLs with a special token \"no_emails\":False, # replace",
"self.transformations = [] self.text_processor = TextPreProcessor( fix_html=True, # fix HTML tokens # corpus",
"contractions (can't -> can not) spell_correct=True, # spell correction for elongated words )",
"tok in trial_doc: if tok.ent_type_ in entities: edited_row.append(tok.text) else: edited_row.append(tok.text.lower()) return ' '.join(edited_row)",
"\"repl\": \"'\"})) return self def with_possessive_elimination(self): self.transformations.append((\"str.replace\", {\"pat\": \"'s\", \"repl\": \"\"})) return self",
"email addresses with a special token \"no_phone_numbers\":False, # replace all phone numbers with",
"import nltk import spacy import torch from nltk.corpus import stopwords from cleantext import",
"re import nltk import spacy import torch from nltk.corpus import stopwords from cleantext",
"= [] self.text_processor = TextPreProcessor( fix_html=True, # fix HTML tokens # corpus from",
"pandas as pd import re import nltk import spacy import torch from nltk.corpus",
"self def with_capitalisation_by_ner(self): self.transformations.append((\"apply\", {\"func\": (lambda x: self._capitalisation_by_ner(x))})) return self def with_joining_contraction_tokens(self): self.transformations.append((\"str.replace\",",
"def with_possessive_elimination(self): self.transformations.append((\"str.replace\", {\"pat\": \"'s\", \"repl\": \"\"})) return self def with_punct_removal(self): self.transformations.append((\"str.replace\", {\"pat\":",
"\" \".join([w for w in x.split(\" \") if w not in self.stops]))})) return",
"TextPreProcessor( fix_html=True, # fix HTML tokens # corpus from which the word statistics",
"item['labels'] = torch.tensor(self.y_train[idx], dtype=torch.float) return item class Preprocessor: @staticmethod def PreprocessorBuilder(): return Preprocessor()",
"# perform word segmentation on hashtags unpack_contractions=False, # Unpack contractions (can't -> can",
"numbers with a special token \"no_numbers\":False, # replace all numbers with a special",
"to be used # for spell correction corrector=\"english\", unpack_hashtags=False, # perform word segmentation",
"all digits with a special token \"no_currency_symbols\":True, # replace all currency symbols with",
"if w not in self.stops]))})) return self def build(self): return self def preprocess(self,",
"= TextPreProcessor( fix_html=True, # fix HTML tokens # corpus from which the word",
"\"repl\": (lambda x: x.group(\"one\"))})) return self def with_spell_check(self): self.transformations.append((\"apply\", {\"func\": (lambda x: self.text_processor.pre_process_doc(x))}))",
"special token \"no_currency_symbols\":True, # replace all currency symbols with a special token \"no_punct\":True,",
"URLs with a special token \"no_emails\":False, # replace all email addresses with a",
"x[1], x[0])[0]), \"axis\":1})) return self def with_capitalisation_by_ner(self): self.transformations.append((\"apply\", {\"func\": (lambda x: self._capitalisation_by_ner(x))})) return",
"self def build(self): return self def preprocess(self, df, clean_col_name='edited_sentence'): _df = pd.DataFrame(index=df.index, columns=[clean_col_name,",
"import spacy import torch from nltk.corpus import stopwords from cleantext import clean from",
"from which the word statistics are going to be used # for spell",
"= train_data self.y_train = labels def __len__(self): return len(self.y_train) def __getitem__(self, idx): item",
"normalizing them \"no_urls\":False, # replace all URLs with a special token \"no_emails\":False, #",
"\"'\"})) return self def with_possessive_elimination(self): self.transformations.append((\"str.replace\", {\"pat\": \"'s\", \"repl\": \"\"})) return self def",
"import pandas as pd import re import nltk import spacy import torch from",
"def with_capitalisation_by_ner(self): self.transformations.append((\"apply\", {\"func\": (lambda x: self._capitalisation_by_ner(x))})) return self def with_joining_contraction_tokens(self): self.transformations.append((\"str.replace\", {\"pat\":",
"func_to_apply = transformed_cols for f in func.split(\".\"): print(f) func_to_apply = getattr(func_to_apply, f) transformed_cols",
"word segmentation segmenter=\"english\", # corpus from which the word statistics are going to",
"# replace all email addresses with a special token \"no_phone_numbers\":False, # replace all",
"self.transformations.append((\"apply\", {\"func\": (lambda x: self.text_processor.pre_process_doc(x))})) return self def with_space_after_hashtags(self): self.transformations.append((\"str.replace\", {\"pat\": \"#\", \"repl\":",
"item = {key: torch.tensor(val[idx]) for key, val in self.x_train.items()} item['labels'] = torch.tensor(self.y_train[idx], dtype=torch.float)",
"fix HTML tokens # corpus from which the word statistics are going to",
"return self def with_space_after_hashtags(self): self.transformations.append((\"str.replace\", {\"pat\": \"#\", \"repl\": \"# \"})) return self def",
"self.transformations.append((\"str.replace\", {\"pat\": \"[0-9]\", \"repl\": \"\"})) return self def with_stopwords_removal(self): self.transformations.append((\"apply\", {\"func\": (lambda x:",
"# instead of removing punctuations you may replace them \"replace_with_number\":\"\", \"replace_with_digit\":\"\", \"replace_with_currency_symbol\":\"\", \"lang\":\"en\"",
"return self def with_punct_removal(self): self.transformations.append((\"str.replace\", {\"pat\": self.punct, \"repl\": \"'\"})) return self def with_digit_removal(self):",
"with_stopwords_removal(self): self.transformations.append((\"apply\", {\"func\": (lambda x: \" \".join([w for w in x.split(\" \") if",
"return item class Preprocessor: @staticmethod def PreprocessorBuilder(): return Preprocessor() def __init__(self): self.transformations =",
"else: edited_row.append(tok.text.lower()) return ' '.join(edited_row) def with_word_replacement(self): self.transformations.append((\"apply\", {\"func\": (lambda x: re.subn(\"<.*/>\", x[1],",
"torch.utils.data import Dataset # Params for clean_text_param = { \"lower\":False, # lowercase text",
"token \"no_phone_numbers\":False, # replace all phone numbers with a special token \"no_numbers\":False, #",
"dtype=torch.float) return item class Preprocessor: @staticmethod def PreprocessorBuilder(): return Preprocessor() def __init__(self): self.transformations",
"handling } nlp = spacy.load('en_core_web_sm') class Task1Dataset(Dataset): def __init__(self, train_data, labels): self.x_train =",
"\"[‘’]\", \"repl\": \"'\"})) return self def with_possessive_elimination(self): self.transformations.append((\"str.replace\", {\"pat\": \"'s\", \"repl\": \"\"})) return",
"labels): self.x_train = train_data self.y_train = labels def __len__(self): return len(self.y_train) def __getitem__(self,",
"with_ascii_quotes_replacement(self): self.transformations.append((\"str.replace\", {\"pat\": \"[‘’]\", \"repl\": \"'\"})) return self def with_possessive_elimination(self): self.transformations.append((\"str.replace\", {\"pat\": \"'s\",",
"replace all phone numbers with a special token \"no_numbers\":False, # replace all numbers",
"clean from ekphrasis.classes.preprocessor import TextPreProcessor from torch.utils.data import Dataset # Params for clean_text_param"
] |
[
"from django.contrib import admin from django.urls import path, re_path from app import views",
"views.signup, name='signup'), path('profile/', views.profile, name='profile'), path('wishlist/', views.wishlist, name='wishlist'), path('about/', views.about, name='about'), path('model/', views.model,",
"URL to urlpatterns: path('', views.home, name='home') Class-based views 1. Add an import: from",
"Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf",
"views.login, name='login'), path('signup/', views.signup, name='signup'), path('profile/', views.profile, name='profile'), path('wishlist/', views.wishlist, name='wishlist'), path('about/', views.about,",
"function: from django.urls import include, path 2. Add a URL to urlpatterns: path('blog/',",
"Examples: Function views 1. Add an import: from my_app import views 2. Add",
"1. Add an import: from other_app.views import Home 2. Add a URL to",
"Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1. Import",
"views. For more information please see: https://docs.djangoproject.com/en/3.1/topics/http/urls/ Examples: Function views 1. Add an",
"\"\"\"projecto URL Configuration The `urlpatterns` list routes URLs to views. For more information",
"views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based views 1.",
"https://docs.djangoproject.com/en/3.1/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2.",
"from app import views urlpatterns = [ path('admin/', admin.site.urls), path('index/', views.index, name='index'), path('',",
"path('model/', views.model, name='model'), path('add_announce/', views.add_announce, name='add_announce'), path('deleteAccount/', views.deleteAccount, name='deleteAccount'), path('remove_announcement/', views.remove_announcement, name=\"remove_announcement\"), path('fav/',",
"import include, path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) \"\"\" from",
"import admin from django.urls import path, re_path from app import views urlpatterns =",
"name='index'), path('login/', views.login, name='login'), path('signup/', views.signup, name='signup'), path('profile/', views.profile, name='profile'), path('wishlist/', views.wishlist, name='wishlist'),",
"name='add_announce'), path('deleteAccount/', views.deleteAccount, name='deleteAccount'), path('remove_announcement/', views.remove_announcement, name=\"remove_announcement\"), path('fav/', views.fav, name=\"fav\"), path('rev/', views.rev, name=\"rev\"),",
"Configuration The `urlpatterns` list routes URLs to views. For more information please see:",
"import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based views",
"urlpatterns: path('blog/', include('blog.urls')) \"\"\" from django.contrib import admin from django.urls import path, re_path",
"Add an import: from other_app.views import Home 2. Add a URL to urlpatterns:",
"path('wishlist/', views.wishlist, name='wishlist'), path('about/', views.about, name='about'), path('model/', views.model, name='model'), path('add_announce/', views.add_announce, name='add_announce'), path('deleteAccount/',",
"import Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including another",
"django.urls import include, path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) \"\"\"",
"\"\"\" from django.contrib import admin from django.urls import path, re_path from app import",
"2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1.",
"URLconf 1. Import the include() function: from django.urls import include, path 2. Add",
"a URL to urlpatterns: path('', views.home, name='home') Class-based views 1. Add an import:",
"Add an import: from my_app import views 2. Add a URL to urlpatterns:",
"views.about, name='about'), path('model/', views.model, name='model'), path('add_announce/', views.add_announce, name='add_announce'), path('deleteAccount/', views.deleteAccount, name='deleteAccount'), path('remove_announcement/', views.remove_announcement,",
"urlpatterns: path('', views.home, name='home') Class-based views 1. Add an import: from other_app.views import",
"name='wishlist'), path('about/', views.about, name='about'), path('model/', views.model, name='model'), path('add_announce/', views.add_announce, name='add_announce'), path('deleteAccount/', views.deleteAccount, name='deleteAccount'),",
"path('blog/', include('blog.urls')) \"\"\" from django.contrib import admin from django.urls import path, re_path from",
"path('deleteAccount/', views.deleteAccount, name='deleteAccount'), path('remove_announcement/', views.remove_announcement, name=\"remove_announcement\"), path('fav/', views.fav, name=\"fav\"), path('rev/', views.rev, name=\"rev\"), ]",
"please see: https://docs.djangoproject.com/en/3.1/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import",
"a URL to urlpatterns: path('blog/', include('blog.urls')) \"\"\" from django.contrib import admin from django.urls",
"Including another URLconf 1. Import the include() function: from django.urls import include, path",
"path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) \"\"\" from django.contrib import",
"= [ path('admin/', admin.site.urls), path('index/', views.index, name='index'), path('', views.index, name='index'), path('login/', views.login, name='login'),",
"information please see: https://docs.djangoproject.com/en/3.1/topics/http/urls/ Examples: Function views 1. Add an import: from my_app",
"other_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including",
"URL Configuration The `urlpatterns` list routes URLs to views. For more information please",
"path('profile/', views.profile, name='profile'), path('wishlist/', views.wishlist, name='wishlist'), path('about/', views.about, name='about'), path('model/', views.model, name='model'), path('add_announce/',",
"from other_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')",
"routes URLs to views. For more information please see: https://docs.djangoproject.com/en/3.1/topics/http/urls/ Examples: Function views",
"app import views urlpatterns = [ path('admin/', admin.site.urls), path('index/', views.index, name='index'), path('', views.index,",
"include() function: from django.urls import include, path 2. Add a URL to urlpatterns:",
"django.contrib import admin from django.urls import path, re_path from app import views urlpatterns",
"`urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/3.1/topics/http/urls/ Examples:",
"an import: from my_app import views 2. Add a URL to urlpatterns: path('',",
"from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home')",
"import: from other_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as_view(),",
"Add a URL to urlpatterns: path('', views.home, name='home') Class-based views 1. Add an",
"views.index, name='index'), path('login/', views.login, name='login'), path('signup/', views.signup, name='signup'), path('profile/', views.profile, name='profile'), path('wishlist/', views.wishlist,",
"list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/3.1/topics/http/urls/ Examples: Function",
"django.urls import path, re_path from app import views urlpatterns = [ path('admin/', admin.site.urls),",
"views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2.",
"name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add",
"The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/3.1/topics/http/urls/",
"path, re_path from app import views urlpatterns = [ path('admin/', admin.site.urls), path('index/', views.index,",
"from django.urls import include, path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))",
"views 1. Add an import: from my_app import views 2. Add a URL",
"name='model'), path('add_announce/', views.add_announce, name='add_announce'), path('deleteAccount/', views.deleteAccount, name='deleteAccount'), path('remove_announcement/', views.remove_announcement, name=\"remove_announcement\"), path('fav/', views.fav, name=\"fav\"),",
"views.profile, name='profile'), path('wishlist/', views.wishlist, name='wishlist'), path('about/', views.about, name='about'), path('model/', views.model, name='model'), path('add_announce/', views.add_announce,",
"1. Add an import: from my_app import views 2. Add a URL to",
"Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.urls import",
"include('blog.urls')) \"\"\" from django.contrib import admin from django.urls import path, re_path from app",
"views.wishlist, name='wishlist'), path('about/', views.about, name='about'), path('model/', views.model, name='model'), path('add_announce/', views.add_announce, name='add_announce'), path('deleteAccount/', views.deleteAccount,",
"my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based",
"admin from django.urls import path, re_path from app import views urlpatterns = [",
"to urlpatterns: path('', views.home, name='home') Class-based views 1. Add an import: from other_app.views",
"the include() function: from django.urls import include, path 2. Add a URL to",
"name='about'), path('model/', views.model, name='model'), path('add_announce/', views.add_announce, name='add_announce'), path('deleteAccount/', views.deleteAccount, name='deleteAccount'), path('remove_announcement/', views.remove_announcement, name=\"remove_announcement\"),",
"2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) \"\"\" from django.contrib import admin",
"Class-based views 1. Add an import: from other_app.views import Home 2. Add a",
"import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home,",
"Function views 1. Add an import: from my_app import views 2. Add a",
"Import the include() function: from django.urls import include, path 2. Add a URL",
"name='login'), path('signup/', views.signup, name='signup'), path('profile/', views.profile, name='profile'), path('wishlist/', views.wishlist, name='wishlist'), path('about/', views.about, name='about'),",
"views urlpatterns = [ path('admin/', admin.site.urls), path('index/', views.index, name='index'), path('', views.index, name='index'), path('login/',",
"views.model, name='model'), path('add_announce/', views.add_announce, name='add_announce'), path('deleteAccount/', views.deleteAccount, name='deleteAccount'), path('remove_announcement/', views.remove_announcement, name=\"remove_announcement\"), path('fav/', views.fav,",
"path('about/', views.about, name='about'), path('model/', views.model, name='model'), path('add_announce/', views.add_announce, name='add_announce'), path('deleteAccount/', views.deleteAccount, name='deleteAccount'), path('remove_announcement/',",
"name='home') Including another URLconf 1. Import the include() function: from django.urls import include,",
"urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from",
"path('admin/', admin.site.urls), path('index/', views.index, name='index'), path('', views.index, name='index'), path('login/', views.login, name='login'), path('signup/', views.signup,",
"Add a URL to urlpatterns: path('blog/', include('blog.urls')) \"\"\" from django.contrib import admin from",
"path('', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.urls",
"path('', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home",
"URL to urlpatterns: path('blog/', include('blog.urls')) \"\"\" from django.contrib import admin from django.urls import",
"path('', views.index, name='index'), path('login/', views.login, name='login'), path('signup/', views.signup, name='signup'), path('profile/', views.profile, name='profile'), path('wishlist/',",
"views.index, name='index'), path('', views.index, name='index'), path('login/', views.login, name='login'), path('signup/', views.signup, name='signup'), path('profile/', views.profile,",
"see: https://docs.djangoproject.com/en/3.1/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views",
"to urlpatterns: path('blog/', include('blog.urls')) \"\"\" from django.contrib import admin from django.urls import path,",
"to views. For more information please see: https://docs.djangoproject.com/en/3.1/topics/http/urls/ Examples: Function views 1. Add",
"path('login/', views.login, name='login'), path('signup/', views.signup, name='signup'), path('profile/', views.profile, name='profile'), path('wishlist/', views.wishlist, name='wishlist'), path('about/',",
"an import: from other_app.views import Home 2. Add a URL to urlpatterns: path('',",
"For more information please see: https://docs.djangoproject.com/en/3.1/topics/http/urls/ Examples: Function views 1. Add an import:",
"admin.site.urls), path('index/', views.index, name='index'), path('', views.index, name='index'), path('login/', views.login, name='login'), path('signup/', views.signup, name='signup'),",
"URLs to views. For more information please see: https://docs.djangoproject.com/en/3.1/topics/http/urls/ Examples: Function views 1.",
"2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based views 1. Add",
"path('add_announce/', views.add_announce, name='add_announce'), path('deleteAccount/', views.deleteAccount, name='deleteAccount'), path('remove_announcement/', views.remove_announcement, name=\"remove_announcement\"), path('fav/', views.fav, name=\"fav\"), path('rev/',",
"more information please see: https://docs.djangoproject.com/en/3.1/topics/http/urls/ Examples: Function views 1. Add an import: from",
"import path, re_path from app import views urlpatterns = [ path('admin/', admin.site.urls), path('index/',",
"to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1. Import the include() function:",
"path('signup/', views.signup, name='signup'), path('profile/', views.profile, name='profile'), path('wishlist/', views.wishlist, name='wishlist'), path('about/', views.about, name='about'), path('model/',",
"name='index'), path('', views.index, name='index'), path('login/', views.login, name='login'), path('signup/', views.signup, name='signup'), path('profile/', views.profile, name='profile'),",
"1. Import the include() function: from django.urls import include, path 2. Add a",
"a URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1. Import the",
"another URLconf 1. Import the include() function: from django.urls import include, path 2.",
"include, path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) \"\"\" from django.contrib",
"re_path from app import views urlpatterns = [ path('admin/', admin.site.urls), path('index/', views.index, name='index'),",
"urlpatterns = [ path('admin/', admin.site.urls), path('index/', views.index, name='index'), path('', views.index, name='index'), path('login/', views.login,",
"name='signup'), path('profile/', views.profile, name='profile'), path('wishlist/', views.wishlist, name='wishlist'), path('about/', views.about, name='about'), path('model/', views.model, name='model'),",
"views 1. Add an import: from other_app.views import Home 2. Add a URL",
"import views urlpatterns = [ path('admin/', admin.site.urls), path('index/', views.index, name='index'), path('', views.index, name='index'),",
"name='profile'), path('wishlist/', views.wishlist, name='wishlist'), path('about/', views.about, name='about'), path('model/', views.model, name='model'), path('add_announce/', views.add_announce, name='add_announce'),",
"URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1. Import the include()",
"from django.urls import path, re_path from app import views urlpatterns = [ path('admin/',",
"[ path('admin/', admin.site.urls), path('index/', views.index, name='index'), path('', views.index, name='index'), path('login/', views.login, name='login'), path('signup/',",
"views.add_announce, name='add_announce'), path('deleteAccount/', views.deleteAccount, name='deleteAccount'), path('remove_announcement/', views.remove_announcement, name=\"remove_announcement\"), path('fav/', views.fav, name=\"fav\"), path('rev/', views.rev,",
"path('index/', views.index, name='index'), path('', views.index, name='index'), path('login/', views.login, name='login'), path('signup/', views.signup, name='signup'), path('profile/',"
] |
[
"= model_selection.GridSearchCV(svm.SVR(kernel=\"poly\" ), parametres, n_jobs=6) grid_search = grid_search.fit(X_train, y_train) return grid_search def compute_and_output_r2_metric(self,",
"grid_search def compute_and_output_r2_metric(self, trained_grid_search, y_train, y_train_pred, y_test, y_test_pred): self._printResults(y_train, y_train_pred, y_test, y_test_pred, str(trained_grid_search.best_params_))",
"from models.basemodel import BaseModel from sklearn import model_selection, svm class SupportVectorMachineRegressionPoly3(BaseModel): def _train(self,",
"'degree': [2,3,4,5,6]} grid_search = model_selection.GridSearchCV(svm.SVR(kernel=\"poly\" ), parametres, n_jobs=6) grid_search = grid_search.fit(X_train, y_train) return",
"sklearn import model_selection, svm class SupportVectorMachineRegressionPoly3(BaseModel): def _train(self, X_train, y_train): parametres = {'gamma':",
"y_train): parametres = {'gamma': [0.01, 0.1, 1], 'C': [1, 10, 100], 'degree': [2,3,4,5,6]}",
"X_train, y_train): parametres = {'gamma': [0.01, 0.1, 1], 'C': [1, 10, 100], 'degree':",
"), parametres, n_jobs=6) grid_search = grid_search.fit(X_train, y_train) return grid_search def compute_and_output_r2_metric(self, trained_grid_search, y_train,",
"'C': [1, 10, 100], 'degree': [2,3,4,5,6]} grid_search = model_selection.GridSearchCV(svm.SVR(kernel=\"poly\" ), parametres, n_jobs=6) grid_search",
"100], 'degree': [2,3,4,5,6]} grid_search = model_selection.GridSearchCV(svm.SVR(kernel=\"poly\" ), parametres, n_jobs=6) grid_search = grid_search.fit(X_train, y_train)",
"model_selection, svm class SupportVectorMachineRegressionPoly3(BaseModel): def _train(self, X_train, y_train): parametres = {'gamma': [0.01, 0.1,",
"[2,3,4,5,6]} grid_search = model_selection.GridSearchCV(svm.SVR(kernel=\"poly\" ), parametres, n_jobs=6) grid_search = grid_search.fit(X_train, y_train) return grid_search",
"n_jobs=6) grid_search = grid_search.fit(X_train, y_train) return grid_search def compute_and_output_r2_metric(self, trained_grid_search, y_train, y_train_pred, y_test,",
"y_train) return grid_search def compute_and_output_r2_metric(self, trained_grid_search, y_train, y_train_pred, y_test, y_test_pred): self._printResults(y_train, y_train_pred, y_test,",
"SupportVectorMachineRegressionPoly3(BaseModel): def _train(self, X_train, y_train): parametres = {'gamma': [0.01, 0.1, 1], 'C': [1,",
"class SupportVectorMachineRegressionPoly3(BaseModel): def _train(self, X_train, y_train): parametres = {'gamma': [0.01, 0.1, 1], 'C':",
"grid_search = model_selection.GridSearchCV(svm.SVR(kernel=\"poly\" ), parametres, n_jobs=6) grid_search = grid_search.fit(X_train, y_train) return grid_search def",
"models.basemodel import BaseModel from sklearn import model_selection, svm class SupportVectorMachineRegressionPoly3(BaseModel): def _train(self, X_train,",
"BaseModel from sklearn import model_selection, svm class SupportVectorMachineRegressionPoly3(BaseModel): def _train(self, X_train, y_train): parametres",
"import model_selection, svm class SupportVectorMachineRegressionPoly3(BaseModel): def _train(self, X_train, y_train): parametres = {'gamma': [0.01,",
"10, 100], 'degree': [2,3,4,5,6]} grid_search = model_selection.GridSearchCV(svm.SVR(kernel=\"poly\" ), parametres, n_jobs=6) grid_search = grid_search.fit(X_train,",
"import BaseModel from sklearn import model_selection, svm class SupportVectorMachineRegressionPoly3(BaseModel): def _train(self, X_train, y_train):",
"grid_search = grid_search.fit(X_train, y_train) return grid_search def compute_and_output_r2_metric(self, trained_grid_search, y_train, y_train_pred, y_test, y_test_pred):",
"= {'gamma': [0.01, 0.1, 1], 'C': [1, 10, 100], 'degree': [2,3,4,5,6]} grid_search =",
"[1, 10, 100], 'degree': [2,3,4,5,6]} grid_search = model_selection.GridSearchCV(svm.SVR(kernel=\"poly\" ), parametres, n_jobs=6) grid_search =",
"_train(self, X_train, y_train): parametres = {'gamma': [0.01, 0.1, 1], 'C': [1, 10, 100],",
"svm class SupportVectorMachineRegressionPoly3(BaseModel): def _train(self, X_train, y_train): parametres = {'gamma': [0.01, 0.1, 1],",
"= grid_search.fit(X_train, y_train) return grid_search def compute_and_output_r2_metric(self, trained_grid_search, y_train, y_train_pred, y_test, y_test_pred): self._printResults(y_train,",
"return grid_search def compute_and_output_r2_metric(self, trained_grid_search, y_train, y_train_pred, y_test, y_test_pred): self._printResults(y_train, y_train_pred, y_test, y_test_pred,",
"[0.01, 0.1, 1], 'C': [1, 10, 100], 'degree': [2,3,4,5,6]} grid_search = model_selection.GridSearchCV(svm.SVR(kernel=\"poly\" ),",
"0.1, 1], 'C': [1, 10, 100], 'degree': [2,3,4,5,6]} grid_search = model_selection.GridSearchCV(svm.SVR(kernel=\"poly\" ), parametres,",
"from sklearn import model_selection, svm class SupportVectorMachineRegressionPoly3(BaseModel): def _train(self, X_train, y_train): parametres =",
"def _train(self, X_train, y_train): parametres = {'gamma': [0.01, 0.1, 1], 'C': [1, 10,",
"parametres, n_jobs=6) grid_search = grid_search.fit(X_train, y_train) return grid_search def compute_and_output_r2_metric(self, trained_grid_search, y_train, y_train_pred,",
"parametres = {'gamma': [0.01, 0.1, 1], 'C': [1, 10, 100], 'degree': [2,3,4,5,6]} grid_search",
"{'gamma': [0.01, 0.1, 1], 'C': [1, 10, 100], 'degree': [2,3,4,5,6]} grid_search = model_selection.GridSearchCV(svm.SVR(kernel=\"poly\"",
"1], 'C': [1, 10, 100], 'degree': [2,3,4,5,6]} grid_search = model_selection.GridSearchCV(svm.SVR(kernel=\"poly\" ), parametres, n_jobs=6)",
"grid_search.fit(X_train, y_train) return grid_search def compute_and_output_r2_metric(self, trained_grid_search, y_train, y_train_pred, y_test, y_test_pred): self._printResults(y_train, y_train_pred,",
"model_selection.GridSearchCV(svm.SVR(kernel=\"poly\" ), parametres, n_jobs=6) grid_search = grid_search.fit(X_train, y_train) return grid_search def compute_and_output_r2_metric(self, trained_grid_search,"
] |
[
"== \"lb11\" def test_get_list(self, hetzner_client): result = hetzner_client.load_balancer_types.get_list() load_balancer_types = result.load_balancer_types assert load_balancer_types[0].id",
"def test_get_by_id(self, hetzner_client): load_balancer_type = hetzner_client.load_balancer_types.get_by_id(1) assert load_balancer_type.id == 1 assert load_balancer_type.name ==",
"hetzner_client): load_balancer_type = hetzner_client.load_balancer_types.get_by_name(\"lb11\") assert load_balancer_type.id == 1 assert load_balancer_type.name == \"lb11\" def",
"test_get_list(self, hetzner_client): result = hetzner_client.load_balancer_types.get_list() load_balancer_types = result.load_balancer_types assert load_balancer_types[0].id == 1 assert",
"class TestLoadBalancerTypesClient(object): def test_get_by_id(self, hetzner_client): load_balancer_type = hetzner_client.load_balancer_types.get_by_id(1) assert load_balancer_type.id == 1 assert",
"1 assert load_balancer_type.name == \"lb11\" def test_get_list(self, hetzner_client): result = hetzner_client.load_balancer_types.get_list() load_balancer_types =",
"TestLoadBalancerTypesClient(object): def test_get_by_id(self, hetzner_client): load_balancer_type = hetzner_client.load_balancer_types.get_by_id(1) assert load_balancer_type.id == 1 assert load_balancer_type.name",
"def test_get_list(self, hetzner_client): result = hetzner_client.load_balancer_types.get_list() load_balancer_types = result.load_balancer_types assert load_balancer_types[0].id == 1",
"\"lb11\" def test_get_by_name(self, hetzner_client): load_balancer_type = hetzner_client.load_balancer_types.get_by_name(\"lb11\") assert load_balancer_type.id == 1 assert load_balancer_type.name",
"load_balancer_type.id == 1 assert load_balancer_type.name == \"lb11\" def test_get_by_name(self, hetzner_client): load_balancer_type = hetzner_client.load_balancer_types.get_by_name(\"lb11\")",
"== \"lb11\" def test_get_by_name(self, hetzner_client): load_balancer_type = hetzner_client.load_balancer_types.get_by_name(\"lb11\") assert load_balancer_type.id == 1 assert",
"def test_get_by_name(self, hetzner_client): load_balancer_type = hetzner_client.load_balancer_types.get_by_name(\"lb11\") assert load_balancer_type.id == 1 assert load_balancer_type.name ==",
"load_balancer_type = hetzner_client.load_balancer_types.get_by_name(\"lb11\") assert load_balancer_type.id == 1 assert load_balancer_type.name == \"lb11\" def test_get_list(self,",
"hetzner_client.load_balancer_types.get_by_id(1) assert load_balancer_type.id == 1 assert load_balancer_type.name == \"lb11\" def test_get_by_name(self, hetzner_client): load_balancer_type",
"hetzner_client.load_balancer_types.get_by_name(\"lb11\") assert load_balancer_type.id == 1 assert load_balancer_type.name == \"lb11\" def test_get_list(self, hetzner_client): result",
"result = hetzner_client.load_balancer_types.get_list() load_balancer_types = result.load_balancer_types assert load_balancer_types[0].id == 1 assert load_balancer_types[0].name ==",
"hetzner_client): load_balancer_type = hetzner_client.load_balancer_types.get_by_id(1) assert load_balancer_type.id == 1 assert load_balancer_type.name == \"lb11\" def",
"assert load_balancer_type.id == 1 assert load_balancer_type.name == \"lb11\" def test_get_by_name(self, hetzner_client): load_balancer_type =",
"= hetzner_client.load_balancer_types.get_by_id(1) assert load_balancer_type.id == 1 assert load_balancer_type.name == \"lb11\" def test_get_by_name(self, hetzner_client):",
"1 assert load_balancer_type.name == \"lb11\" def test_get_by_name(self, hetzner_client): load_balancer_type = hetzner_client.load_balancer_types.get_by_name(\"lb11\") assert load_balancer_type.id",
"hetzner_client): result = hetzner_client.load_balancer_types.get_list() load_balancer_types = result.load_balancer_types assert load_balancer_types[0].id == 1 assert load_balancer_types[0].name",
"test_get_by_name(self, hetzner_client): load_balancer_type = hetzner_client.load_balancer_types.get_by_name(\"lb11\") assert load_balancer_type.id == 1 assert load_balancer_type.name == \"lb11\"",
"\"lb11\" def test_get_list(self, hetzner_client): result = hetzner_client.load_balancer_types.get_list() load_balancer_types = result.load_balancer_types assert load_balancer_types[0].id ==",
"assert load_balancer_type.name == \"lb11\" def test_get_by_name(self, hetzner_client): load_balancer_type = hetzner_client.load_balancer_types.get_by_name(\"lb11\") assert load_balancer_type.id ==",
"test_get_by_id(self, hetzner_client): load_balancer_type = hetzner_client.load_balancer_types.get_by_id(1) assert load_balancer_type.id == 1 assert load_balancer_type.name == \"lb11\"",
"load_balancer_type.name == \"lb11\" def test_get_list(self, hetzner_client): result = hetzner_client.load_balancer_types.get_list() load_balancer_types = result.load_balancer_types assert",
"assert load_balancer_type.name == \"lb11\" def test_get_list(self, hetzner_client): result = hetzner_client.load_balancer_types.get_list() load_balancer_types = result.load_balancer_types",
"== 1 assert load_balancer_type.name == \"lb11\" def test_get_list(self, hetzner_client): result = hetzner_client.load_balancer_types.get_list() load_balancer_types",
"= hetzner_client.load_balancer_types.get_list() load_balancer_types = result.load_balancer_types assert load_balancer_types[0].id == 1 assert load_balancer_types[0].name == \"lb11\"",
"= hetzner_client.load_balancer_types.get_by_name(\"lb11\") assert load_balancer_type.id == 1 assert load_balancer_type.name == \"lb11\" def test_get_list(self, hetzner_client):",
"load_balancer_type.name == \"lb11\" def test_get_by_name(self, hetzner_client): load_balancer_type = hetzner_client.load_balancer_types.get_by_name(\"lb11\") assert load_balancer_type.id == 1",
"assert load_balancer_type.id == 1 assert load_balancer_type.name == \"lb11\" def test_get_list(self, hetzner_client): result =",
"load_balancer_type = hetzner_client.load_balancer_types.get_by_id(1) assert load_balancer_type.id == 1 assert load_balancer_type.name == \"lb11\" def test_get_by_name(self,",
"<filename>tests/integration/load_balancer_types/test_load_balancer_types.py class TestLoadBalancerTypesClient(object): def test_get_by_id(self, hetzner_client): load_balancer_type = hetzner_client.load_balancer_types.get_by_id(1) assert load_balancer_type.id == 1",
"load_balancer_type.id == 1 assert load_balancer_type.name == \"lb11\" def test_get_list(self, hetzner_client): result = hetzner_client.load_balancer_types.get_list()",
"== 1 assert load_balancer_type.name == \"lb11\" def test_get_by_name(self, hetzner_client): load_balancer_type = hetzner_client.load_balancer_types.get_by_name(\"lb11\") assert"
] |
[
"import sys import os sys.path.append(os.path.dirname(os.path.abspath(os.path.dirname(\"__file__\")))) def parse(path): with open(path, 'r') as f: config",
"import os sys.path.append(os.path.dirname(os.path.abspath(os.path.dirname(\"__file__\")))) def parse(path): with open(path, 'r') as f: config = yaml.safe_load(f)",
"import yaml import sys import os sys.path.append(os.path.dirname(os.path.abspath(os.path.dirname(\"__file__\")))) def parse(path): with open(path, 'r') as",
"os sys.path.append(os.path.dirname(os.path.abspath(os.path.dirname(\"__file__\")))) def parse(path): with open(path, 'r') as f: config = yaml.safe_load(f) f.close()",
"sys import os sys.path.append(os.path.dirname(os.path.abspath(os.path.dirname(\"__file__\")))) def parse(path): with open(path, 'r') as f: config =",
"sys.path.append(os.path.dirname(os.path.abspath(os.path.dirname(\"__file__\")))) def parse(path): with open(path, 'r') as f: config = yaml.safe_load(f) f.close() return",
"yaml import sys import os sys.path.append(os.path.dirname(os.path.abspath(os.path.dirname(\"__file__\")))) def parse(path): with open(path, 'r') as f:",
"<reponame>hin1115/building_extraction_in_satellite_image import yaml import sys import os sys.path.append(os.path.dirname(os.path.abspath(os.path.dirname(\"__file__\")))) def parse(path): with open(path, 'r')",
"def parse(path): with open(path, 'r') as f: config = yaml.safe_load(f) f.close() return config"
] |
[
"@property def set_point(self): return self.__set_point @set_point.setter def set_point(self, value): if value < 0:",
"game_point @property def set_point(self): return self.__set_point @set_point.setter def set_point(self, value): if value <",
"value @property def game_point(self): return self.__game_point @game_point.setter def game_point(self, value): if value <",
"self.__set_point @set_point.setter def set_point(self, value): if value < 0: raise ValueError(\"Negative set point",
"self.name = name self.set_point = set_point self.game_point = game_point @property def set_point(self): return",
"class Player: def __init__(self, name, set_point=0, game_point=0): self.name = name self.set_point = set_point",
"= set_point self.game_point = game_point @property def set_point(self): return self.__set_point @set_point.setter def set_point(self,",
"def set_point(self): return self.__set_point @set_point.setter def set_point(self, value): if value < 0: raise",
"< 0: raise ValueError(\"Negative set point is impossible!\") self.__set_point = value @property def",
"def game_point(self, value): if value < 0: raise ValueError(\"Negative game point is impossible!\")",
"value): if value < 0: raise ValueError(\"Negative game point is impossible!\") self.__game_point =",
"name self.set_point = set_point self.game_point = game_point @property def set_point(self): return self.__set_point @set_point.setter",
"def game_point(self): return self.__game_point @game_point.setter def game_point(self, value): if value < 0: raise",
"self.__set_point = value @property def game_point(self): return self.__game_point @game_point.setter def game_point(self, value): if",
"@property def game_point(self): return self.__game_point @game_point.setter def game_point(self, value): if value < 0:",
"raise ValueError(\"Negative set point is impossible!\") self.__set_point = value @property def game_point(self): return",
"if value < 0: raise ValueError(\"Negative set point is impossible!\") self.__set_point = value",
"impossible!\") self.__set_point = value @property def game_point(self): return self.__game_point @game_point.setter def game_point(self, value):",
"set point is impossible!\") self.__set_point = value @property def game_point(self): return self.__game_point @game_point.setter",
"game_point(self, value): if value < 0: raise ValueError(\"Negative game point is impossible!\") self.__game_point",
"= game_point @property def set_point(self): return self.__set_point @set_point.setter def set_point(self, value): if value",
"@set_point.setter def set_point(self, value): if value < 0: raise ValueError(\"Negative set point is",
"= value @property def game_point(self): return self.__game_point @game_point.setter def game_point(self, value): if value",
"if value < 0: raise ValueError(\"Negative game point is impossible!\") self.__game_point = value",
"set_point(self): return self.__set_point @set_point.setter def set_point(self, value): if value < 0: raise ValueError(\"Negative",
"def set_point(self, value): if value < 0: raise ValueError(\"Negative set point is impossible!\")",
"set_point self.game_point = game_point @property def set_point(self): return self.__set_point @set_point.setter def set_point(self, value):",
"set_point(self, value): if value < 0: raise ValueError(\"Negative set point is impossible!\") self.__set_point",
"value): if value < 0: raise ValueError(\"Negative set point is impossible!\") self.__set_point =",
"= name self.set_point = set_point self.game_point = game_point @property def set_point(self): return self.__set_point",
"def __init__(self, name, set_point=0, game_point=0): self.name = name self.set_point = set_point self.game_point =",
"game_point=0): self.name = name self.set_point = set_point self.game_point = game_point @property def set_point(self):",
"<filename>src/player.py<gh_stars>0 class Player: def __init__(self, name, set_point=0, game_point=0): self.name = name self.set_point =",
"is impossible!\") self.__set_point = value @property def game_point(self): return self.__game_point @game_point.setter def game_point(self,",
"return self.__set_point @set_point.setter def set_point(self, value): if value < 0: raise ValueError(\"Negative set",
"0: raise ValueError(\"Negative set point is impossible!\") self.__set_point = value @property def game_point(self):",
"game_point(self): return self.__game_point @game_point.setter def game_point(self, value): if value < 0: raise ValueError(\"Negative",
"point is impossible!\") self.__set_point = value @property def game_point(self): return self.__game_point @game_point.setter def",
"ValueError(\"Negative set point is impossible!\") self.__set_point = value @property def game_point(self): return self.__game_point",
"return self.__game_point @game_point.setter def game_point(self, value): if value < 0: raise ValueError(\"Negative game",
"self.game_point = game_point @property def set_point(self): return self.__set_point @set_point.setter def set_point(self, value): if",
"self.__game_point @game_point.setter def game_point(self, value): if value < 0: raise ValueError(\"Negative game point",
"@game_point.setter def game_point(self, value): if value < 0: raise ValueError(\"Negative game point is",
"__init__(self, name, set_point=0, game_point=0): self.name = name self.set_point = set_point self.game_point = game_point",
"self.set_point = set_point self.game_point = game_point @property def set_point(self): return self.__set_point @set_point.setter def",
"value < 0: raise ValueError(\"Negative set point is impossible!\") self.__set_point = value @property",
"set_point=0, game_point=0): self.name = name self.set_point = set_point self.game_point = game_point @property def",
"name, set_point=0, game_point=0): self.name = name self.set_point = set_point self.game_point = game_point @property",
"Player: def __init__(self, name, set_point=0, game_point=0): self.name = name self.set_point = set_point self.game_point"
] |
[
"# init the conversion calculation cc = CC.Calc_Conv(config = opt.c) # the energy",
"color = plt.cm.Greens(0.8)) plt.fill_between(EGeV,MedCon['conf_68'][0],y2 = MedCon['conf_68'][1], color = plt.cm.Greens(0.5)) plt.plot(EGeV,MedCon['median'], ls = '-',",
"= CC.Calc_Conv(config = opt.c) # the energy array in GeV EGeV = np.logspace(cc.log10Estart,cc.log10Estop,cc.Estep)",
"= True # calculate the mixing for all energies. If new_angles = True,",
"as plt import PhotALPsConv.calc_conversion as CC from PhotALPsConv.tools import median_contours from optparse import",
"plt.cm.Greens(0.5)) plt.plot(EGeV,MedCon['median'], ls = '-', color = 'gold', label = 'median') label =",
"+ Pu[0], ls = '-', color = '0.', label = label, lw =",
"'-', color = '0.', label = label, lw = 3.) plt.xlabel(\"Energy (GeV)\", size",
"or IGM are included for i in range(cc.nsim): try: cc.scenario.index('Jet') new_angles = False",
"True # calculate the mixing for all energies. If new_angles = True, #",
"= label, lw = 3.) plt.xlabel(\"Energy (GeV)\", size = 'x-large') plt.ylabel(\"Photon survival probability\",",
"calculate the median and 68% and 95% confidence contours MedCon = median_contours(Pt +",
"many realizations if cc.nsim > 1: plt.fill_between(EGeV,MedCon['conf_95'][0],y2 = MedCon['conf_95'][1], color = plt.cm.Greens(0.8)) plt.fill_between(EGeV,MedCon['conf_68'][0],y2",
"Pu[0], ls = '-', color = '0.', label = label, lw = 3.)",
"calculation cc = CC.Calc_Conv(config = opt.c) # the energy array in GeV EGeV",
"# plot the results plt.figure() ax = plt.subplot(111) ax.set_xscale(\"log\") ax.set_yscale(\"log\") # plot the",
"from PhotALPsConv.tools import median_contours from optparse import OptionParser # -------------------------------------------------- # # read",
"# plot the photon survival probability including ALPs plt.plot(EGeV,Pt[0] + Pu[0], ls =",
"matplotlib.pyplot as plt import PhotALPsConv.calc_conversion as CC from PhotALPsConv.tools import median_contours from optparse",
"as CC from PhotALPsConv.tools import median_contours from optparse import OptionParser # -------------------------------------------------- #",
"------------------------------------- # import numpy as np import matplotlib.pyplot as plt import PhotALPsConv.calc_conversion as",
"the different photon (t,u) and ALP (a) polarization states Pt = np.zeros((cc.nsim,EGeV.shape[0])) Pu",
"array in GeV EGeV = np.logspace(cc.log10Estart,cc.log10Estop,cc.Estep) # init matrices that will store the",
"only if ICM or IGM are included for i in range(cc.nsim): try: cc.scenario.index('Jet')",
"label, lw = 3.) plt.xlabel(\"Energy (GeV)\", size = 'x-large') plt.ylabel(\"Photon survival probability\", size",
"dealing with many realizations if cc.nsim > 1: plt.fill_between(EGeV,MedCon['conf_95'][0],y2 = MedCon['conf_95'][1], color =",
"contours MedCon = median_contours(Pt + Pu) # plot the results plt.figure() ax =",
"if ICM or IGM are included for i in range(cc.nsim): try: cc.scenario.index('Jet') new_angles",
"= '0.', label = label, lw = 3.) plt.xlabel(\"Energy (GeV)\", size = 'x-large')",
"parser=OptionParser() parser.add_option(\"-c\",\"--config\",dest=\"c\",help=\"config yaml file\",action=\"store\") (opt, args) = parser.parse_args() # init the conversion calculation",
"init the conversion calculation cc = CC.Calc_Conv(config = opt.c) # the energy array",
"EGeV = np.logspace(cc.log10Estart,cc.log10Estop,cc.Estep) # init matrices that will store the conversion probabilities #",
"+ Pu) # plot the results plt.figure() ax = plt.subplot(111) ax.set_xscale(\"log\") ax.set_yscale(\"log\") #",
"lw = 3.) plt.xlabel(\"Energy (GeV)\", size = 'x-large') plt.ylabel(\"Photon survival probability\", size =",
"68% and 95% confidence contours MedCon = median_contours(Pt + Pu) # plot the",
"= True, # new random angles will be generated for each random realizatioin",
"Pu) # plot the results plt.figure() ax = plt.subplot(111) ax.set_xscale(\"log\") ax.set_yscale(\"log\") # plot",
"confidence contours MedCon = median_contours(Pt + Pu) # plot the results plt.figure() ax",
"ls = '--', color = 'red', label = r'w/o ALPs', lw = 3.)",
"plt.plot(EGeV,Pt[0] + Pu[0], ls = '-', color = '0.', label = label, lw",
"plt.xlabel(\"Energy (GeV)\", size = 'x-large') plt.ylabel(\"Photon survival probability\", size = 'x-large') plt.legend(loc =",
"0 only if ICM or IGM are included for i in range(cc.nsim): try:",
"will store the conversion probabilities # for the different photon (t,u) and ALP",
"realization' else: label = 'w/ ALPs' # plot the standard attenuation plt.plot(EGeV,np.exp(-1. *",
"script to show use of PhotALPsConv.calc_conversion module. # ---- Imports ------------------------------------- # import",
"np.zeros((cc.nsim,EGeV.shape[0])) Pu = np.zeros((cc.nsim,EGeV.shape[0])) Pa = np.zeros((cc.nsim,EGeV.shape[0])) # calculate the mixing, nsim >",
"= 'gold', label = 'median') label = 'one realization' else: label = 'w/",
"cc.scenario.index('Jet') new_angles = False except ValueError: new_angles = True # calculate the mixing",
"are dealing with many realizations if cc.nsim > 1: plt.fill_between(EGeV,MedCon['conf_95'][0],y2 = MedCon['conf_95'][1], color",
"= MedCon['conf_68'][1], color = plt.cm.Greens(0.5)) plt.plot(EGeV,MedCon['median'], ls = '-', color = 'gold', label",
"be generated for each random realizatioin Pt[i],Pu[i],Pa[i] = cc.calc_conversion(EGeV, new_angles = new_angles) #",
"else: label = 'w/ ALPs' # plot the standard attenuation plt.plot(EGeV,np.exp(-1. * cc.ebl_norm",
"will be generated for each random realizatioin Pt[i],Pu[i],Pa[i] = cc.calc_conversion(EGeV, new_angles = new_angles)",
"/ 1e3)[0]), ls = '--', color = 'red', label = r'w/o ALPs', lw",
"= cc.calc_conversion(EGeV, new_angles = new_angles) # calculate the median and 68% and 95%",
"= False except ValueError: new_angles = True # calculate the mixing for all",
"plt.fill_between(EGeV,MedCon['conf_95'][0],y2 = MedCon['conf_95'][1], color = plt.cm.Greens(0.8)) plt.fill_between(EGeV,MedCon['conf_68'][0],y2 = MedCon['conf_68'][1], color = plt.cm.Greens(0.5)) plt.plot(EGeV,MedCon['median'],",
"new_angles = False except ValueError: new_angles = True # calculate the mixing for",
"the conversion calculation cc = CC.Calc_Conv(config = opt.c) # the energy array in",
"'w/ ALPs' # plot the standard attenuation plt.plot(EGeV,np.exp(-1. * cc.ebl_norm * cc.tau.opt_depth_array(cc.z,EGeV /",
"survival probability\", size = 'x-large') plt.legend(loc = 3, fontsize = 'x-large') plt.axis([EGeV[0],EGeV[-1],1e-1,1.1]) plt.show()",
"cc.ebl_norm * cc.tau.opt_depth_array(cc.z,EGeV / 1e3)[0]), ls = '--', color = 'red', label =",
"new_angles) # calculate the median and 68% and 95% confidence contours MedCon =",
"in the config file parser=OptionParser() parser.add_option(\"-c\",\"--config\",dest=\"c\",help=\"config yaml file\",action=\"store\") (opt, args) = parser.parse_args() #",
"# plot the contours if we are dealing with many realizations if cc.nsim",
"'--', color = 'red', label = r'w/o ALPs', lw = 3.) # plot",
"* cc.ebl_norm * cc.tau.opt_depth_array(cc.z,EGeV / 1e3)[0]), ls = '--', color = 'red', label",
"except ValueError: new_angles = True # calculate the mixing for all energies. If",
"realizations if cc.nsim > 1: plt.fill_between(EGeV,MedCon['conf_95'][0],y2 = MedCon['conf_95'][1], color = plt.cm.Greens(0.8)) plt.fill_between(EGeV,MedCon['conf_68'][0],y2 =",
"= 'x-large') plt.ylabel(\"Photon survival probability\", size = 'x-large') plt.legend(loc = 3, fontsize =",
"for each random realizatioin Pt[i],Pu[i],Pa[i] = cc.calc_conversion(EGeV, new_angles = new_angles) # calculate the",
"config file parser=OptionParser() parser.add_option(\"-c\",\"--config\",dest=\"c\",help=\"config yaml file\",action=\"store\") (opt, args) = parser.parse_args() # init the",
"cc = CC.Calc_Conv(config = opt.c) # the energy array in GeV EGeV =",
"that will store the conversion probabilities # for the different photon (t,u) and",
"the mixing for all energies. If new_angles = True, # new random angles",
"each random realizatioin Pt[i],Pu[i],Pa[i] = cc.calc_conversion(EGeV, new_angles = new_angles) # calculate the median",
"new_angles = new_angles) # calculate the median and 68% and 95% confidence contours",
"cc.nsim > 1: plt.fill_between(EGeV,MedCon['conf_95'][0],y2 = MedCon['conf_95'][1], color = plt.cm.Greens(0.8)) plt.fill_between(EGeV,MedCon['conf_68'][0],y2 = MedCon['conf_68'][1], color",
"= plt.cm.Greens(0.8)) plt.fill_between(EGeV,MedCon['conf_68'][0],y2 = MedCon['conf_68'][1], color = plt.cm.Greens(0.5)) plt.plot(EGeV,MedCon['median'], ls = '-', color",
"# calculate the median and 68% and 95% confidence contours MedCon = median_contours(Pt",
"# the energy array in GeV EGeV = np.logspace(cc.log10Estart,cc.log10Estop,cc.Estep) # init matrices that",
"= opt.c) # the energy array in GeV EGeV = np.logspace(cc.log10Estart,cc.log10Estop,cc.Estep) # init",
"random realizatioin Pt[i],Pu[i],Pa[i] = cc.calc_conversion(EGeV, new_angles = new_angles) # calculate the median and",
"> 1: plt.fill_between(EGeV,MedCon['conf_95'][0],y2 = MedCon['conf_95'][1], color = plt.cm.Greens(0.8)) plt.fill_between(EGeV,MedCon['conf_68'][0],y2 = MedCon['conf_68'][1], color =",
"ALPs plt.plot(EGeV,Pt[0] + Pu[0], ls = '-', color = '0.', label = label,",
"# plot the standard attenuation plt.plot(EGeV,np.exp(-1. * cc.ebl_norm * cc.tau.opt_depth_array(cc.z,EGeV / 1e3)[0]), ls",
"label = r'w/o ALPs', lw = 3.) # plot the photon survival probability",
"the config file parser=OptionParser() parser.add_option(\"-c\",\"--config\",dest=\"c\",help=\"config yaml file\",action=\"store\") (opt, args) = parser.parse_args() # init",
"color = '0.', label = label, lw = 3.) plt.xlabel(\"Energy (GeV)\", size =",
"= plt.subplot(111) ax.set_xscale(\"log\") ax.set_yscale(\"log\") # plot the contours if we are dealing with",
"random angles will be generated for each random realizatioin Pt[i],Pu[i],Pa[i] = cc.calc_conversion(EGeV, new_angles",
"GeV EGeV = np.logspace(cc.log10Estart,cc.log10Estop,cc.Estep) # init matrices that will store the conversion probabilities",
"If new_angles = True, # new random angles will be generated for each",
"= parser.parse_args() # init the conversion calculation cc = CC.Calc_Conv(config = opt.c) #",
"as np import matplotlib.pyplot as plt import PhotALPsConv.calc_conversion as CC from PhotALPsConv.tools import",
"CC.Calc_Conv(config = opt.c) # the energy array in GeV EGeV = np.logspace(cc.log10Estart,cc.log10Estop,cc.Estep) #",
"ALP (a) polarization states Pt = np.zeros((cc.nsim,EGeV.shape[0])) Pu = np.zeros((cc.nsim,EGeV.shape[0])) Pa = np.zeros((cc.nsim,EGeV.shape[0]))",
"import OptionParser # -------------------------------------------------- # # read in the config file parser=OptionParser() parser.add_option(\"-c\",\"--config\",dest=\"c\",help=\"config",
"show use of PhotALPsConv.calc_conversion module. # ---- Imports ------------------------------------- # import numpy as",
"all energies. If new_angles = True, # new random angles will be generated",
"from optparse import OptionParser # -------------------------------------------------- # # read in the config file",
"generated for each random realizatioin Pt[i],Pu[i],Pa[i] = cc.calc_conversion(EGeV, new_angles = new_angles) # calculate",
"'0.', label = label, lw = 3.) plt.xlabel(\"Energy (GeV)\", size = 'x-large') plt.ylabel(\"Photon",
"contours if we are dealing with many realizations if cc.nsim > 1: plt.fill_between(EGeV,MedCon['conf_95'][0],y2",
"range(cc.nsim): try: cc.scenario.index('Jet') new_angles = False except ValueError: new_angles = True # calculate",
"(a) polarization states Pt = np.zeros((cc.nsim,EGeV.shape[0])) Pu = np.zeros((cc.nsim,EGeV.shape[0])) Pa = np.zeros((cc.nsim,EGeV.shape[0])) #",
"'x-large') plt.ylabel(\"Photon survival probability\", size = 'x-large') plt.legend(loc = 3, fontsize = 'x-large')",
"read in the config file parser=OptionParser() parser.add_option(\"-c\",\"--config\",dest=\"c\",help=\"config yaml file\",action=\"store\") (opt, args) = parser.parse_args()",
"= new_angles) # calculate the median and 68% and 95% confidence contours MedCon",
"> 0 only if ICM or IGM are included for i in range(cc.nsim):",
"95% confidence contours MedCon = median_contours(Pt + Pu) # plot the results plt.figure()",
"'one realization' else: label = 'w/ ALPs' # plot the standard attenuation plt.plot(EGeV,np.exp(-1.",
"# init matrices that will store the conversion probabilities # for the different",
"Pu = np.zeros((cc.nsim,EGeV.shape[0])) Pa = np.zeros((cc.nsim,EGeV.shape[0])) # calculate the mixing, nsim > 0",
"for i in range(cc.nsim): try: cc.scenario.index('Jet') new_angles = False except ValueError: new_angles =",
"if cc.nsim > 1: plt.fill_between(EGeV,MedCon['conf_95'][0],y2 = MedCon['conf_95'][1], color = plt.cm.Greens(0.8)) plt.fill_between(EGeV,MedCon['conf_68'][0],y2 = MedCon['conf_68'][1],",
"np import matplotlib.pyplot as plt import PhotALPsConv.calc_conversion as CC from PhotALPsConv.tools import median_contours",
"# read in the config file parser=OptionParser() parser.add_option(\"-c\",\"--config\",dest=\"c\",help=\"config yaml file\",action=\"store\") (opt, args) =",
"included for i in range(cc.nsim): try: cc.scenario.index('Jet') new_angles = False except ValueError: new_angles",
"ValueError: new_angles = True # calculate the mixing for all energies. If new_angles",
"angles will be generated for each random realizatioin Pt[i],Pu[i],Pa[i] = cc.calc_conversion(EGeV, new_angles =",
"plot the photon survival probability including ALPs plt.plot(EGeV,Pt[0] + Pu[0], ls = '-',",
"3.) plt.xlabel(\"Energy (GeV)\", size = 'x-large') plt.ylabel(\"Photon survival probability\", size = 'x-large') plt.legend(loc",
"label = 'one realization' else: label = 'w/ ALPs' # plot the standard",
"cc.tau.opt_depth_array(cc.z,EGeV / 1e3)[0]), ls = '--', color = 'red', label = r'w/o ALPs',",
"'median') label = 'one realization' else: label = 'w/ ALPs' # plot the",
"PhotALPsConv.tools import median_contours from optparse import OptionParser # -------------------------------------------------- # # read in",
"CC from PhotALPsConv.tools import median_contours from optparse import OptionParser # -------------------------------------------------- # #",
"the energy array in GeV EGeV = np.logspace(cc.log10Estart,cc.log10Estop,cc.Estep) # init matrices that will",
"= 3.) plt.xlabel(\"Energy (GeV)\", size = 'x-large') plt.ylabel(\"Photon survival probability\", size = 'x-large')",
"---- Imports ------------------------------------- # import numpy as np import matplotlib.pyplot as plt import",
"try: cc.scenario.index('Jet') new_angles = False except ValueError: new_angles = True # calculate the",
"plt import PhotALPsConv.calc_conversion as CC from PhotALPsConv.tools import median_contours from optparse import OptionParser",
"yaml file\",action=\"store\") (opt, args) = parser.parse_args() # init the conversion calculation cc =",
"parser.add_option(\"-c\",\"--config\",dest=\"c\",help=\"config yaml file\",action=\"store\") (opt, args) = parser.parse_args() # init the conversion calculation cc",
"= np.logspace(cc.log10Estart,cc.log10Estop,cc.Estep) # init matrices that will store the conversion probabilities # for",
"MedCon['conf_95'][1], color = plt.cm.Greens(0.8)) plt.fill_between(EGeV,MedCon['conf_68'][0],y2 = MedCon['conf_68'][1], color = plt.cm.Greens(0.5)) plt.plot(EGeV,MedCon['median'], ls =",
"ls = '-', color = 'gold', label = 'median') label = 'one realization'",
"import numpy as np import matplotlib.pyplot as plt import PhotALPsConv.calc_conversion as CC from",
"MedCon = median_contours(Pt + Pu) # plot the results plt.figure() ax = plt.subplot(111)",
"energies. If new_angles = True, # new random angles will be generated for",
"photon (t,u) and ALP (a) polarization states Pt = np.zeros((cc.nsim,EGeV.shape[0])) Pu = np.zeros((cc.nsim,EGeV.shape[0]))",
"standard attenuation plt.plot(EGeV,np.exp(-1. * cc.ebl_norm * cc.tau.opt_depth_array(cc.z,EGeV / 1e3)[0]), ls = '--', color",
"ICM or IGM are included for i in range(cc.nsim): try: cc.scenario.index('Jet') new_angles =",
"# -------------------------------------------------- # # read in the config file parser=OptionParser() parser.add_option(\"-c\",\"--config\",dest=\"c\",help=\"config yaml file\",action=\"store\")",
"# import numpy as np import matplotlib.pyplot as plt import PhotALPsConv.calc_conversion as CC",
"lw = 3.) # plot the photon survival probability including ALPs plt.plot(EGeV,Pt[0] +",
"median and 68% and 95% confidence contours MedCon = median_contours(Pt + Pu) #",
"the conversion probabilities # for the different photon (t,u) and ALP (a) polarization",
"= np.zeros((cc.nsim,EGeV.shape[0])) Pa = np.zeros((cc.nsim,EGeV.shape[0])) # calculate the mixing, nsim > 0 only",
"Pt = np.zeros((cc.nsim,EGeV.shape[0])) Pu = np.zeros((cc.nsim,EGeV.shape[0])) Pa = np.zeros((cc.nsim,EGeV.shape[0])) # calculate the mixing,",
"conversion probabilities # for the different photon (t,u) and ALP (a) polarization states",
"np.logspace(cc.log10Estart,cc.log10Estop,cc.Estep) # init matrices that will store the conversion probabilities # for the",
"= plt.cm.Greens(0.5)) plt.plot(EGeV,MedCon['median'], ls = '-', color = 'gold', label = 'median') label",
"matrices that will store the conversion probabilities # for the different photon (t,u)",
"different photon (t,u) and ALP (a) polarization states Pt = np.zeros((cc.nsim,EGeV.shape[0])) Pu =",
"# calculate the mixing, nsim > 0 only if ICM or IGM are",
"for the different photon (t,u) and ALP (a) polarization states Pt = np.zeros((cc.nsim,EGeV.shape[0]))",
"calculate the mixing, nsim > 0 only if ICM or IGM are included",
"* cc.tau.opt_depth_array(cc.z,EGeV / 1e3)[0]), ls = '--', color = 'red', label = r'w/o",
"plt.subplot(111) ax.set_xscale(\"log\") ax.set_yscale(\"log\") # plot the contours if we are dealing with many",
"ax = plt.subplot(111) ax.set_xscale(\"log\") ax.set_yscale(\"log\") # plot the contours if we are dealing",
"to show use of PhotALPsConv.calc_conversion module. # ---- Imports ------------------------------------- # import numpy",
"mixing, nsim > 0 only if ICM or IGM are included for i",
"results plt.figure() ax = plt.subplot(111) ax.set_xscale(\"log\") ax.set_yscale(\"log\") # plot the contours if we",
"False except ValueError: new_angles = True # calculate the mixing for all energies.",
"(t,u) and ALP (a) polarization states Pt = np.zeros((cc.nsim,EGeV.shape[0])) Pu = np.zeros((cc.nsim,EGeV.shape[0])) Pa",
"PhotALPsConv.calc_conversion as CC from PhotALPsConv.tools import median_contours from optparse import OptionParser # --------------------------------------------------",
"photon survival probability including ALPs plt.plot(EGeV,Pt[0] + Pu[0], ls = '-', color =",
"3.) # plot the photon survival probability including ALPs plt.plot(EGeV,Pt[0] + Pu[0], ls",
"label = label, lw = 3.) plt.xlabel(\"Energy (GeV)\", size = 'x-large') plt.ylabel(\"Photon survival",
"PhotALPsConv.calc_conversion module. # ---- Imports ------------------------------------- # import numpy as np import matplotlib.pyplot",
"1: plt.fill_between(EGeV,MedCon['conf_95'][0],y2 = MedCon['conf_95'][1], color = plt.cm.Greens(0.8)) plt.fill_between(EGeV,MedCon['conf_68'][0],y2 = MedCon['conf_68'][1], color = plt.cm.Greens(0.5))",
"import PhotALPsConv.calc_conversion as CC from PhotALPsConv.tools import median_contours from optparse import OptionParser #",
"= '-', color = 'gold', label = 'median') label = 'one realization' else:",
"= np.zeros((cc.nsim,EGeV.shape[0])) # calculate the mixing, nsim > 0 only if ICM or",
"are included for i in range(cc.nsim): try: cc.scenario.index('Jet') new_angles = False except ValueError:",
"= 'red', label = r'w/o ALPs', lw = 3.) # plot the photon",
"IGM are included for i in range(cc.nsim): try: cc.scenario.index('Jet') new_angles = False except",
"(GeV)\", size = 'x-large') plt.ylabel(\"Photon survival probability\", size = 'x-large') plt.legend(loc = 3,",
"import matplotlib.pyplot as plt import PhotALPsConv.calc_conversion as CC from PhotALPsConv.tools import median_contours from",
"opt.c) # the energy array in GeV EGeV = np.logspace(cc.log10Estart,cc.log10Estop,cc.Estep) # init matrices",
"np.zeros((cc.nsim,EGeV.shape[0])) Pa = np.zeros((cc.nsim,EGeV.shape[0])) # calculate the mixing, nsim > 0 only if",
"if we are dealing with many realizations if cc.nsim > 1: plt.fill_between(EGeV,MedCon['conf_95'][0],y2 =",
"plt.cm.Greens(0.8)) plt.fill_between(EGeV,MedCon['conf_68'][0],y2 = MedCon['conf_68'][1], color = plt.cm.Greens(0.5)) plt.plot(EGeV,MedCon['median'], ls = '-', color =",
"module. # ---- Imports ------------------------------------- # import numpy as np import matplotlib.pyplot as",
"new random angles will be generated for each random realizatioin Pt[i],Pu[i],Pa[i] = cc.calc_conversion(EGeV,",
"plot the standard attenuation plt.plot(EGeV,np.exp(-1. * cc.ebl_norm * cc.tau.opt_depth_array(cc.z,EGeV / 1e3)[0]), ls =",
"# calculate the mixing for all energies. If new_angles = True, # new",
"and 95% confidence contours MedCon = median_contours(Pt + Pu) # plot the results",
"= MedCon['conf_95'][1], color = plt.cm.Greens(0.8)) plt.fill_between(EGeV,MedCon['conf_68'][0],y2 = MedCon['conf_68'][1], color = plt.cm.Greens(0.5)) plt.plot(EGeV,MedCon['median'], ls",
"ALPs', lw = 3.) # plot the photon survival probability including ALPs plt.plot(EGeV,Pt[0]",
"= '-', color = '0.', label = label, lw = 3.) plt.xlabel(\"Energy (GeV)\",",
"attenuation plt.plot(EGeV,np.exp(-1. * cc.ebl_norm * cc.tau.opt_depth_array(cc.z,EGeV / 1e3)[0]), ls = '--', color =",
"for all energies. If new_angles = True, # new random angles will be",
"and 68% and 95% confidence contours MedCon = median_contours(Pt + Pu) # plot",
"import median_contours from optparse import OptionParser # -------------------------------------------------- # # read in the",
"'gold', label = 'median') label = 'one realization' else: label = 'w/ ALPs'",
"including ALPs plt.plot(EGeV,Pt[0] + Pu[0], ls = '-', color = '0.', label =",
"plot the contours if we are dealing with many realizations if cc.nsim >",
"args) = parser.parse_args() # init the conversion calculation cc = CC.Calc_Conv(config = opt.c)",
"file parser=OptionParser() parser.add_option(\"-c\",\"--config\",dest=\"c\",help=\"config yaml file\",action=\"store\") (opt, args) = parser.parse_args() # init the conversion",
"= median_contours(Pt + Pu) # plot the results plt.figure() ax = plt.subplot(111) ax.set_xscale(\"log\")",
"median_contours from optparse import OptionParser # -------------------------------------------------- # # read in the config",
"= np.zeros((cc.nsim,EGeV.shape[0])) Pu = np.zeros((cc.nsim,EGeV.shape[0])) Pa = np.zeros((cc.nsim,EGeV.shape[0])) # calculate the mixing, nsim",
"(opt, args) = parser.parse_args() # init the conversion calculation cc = CC.Calc_Conv(config =",
"ax.set_yscale(\"log\") # plot the contours if we are dealing with many realizations if",
"conversion calculation cc = CC.Calc_Conv(config = opt.c) # the energy array in GeV",
"plot the results plt.figure() ax = plt.subplot(111) ax.set_xscale(\"log\") ax.set_yscale(\"log\") # plot the contours",
"= r'w/o ALPs', lw = 3.) # plot the photon survival probability including",
"use of PhotALPsConv.calc_conversion module. # ---- Imports ------------------------------------- # import numpy as np",
"size = 'x-large') plt.ylabel(\"Photon survival probability\", size = 'x-large') plt.legend(loc = 3, fontsize",
"numpy as np import matplotlib.pyplot as plt import PhotALPsConv.calc_conversion as CC from PhotALPsConv.tools",
"file\",action=\"store\") (opt, args) = parser.parse_args() # init the conversion calculation cc = CC.Calc_Conv(config",
"#Example script to show use of PhotALPsConv.calc_conversion module. # ---- Imports ------------------------------------- #",
"'red', label = r'w/o ALPs', lw = 3.) # plot the photon survival",
"label = 'median') label = 'one realization' else: label = 'w/ ALPs' #",
"with many realizations if cc.nsim > 1: plt.fill_between(EGeV,MedCon['conf_95'][0],y2 = MedCon['conf_95'][1], color = plt.cm.Greens(0.8))",
"ALPs' # plot the standard attenuation plt.plot(EGeV,np.exp(-1. * cc.ebl_norm * cc.tau.opt_depth_array(cc.z,EGeV / 1e3)[0]),",
"-------------------------------------------------- # # read in the config file parser=OptionParser() parser.add_option(\"-c\",\"--config\",dest=\"c\",help=\"config yaml file\",action=\"store\") (opt,",
"OptionParser # -------------------------------------------------- # # read in the config file parser=OptionParser() parser.add_option(\"-c\",\"--config\",dest=\"c\",help=\"config yaml",
"= 'median') label = 'one realization' else: label = 'w/ ALPs' # plot",
"optparse import OptionParser # -------------------------------------------------- # # read in the config file parser=OptionParser()",
"plt.plot(EGeV,MedCon['median'], ls = '-', color = 'gold', label = 'median') label = 'one",
"# new random angles will be generated for each random realizatioin Pt[i],Pu[i],Pa[i] =",
"of PhotALPsConv.calc_conversion module. # ---- Imports ------------------------------------- # import numpy as np import",
"and ALP (a) polarization states Pt = np.zeros((cc.nsim,EGeV.shape[0])) Pu = np.zeros((cc.nsim,EGeV.shape[0])) Pa =",
"in GeV EGeV = np.logspace(cc.log10Estart,cc.log10Estop,cc.Estep) # init matrices that will store the conversion",
"nsim > 0 only if ICM or IGM are included for i in",
"plt.figure() ax = plt.subplot(111) ax.set_xscale(\"log\") ax.set_yscale(\"log\") # plot the contours if we are",
"= 3.) # plot the photon survival probability including ALPs plt.plot(EGeV,Pt[0] + Pu[0],",
"store the conversion probabilities # for the different photon (t,u) and ALP (a)",
"probabilities # for the different photon (t,u) and ALP (a) polarization states Pt",
"True, # new random angles will be generated for each random realizatioin Pt[i],Pu[i],Pa[i]",
"= 'one realization' else: label = 'w/ ALPs' # plot the standard attenuation",
"the results plt.figure() ax = plt.subplot(111) ax.set_xscale(\"log\") ax.set_yscale(\"log\") # plot the contours if",
"plt.plot(EGeV,np.exp(-1. * cc.ebl_norm * cc.tau.opt_depth_array(cc.z,EGeV / 1e3)[0]), ls = '--', color = 'red',",
"polarization states Pt = np.zeros((cc.nsim,EGeV.shape[0])) Pu = np.zeros((cc.nsim,EGeV.shape[0])) Pa = np.zeros((cc.nsim,EGeV.shape[0])) # calculate",
"the contours if we are dealing with many realizations if cc.nsim > 1:",
"Pa = np.zeros((cc.nsim,EGeV.shape[0])) # calculate the mixing, nsim > 0 only if ICM",
"the photon survival probability including ALPs plt.plot(EGeV,Pt[0] + Pu[0], ls = '-', color",
"label = 'w/ ALPs' # plot the standard attenuation plt.plot(EGeV,np.exp(-1. * cc.ebl_norm *",
"realizatioin Pt[i],Pu[i],Pa[i] = cc.calc_conversion(EGeV, new_angles = new_angles) # calculate the median and 68%",
"Imports ------------------------------------- # import numpy as np import matplotlib.pyplot as plt import PhotALPsConv.calc_conversion",
"color = plt.cm.Greens(0.5)) plt.plot(EGeV,MedCon['median'], ls = '-', color = 'gold', label = 'median')",
"# # read in the config file parser=OptionParser() parser.add_option(\"-c\",\"--config\",dest=\"c\",help=\"config yaml file\",action=\"store\") (opt, args)",
"calculate the mixing for all energies. If new_angles = True, # new random",
"= 'w/ ALPs' # plot the standard attenuation plt.plot(EGeV,np.exp(-1. * cc.ebl_norm * cc.tau.opt_depth_array(cc.z,EGeV",
"new_angles = True # calculate the mixing for all energies. If new_angles =",
"np.zeros((cc.nsim,EGeV.shape[0])) # calculate the mixing, nsim > 0 only if ICM or IGM",
"plt.ylabel(\"Photon survival probability\", size = 'x-large') plt.legend(loc = 3, fontsize = 'x-large') plt.axis([EGeV[0],EGeV[-1],1e-1,1.1])",
"ax.set_xscale(\"log\") ax.set_yscale(\"log\") # plot the contours if we are dealing with many realizations",
"mixing for all energies. If new_angles = True, # new random angles will",
"ls = '-', color = '0.', label = label, lw = 3.) plt.xlabel(\"Energy",
"in range(cc.nsim): try: cc.scenario.index('Jet') new_angles = False except ValueError: new_angles = True #",
"cc.calc_conversion(EGeV, new_angles = new_angles) # calculate the median and 68% and 95% confidence",
"parser.parse_args() # init the conversion calculation cc = CC.Calc_Conv(config = opt.c) # the",
"we are dealing with many realizations if cc.nsim > 1: plt.fill_between(EGeV,MedCon['conf_95'][0],y2 = MedCon['conf_95'][1],",
"= '--', color = 'red', label = r'w/o ALPs', lw = 3.) #",
"energy array in GeV EGeV = np.logspace(cc.log10Estart,cc.log10Estop,cc.Estep) # init matrices that will store",
"new_angles = True, # new random angles will be generated for each random",
"'-', color = 'gold', label = 'median') label = 'one realization' else: label",
"r'w/o ALPs', lw = 3.) # plot the photon survival probability including ALPs",
"the standard attenuation plt.plot(EGeV,np.exp(-1. * cc.ebl_norm * cc.tau.opt_depth_array(cc.z,EGeV / 1e3)[0]), ls = '--',",
"# ---- Imports ------------------------------------- # import numpy as np import matplotlib.pyplot as plt",
"probability including ALPs plt.plot(EGeV,Pt[0] + Pu[0], ls = '-', color = '0.', label",
"states Pt = np.zeros((cc.nsim,EGeV.shape[0])) Pu = np.zeros((cc.nsim,EGeV.shape[0])) Pa = np.zeros((cc.nsim,EGeV.shape[0])) # calculate the",
"median_contours(Pt + Pu) # plot the results plt.figure() ax = plt.subplot(111) ax.set_xscale(\"log\") ax.set_yscale(\"log\")",
"plt.fill_between(EGeV,MedCon['conf_68'][0],y2 = MedCon['conf_68'][1], color = plt.cm.Greens(0.5)) plt.plot(EGeV,MedCon['median'], ls = '-', color = 'gold',",
"Pt[i],Pu[i],Pa[i] = cc.calc_conversion(EGeV, new_angles = new_angles) # calculate the median and 68% and",
"MedCon['conf_68'][1], color = plt.cm.Greens(0.5)) plt.plot(EGeV,MedCon['median'], ls = '-', color = 'gold', label =",
"init matrices that will store the conversion probabilities # for the different photon",
"color = 'red', label = r'w/o ALPs', lw = 3.) # plot the",
"the median and 68% and 95% confidence contours MedCon = median_contours(Pt + Pu)",
"# for the different photon (t,u) and ALP (a) polarization states Pt =",
"1e3)[0]), ls = '--', color = 'red', label = r'w/o ALPs', lw =",
"the mixing, nsim > 0 only if ICM or IGM are included for",
"survival probability including ALPs plt.plot(EGeV,Pt[0] + Pu[0], ls = '-', color = '0.',",
"i in range(cc.nsim): try: cc.scenario.index('Jet') new_angles = False except ValueError: new_angles = True",
"color = 'gold', label = 'median') label = 'one realization' else: label ="
] |
[
"of create video-stream \"\"\" fourcc = cv2.cv.CV_FOURCC(**list(fourcc_str)) fid = cv2.VideoWriter(filename, fourcc, fps, clip.shape[0:2])",
"cv2.cv.CV_FOURCC(**list(fourcc_str)) fid = cv2.VideoWriter(filename, fourcc, fps, clip.shape[0:2]) if fid.isOpened(): for i in xrange(clip.shape[0]):",
"to generate clip : ndarray ndarray where first dimension is used to refer",
"ndarray ndarray where first dimension is used to refer to i-th frame fourcc_str",
"fps, clip.shape[0:2]) if fid.isOpened(): for i in xrange(clip.shape[0]): fid.write(clip[i, ...]) return True else:",
"clip, fourcc_str='X264', fps=30.0): \"\"\"Write video on disk from a stack of images Parameters",
": str Fullpath of video-file to generate clip : ndarray ndarray where first",
"to retrieve fourcc from opencv fps : float frame rate of create video-stream",
"video-stream \"\"\" fourcc = cv2.cv.CV_FOURCC(**list(fourcc_str)) fid = cv2.VideoWriter(filename, fourcc, fps, clip.shape[0:2]) if fid.isOpened():",
"disk from a stack of images Parameters ---------- filename : str Fullpath of",
"dimension is used to refer to i-th frame fourcc_str : str str to",
"clip.shape[0:2]) if fid.isOpened(): for i in xrange(clip.shape[0]): fid.write(clip[i, ...]) return True else: return",
": str str to retrieve fourcc from opencv fps : float frame rate",
"float frame rate of create video-stream \"\"\" fourcc = cv2.cv.CV_FOURCC(**list(fourcc_str)) fid = cv2.VideoWriter(filename,",
"cv2 def dump_video(filename, clip, fourcc_str='X264', fps=30.0): \"\"\"Write video on disk from a stack",
"fourcc_str='X264', fps=30.0): \"\"\"Write video on disk from a stack of images Parameters ----------",
"Fullpath of video-file to generate clip : ndarray ndarray where first dimension is",
"= cv2.cv.CV_FOURCC(**list(fourcc_str)) fid = cv2.VideoWriter(filename, fourcc, fps, clip.shape[0:2]) if fid.isOpened(): for i in",
"frame fourcc_str : str str to retrieve fourcc from opencv fps : float",
"rate of create video-stream \"\"\" fourcc = cv2.cv.CV_FOURCC(**list(fourcc_str)) fid = cv2.VideoWriter(filename, fourcc, fps,",
"first dimension is used to refer to i-th frame fourcc_str : str str",
"<filename>daps/utils/deprecated/video.py import cv2 def dump_video(filename, clip, fourcc_str='X264', fps=30.0): \"\"\"Write video on disk from",
"to refer to i-th frame fourcc_str : str str to retrieve fourcc from",
"refer to i-th frame fourcc_str : str str to retrieve fourcc from opencv",
"fourcc_str : str str to retrieve fourcc from opencv fps : float frame",
"def dump_video(filename, clip, fourcc_str='X264', fps=30.0): \"\"\"Write video on disk from a stack of",
"import cv2 def dump_video(filename, clip, fourcc_str='X264', fps=30.0): \"\"\"Write video on disk from a",
"retrieve fourcc from opencv fps : float frame rate of create video-stream \"\"\"",
"fourcc, fps, clip.shape[0:2]) if fid.isOpened(): for i in xrange(clip.shape[0]): fid.write(clip[i, ...]) return True",
"opencv fps : float frame rate of create video-stream \"\"\" fourcc = cv2.cv.CV_FOURCC(**list(fourcc_str))",
"of video-file to generate clip : ndarray ndarray where first dimension is used",
"fps : float frame rate of create video-stream \"\"\" fourcc = cv2.cv.CV_FOURCC(**list(fourcc_str)) fid",
"generate clip : ndarray ndarray where first dimension is used to refer to",
"where first dimension is used to refer to i-th frame fourcc_str : str",
"of images Parameters ---------- filename : str Fullpath of video-file to generate clip",
"a stack of images Parameters ---------- filename : str Fullpath of video-file to",
"used to refer to i-th frame fourcc_str : str str to retrieve fourcc",
"---------- filename : str Fullpath of video-file to generate clip : ndarray ndarray",
"= cv2.VideoWriter(filename, fourcc, fps, clip.shape[0:2]) if fid.isOpened(): for i in xrange(clip.shape[0]): fid.write(clip[i, ...])",
"create video-stream \"\"\" fourcc = cv2.cv.CV_FOURCC(**list(fourcc_str)) fid = cv2.VideoWriter(filename, fourcc, fps, clip.shape[0:2]) if",
"clip : ndarray ndarray where first dimension is used to refer to i-th",
"\"\"\" fourcc = cv2.cv.CV_FOURCC(**list(fourcc_str)) fid = cv2.VideoWriter(filename, fourcc, fps, clip.shape[0:2]) if fid.isOpened(): for",
"from opencv fps : float frame rate of create video-stream \"\"\" fourcc =",
"to i-th frame fourcc_str : str str to retrieve fourcc from opencv fps",
"fourcc = cv2.cv.CV_FOURCC(**list(fourcc_str)) fid = cv2.VideoWriter(filename, fourcc, fps, clip.shape[0:2]) if fid.isOpened(): for i",
": float frame rate of create video-stream \"\"\" fourcc = cv2.cv.CV_FOURCC(**list(fourcc_str)) fid =",
"frame rate of create video-stream \"\"\" fourcc = cv2.cv.CV_FOURCC(**list(fourcc_str)) fid = cv2.VideoWriter(filename, fourcc,",
"video on disk from a stack of images Parameters ---------- filename : str",
"ndarray where first dimension is used to refer to i-th frame fourcc_str :",
"fourcc from opencv fps : float frame rate of create video-stream \"\"\" fourcc",
"if fid.isOpened(): for i in xrange(clip.shape[0]): fid.write(clip[i, ...]) return True else: return False",
"Parameters ---------- filename : str Fullpath of video-file to generate clip : ndarray",
"cv2.VideoWriter(filename, fourcc, fps, clip.shape[0:2]) if fid.isOpened(): for i in xrange(clip.shape[0]): fid.write(clip[i, ...]) return",
"str str to retrieve fourcc from opencv fps : float frame rate of",
"stack of images Parameters ---------- filename : str Fullpath of video-file to generate",
"images Parameters ---------- filename : str Fullpath of video-file to generate clip :",
"filename : str Fullpath of video-file to generate clip : ndarray ndarray where",
": ndarray ndarray where first dimension is used to refer to i-th frame",
"i-th frame fourcc_str : str str to retrieve fourcc from opencv fps :",
"str to retrieve fourcc from opencv fps : float frame rate of create",
"fid = cv2.VideoWriter(filename, fourcc, fps, clip.shape[0:2]) if fid.isOpened(): for i in xrange(clip.shape[0]): fid.write(clip[i,",
"str Fullpath of video-file to generate clip : ndarray ndarray where first dimension",
"\"\"\"Write video on disk from a stack of images Parameters ---------- filename :",
"from a stack of images Parameters ---------- filename : str Fullpath of video-file",
"dump_video(filename, clip, fourcc_str='X264', fps=30.0): \"\"\"Write video on disk from a stack of images",
"video-file to generate clip : ndarray ndarray where first dimension is used to",
"is used to refer to i-th frame fourcc_str : str str to retrieve",
"fps=30.0): \"\"\"Write video on disk from a stack of images Parameters ---------- filename",
"on disk from a stack of images Parameters ---------- filename : str Fullpath"
] |
[
"divisor \"\"\" return functools.reduce(math.gcd, numbers) def lcm(*numbers): \"\"\" least common multiple \"\"\" return",
"a, b: (a * b) // gcd(a, b), numbers, 1) # la réponse",
"\"\"\" least common multiple \"\"\" return functools.reduce(lambda a, b: (a * b) //",
"list(map(int, input().split())) x = A[0] B = [x] i = 1 while i",
"ppcm \"glissant\" des Ai for _ in range(int(input())): n = int(input()) A =",
"= list(map(int, input().split())) x = A[0] B = [x] i = 1 while",
"Number Theory > John and GCD list # Help John in making a",
"math import functools def gcd(*numbers): \"\"\" greatest common divisor \"\"\" return functools.reduce(math.gcd, numbers)",
"Mathematics > Number Theory > John and GCD list # Help John in",
"= A[0] B = [x] i = 1 while i < n: y",
"Theory > John and GCD list # Help John in making a list",
"functools.reduce(math.gcd, numbers) def lcm(*numbers): \"\"\" least common multiple \"\"\" return functools.reduce(lambda a, b:",
"< n: y = A[i] B.append(lcm(x, y)) x = y i += 1",
"lcm(*numbers): \"\"\" least common multiple \"\"\" return functools.reduce(lambda a, b: (a * b)",
"\"\"\" return functools.reduce(math.gcd, numbers) def lcm(*numbers): \"\"\" least common multiple \"\"\" return functools.reduce(lambda",
"= 1 while i < n: y = A[i] B.append(lcm(x, y)) x =",
"functools def gcd(*numbers): \"\"\" greatest common divisor \"\"\" return functools.reduce(math.gcd, numbers) def lcm(*numbers):",
"int(input()) A = list(map(int, input().split())) x = A[0] B = [x] i =",
"i = 1 while i < n: y = A[i] B.append(lcm(x, y)) x",
"John in making a list from GCD list # # https://www.hackerrank.com/challenges/john-and-gcd-list/problem # import",
"def lcm(*numbers): \"\"\" least common multiple \"\"\" return functools.reduce(lambda a, b: (a *",
"functools.reduce(lambda a, b: (a * b) // gcd(a, b), numbers, 1) # la",
"# Mathematics > Number Theory > John and GCD list # Help John",
"list from GCD list # # https://www.hackerrank.com/challenges/john-and-gcd-list/problem # import math import functools def",
"n = int(input()) A = list(map(int, input().split())) x = A[0] B = [x]",
"* b) // gcd(a, b), numbers, 1) # la réponse est le ppcm",
"import functools def gcd(*numbers): \"\"\" greatest common divisor \"\"\" return functools.reduce(math.gcd, numbers) def",
"list # # https://www.hackerrank.com/challenges/john-and-gcd-list/problem # import math import functools def gcd(*numbers): \"\"\" greatest",
"import math import functools def gcd(*numbers): \"\"\" greatest common divisor \"\"\" return functools.reduce(math.gcd,",
"n: y = A[i] B.append(lcm(x, y)) x = y i += 1 B.append(A[-1])",
"// gcd(a, b), numbers, 1) # la réponse est le ppcm \"glissant\" des",
"= [x] i = 1 while i < n: y = A[i] B.append(lcm(x,",
"i < n: y = A[i] B.append(lcm(x, y)) x = y i +=",
"common divisor \"\"\" return functools.reduce(math.gcd, numbers) def lcm(*numbers): \"\"\" least common multiple \"\"\"",
"common multiple \"\"\" return functools.reduce(lambda a, b: (a * b) // gcd(a, b),",
"\"glissant\" des Ai for _ in range(int(input())): n = int(input()) A = list(map(int,",
"while i < n: y = A[i] B.append(lcm(x, y)) x = y i",
"list # Help John in making a list from GCD list # #",
"input().split())) x = A[0] B = [x] i = 1 while i <",
"return functools.reduce(lambda a, b: (a * b) // gcd(a, b), numbers, 1) #",
"numbers, 1) # la réponse est le ppcm \"glissant\" des Ai for _",
"GCD list # # https://www.hackerrank.com/challenges/john-and-gcd-list/problem # import math import functools def gcd(*numbers): \"\"\"",
"(a * b) // gcd(a, b), numbers, 1) # la réponse est le",
"a list from GCD list # # https://www.hackerrank.com/challenges/john-and-gcd-list/problem # import math import functools",
"\"\"\" return functools.reduce(lambda a, b: (a * b) // gcd(a, b), numbers, 1)",
"Help John in making a list from GCD list # # https://www.hackerrank.com/challenges/john-and-gcd-list/problem #",
"def gcd(*numbers): \"\"\" greatest common divisor \"\"\" return functools.reduce(math.gcd, numbers) def lcm(*numbers): \"\"\"",
"Ai for _ in range(int(input())): n = int(input()) A = list(map(int, input().split())) x",
"> John and GCD list # Help John in making a list from",
"# # https://www.hackerrank.com/challenges/john-and-gcd-list/problem # import math import functools def gcd(*numbers): \"\"\" greatest common",
"A[0] B = [x] i = 1 while i < n: y =",
"le ppcm \"glissant\" des Ai for _ in range(int(input())): n = int(input()) A",
"range(int(input())): n = int(input()) A = list(map(int, input().split())) x = A[0] B =",
"# import math import functools def gcd(*numbers): \"\"\" greatest common divisor \"\"\" return",
"gcd(a, b), numbers, 1) # la réponse est le ppcm \"glissant\" des Ai",
"= int(input()) A = list(map(int, input().split())) x = A[0] B = [x] i",
"greatest common divisor \"\"\" return functools.reduce(math.gcd, numbers) def lcm(*numbers): \"\"\" least common multiple",
"[x] i = 1 while i < n: y = A[i] B.append(lcm(x, y))",
"from GCD list # # https://www.hackerrank.com/challenges/john-and-gcd-list/problem # import math import functools def gcd(*numbers):",
"least common multiple \"\"\" return functools.reduce(lambda a, b: (a * b) // gcd(a,",
"est le ppcm \"glissant\" des Ai for _ in range(int(input())): n = int(input())",
"B = [x] i = 1 while i < n: y = A[i]",
"for _ in range(int(input())): n = int(input()) A = list(map(int, input().split())) x =",
"> Number Theory > John and GCD list # Help John in making",
"return functools.reduce(math.gcd, numbers) def lcm(*numbers): \"\"\" least common multiple \"\"\" return functools.reduce(lambda a,",
"in range(int(input())): n = int(input()) A = list(map(int, input().split())) x = A[0] B",
"# Help John in making a list from GCD list # # https://www.hackerrank.com/challenges/john-and-gcd-list/problem",
"\"\"\" greatest common divisor \"\"\" return functools.reduce(math.gcd, numbers) def lcm(*numbers): \"\"\" least common",
"John and GCD list # Help John in making a list from GCD",
"1 while i < n: y = A[i] B.append(lcm(x, y)) x = y",
"# la réponse est le ppcm \"glissant\" des Ai for _ in range(int(input())):",
"making a list from GCD list # # https://www.hackerrank.com/challenges/john-and-gcd-list/problem # import math import",
"https://www.hackerrank.com/challenges/john-and-gcd-list/problem # import math import functools def gcd(*numbers): \"\"\" greatest common divisor \"\"\"",
"la réponse est le ppcm \"glissant\" des Ai for _ in range(int(input())): n",
"y = A[i] B.append(lcm(x, y)) x = y i += 1 B.append(A[-1]) print(*B)",
"b) // gcd(a, b), numbers, 1) # la réponse est le ppcm \"glissant\"",
"A = list(map(int, input().split())) x = A[0] B = [x] i = 1",
"b: (a * b) // gcd(a, b), numbers, 1) # la réponse est",
"gcd(*numbers): \"\"\" greatest common divisor \"\"\" return functools.reduce(math.gcd, numbers) def lcm(*numbers): \"\"\" least",
"réponse est le ppcm \"glissant\" des Ai for _ in range(int(input())): n =",
"# https://www.hackerrank.com/challenges/john-and-gcd-list/problem # import math import functools def gcd(*numbers): \"\"\" greatest common divisor",
"des Ai for _ in range(int(input())): n = int(input()) A = list(map(int, input().split()))",
"in making a list from GCD list # # https://www.hackerrank.com/challenges/john-and-gcd-list/problem # import math",
"numbers) def lcm(*numbers): \"\"\" least common multiple \"\"\" return functools.reduce(lambda a, b: (a",
"GCD list # Help John in making a list from GCD list #",
"and GCD list # Help John in making a list from GCD list",
"_ in range(int(input())): n = int(input()) A = list(map(int, input().split())) x = A[0]",
"x = A[0] B = [x] i = 1 while i < n:",
"multiple \"\"\" return functools.reduce(lambda a, b: (a * b) // gcd(a, b), numbers,",
"b), numbers, 1) # la réponse est le ppcm \"glissant\" des Ai for",
"1) # la réponse est le ppcm \"glissant\" des Ai for _ in"
] |
[
"7, 9)) print(numbers_searching(50, 50, 47, 47, 48, 45, 49, 44, 47, 45, 44,",
"5, 9, 10, 7, 8, 7, 9)) print(numbers_searching(50, 50, 47, 47, 48, 45,",
"2, 4, 2, 5, 4)) print(numbers_searching(5, 5, 9, 10, 7, 8, 7, 9))",
"min(args), max(args) for search_num in range(min_num, max_num + 1): if search_num not in",
"9, 10, 7, 8, 7, 9)) print(numbers_searching(50, 50, 47, 47, 48, 45, 49,",
"1: duplicate_nums.append(number) answer.append(sorted(duplicate_nums)) return answer print(numbers_searching(1, 2, 4, 2, 5, 4)) print(numbers_searching(5, 5,",
"4, 2, 5, 4)) print(numbers_searching(5, 5, 9, 10, 7, 8, 7, 9)) print(numbers_searching(50,",
"return answer print(numbers_searching(1, 2, 4, 2, 5, 4)) print(numbers_searching(5, 5, 9, 10, 7,",
"= [] min_num, max_num = min(args), max(args) for search_num in range(min_num, max_num +",
"2, 5, 4)) print(numbers_searching(5, 5, 9, 10, 7, 8, 7, 9)) print(numbers_searching(50, 50,",
"9)) print(numbers_searching(50, 50, 47, 47, 48, 45, 49, 44, 47, 45, 44, 44,",
"print(numbers_searching(5, 5, 9, 10, 7, 8, 7, 9)) print(numbers_searching(50, 50, 47, 47, 48,",
"5, 4)) print(numbers_searching(5, 5, 9, 10, 7, 8, 7, 9)) print(numbers_searching(50, 50, 47,",
"[] min_num, max_num = min(args), max(args) for search_num in range(min_num, max_num + 1):",
"8, 7, 9)) print(numbers_searching(50, 50, 47, 47, 48, 45, 49, 44, 47, 45,",
"4)) print(numbers_searching(5, 5, 9, 10, 7, 8, 7, 9)) print(numbers_searching(50, 50, 47, 47,",
"if search_num not in args: answer.append(search_num) for number in set(args): if args.count(number) >",
"args: answer.append(search_num) for number in set(args): if args.count(number) > 1: duplicate_nums.append(number) answer.append(sorted(duplicate_nums)) return",
"+ 1): if search_num not in args: answer.append(search_num) for number in set(args): if",
"max(args) for search_num in range(min_num, max_num + 1): if search_num not in args:",
"> 1: duplicate_nums.append(number) answer.append(sorted(duplicate_nums)) return answer print(numbers_searching(1, 2, 4, 2, 5, 4)) print(numbers_searching(5,",
"duplicate_nums.append(number) answer.append(sorted(duplicate_nums)) return answer print(numbers_searching(1, 2, 4, 2, 5, 4)) print(numbers_searching(5, 5, 9,",
"search_num not in args: answer.append(search_num) for number in set(args): if args.count(number) > 1:",
"answer print(numbers_searching(1, 2, 4, 2, 5, 4)) print(numbers_searching(5, 5, 9, 10, 7, 8,",
"[] duplicate_nums = [] min_num, max_num = min(args), max(args) for search_num in range(min_num,",
"7, 8, 7, 9)) print(numbers_searching(50, 50, 47, 47, 48, 45, 49, 44, 47,",
"answer = [] duplicate_nums = [] min_num, max_num = min(args), max(args) for search_num",
"= min(args), max(args) for search_num in range(min_num, max_num + 1): if search_num not",
"print(numbers_searching(1, 2, 4, 2, 5, 4)) print(numbers_searching(5, 5, 9, 10, 7, 8, 7,",
"print(numbers_searching(50, 50, 47, 47, 48, 45, 49, 44, 47, 45, 44, 44, 48,",
"max_num = min(args), max(args) for search_num in range(min_num, max_num + 1): if search_num",
"in args: answer.append(search_num) for number in set(args): if args.count(number) > 1: duplicate_nums.append(number) answer.append(sorted(duplicate_nums))",
"duplicate_nums = [] min_num, max_num = min(args), max(args) for search_num in range(min_num, max_num",
"= [] duplicate_nums = [] min_num, max_num = min(args), max(args) for search_num in",
"answer.append(sorted(duplicate_nums)) return answer print(numbers_searching(1, 2, 4, 2, 5, 4)) print(numbers_searching(5, 5, 9, 10,",
"not in args: answer.append(search_num) for number in set(args): if args.count(number) > 1: duplicate_nums.append(number)",
"answer.append(search_num) for number in set(args): if args.count(number) > 1: duplicate_nums.append(number) answer.append(sorted(duplicate_nums)) return answer",
"number in set(args): if args.count(number) > 1: duplicate_nums.append(number) answer.append(sorted(duplicate_nums)) return answer print(numbers_searching(1, 2,",
"def numbers_searching(*args): answer = [] duplicate_nums = [] min_num, max_num = min(args), max(args)",
"in set(args): if args.count(number) > 1: duplicate_nums.append(number) answer.append(sorted(duplicate_nums)) return answer print(numbers_searching(1, 2, 4,",
"47, 47, 48, 45, 49, 44, 47, 45, 44, 44, 48, 44, 48))",
"50, 47, 47, 48, 45, 49, 44, 47, 45, 44, 44, 48, 44,",
"for search_num in range(min_num, max_num + 1): if search_num not in args: answer.append(search_num)",
"search_num in range(min_num, max_num + 1): if search_num not in args: answer.append(search_num) for",
"range(min_num, max_num + 1): if search_num not in args: answer.append(search_num) for number in",
"min_num, max_num = min(args), max(args) for search_num in range(min_num, max_num + 1): if",
"max_num + 1): if search_num not in args: answer.append(search_num) for number in set(args):",
"numbers_searching(*args): answer = [] duplicate_nums = [] min_num, max_num = min(args), max(args) for",
"1): if search_num not in args: answer.append(search_num) for number in set(args): if args.count(number)",
"for number in set(args): if args.count(number) > 1: duplicate_nums.append(number) answer.append(sorted(duplicate_nums)) return answer print(numbers_searching(1,",
"10, 7, 8, 7, 9)) print(numbers_searching(50, 50, 47, 47, 48, 45, 49, 44,",
"args.count(number) > 1: duplicate_nums.append(number) answer.append(sorted(duplicate_nums)) return answer print(numbers_searching(1, 2, 4, 2, 5, 4))",
"set(args): if args.count(number) > 1: duplicate_nums.append(number) answer.append(sorted(duplicate_nums)) return answer print(numbers_searching(1, 2, 4, 2,",
"in range(min_num, max_num + 1): if search_num not in args: answer.append(search_num) for number",
"if args.count(number) > 1: duplicate_nums.append(number) answer.append(sorted(duplicate_nums)) return answer print(numbers_searching(1, 2, 4, 2, 5,"
] |
[
"read from ram registers you must use rtc.read_register # to write to eeprom",
"0x2A] # configuration eeprom address space : [0x30 - 0x37] my_saved_data = rtc.read_eeprom_register(register_address=my_reg_address)",
"my_data = 0x42 # to write to ram registers you must use rtc.write_register",
"memory (disables the automatic configuration refresh) rtc.use_eeprom() my_reg_address = 0x00 my_data = 0x42",
"# to write to eeprom you must use rtc.read_eeprom_register # user eeprom address",
"setup the rtc to use the eeprom memory (disables the automatic configuration refresh)",
"use rtc.write_register # to write to eeprom you must use rtc.write_eeprom_register # user",
"the rtc to use the eeprom memory (disables the automatic configuration refresh) rtc.use_eeprom()",
"address {} in eeprom\".format(my_data, my_reg_address)) # give some time to execute writing operation",
"you must use rtc.write_register # to write to eeprom you must use rtc.write_eeprom_register",
"value=my_data) print(\"Saved {} at address {} in eeprom\".format(my_data, my_reg_address)) # give some time",
"python3 # -*- coding: utf-8 -*- \"\"\" @author: <NAME> \"\"\" import melopero_RV_3028 as",
"coding: utf-8 -*- \"\"\" @author: <NAME> \"\"\" import melopero_RV_3028 as mp import time",
"0x00 my_data = 0x42 # to write to ram registers you must use",
": [0x00 - 0x2A] # configuration eeprom address space : [0x30 - 0x37]",
"[0x00 - 0x2A] # configuration eeprom address space : [0x30 - 0x37] rtc.write_eeprom_register(register_address=my_reg_address,",
"ram registers you must use rtc.write_register # to write to eeprom you must",
"{} at address {} in eeprom\".format(my_data, my_reg_address)) # give some time to execute",
": [0x30 - 0x37] my_saved_data = rtc.read_eeprom_register(register_address=my_reg_address) print(\"Read {} from eeprom address {}\".format(my_saved_data,",
"- 0x37] rtc.write_eeprom_register(register_address=my_reg_address, value=my_data) print(\"Saved {} at address {} in eeprom\".format(my_data, my_reg_address)) #",
"#!/usr/bin/env python3 # -*- coding: utf-8 -*- \"\"\" @author: <NAME> \"\"\" import melopero_RV_3028",
"# configuration eeprom address space : [0x30 - 0x37] my_saved_data = rtc.read_eeprom_register(register_address=my_reg_address) print(\"Read",
"import time def main(): # First initialize and create the rtc device rtc",
"rtc.write_eeprom_register # user eeprom address space : [0x00 - 0x2A] # configuration eeprom",
"# to write to ram registers you must use rtc.write_register # to write",
"registers you must use rtc.read_register # to write to eeprom you must use",
"to eeprom you must use rtc.write_eeprom_register # user eeprom address space : [0x00",
"must use rtc.write_register # to write to eeprom you must use rtc.write_eeprom_register #",
": [0x30 - 0x37] rtc.write_eeprom_register(register_address=my_reg_address, value=my_data) print(\"Saved {} at address {} in eeprom\".format(my_data,",
"use the eeprom memory (disables the automatic configuration refresh) rtc.use_eeprom() my_reg_address = 0x00",
"from ram registers you must use rtc.read_register # to write to eeprom you",
"# to write to eeprom you must use rtc.write_eeprom_register # user eeprom address",
"device rtc = mp.RV_3028() # setup the rtc to use the eeprom memory",
"and create the rtc device rtc = mp.RV_3028() # setup the rtc to",
"eeprom you must use rtc.read_eeprom_register # user eeprom address space : [0x00 -",
"to read from ram registers you must use rtc.read_register # to write to",
"(disables the automatic configuration refresh) rtc.use_eeprom() my_reg_address = 0x00 my_data = 0x42 #",
"registers you must use rtc.write_register # to write to eeprom you must use",
"0x37] my_saved_data = rtc.read_eeprom_register(register_address=my_reg_address) print(\"Read {} from eeprom address {}\".format(my_saved_data, my_reg_address)) if __name__",
"# configuration eeprom address space : [0x30 - 0x37] rtc.write_eeprom_register(register_address=my_reg_address, value=my_data) print(\"Saved {}",
"main(): # First initialize and create the rtc device rtc = mp.RV_3028() #",
"must use rtc.read_register # to write to eeprom you must use rtc.read_eeprom_register #",
"= rtc.read_eeprom_register(register_address=my_reg_address) print(\"Read {} from eeprom address {}\".format(my_saved_data, my_reg_address)) if __name__ == \"__main__\":",
"0x37] rtc.write_eeprom_register(register_address=my_reg_address, value=my_data) print(\"Saved {} at address {} in eeprom\".format(my_data, my_reg_address)) # give",
"rtc = mp.RV_3028() # setup the rtc to use the eeprom memory (disables",
"writing operation time.sleep(1) # to read from ram registers you must use rtc.read_register",
"write to eeprom you must use rtc.read_eeprom_register # user eeprom address space :",
"rtc.read_register # to write to eeprom you must use rtc.read_eeprom_register # user eeprom",
"eeprom address space : [0x30 - 0x37] rtc.write_eeprom_register(register_address=my_reg_address, value=my_data) print(\"Saved {} at address",
"configuration eeprom address space : [0x30 - 0x37] rtc.write_eeprom_register(register_address=my_reg_address, value=my_data) print(\"Saved {} at",
"{} in eeprom\".format(my_data, my_reg_address)) # give some time to execute writing operation time.sleep(1)",
"use rtc.read_eeprom_register # user eeprom address space : [0x00 - 0x2A] # configuration",
"the rtc device rtc = mp.RV_3028() # setup the rtc to use the",
"- 0x2A] # configuration eeprom address space : [0x30 - 0x37] my_saved_data =",
"user eeprom address space : [0x00 - 0x2A] # configuration eeprom address space",
"to write to ram registers you must use rtc.write_register # to write to",
"space : [0x00 - 0x2A] # configuration eeprom address space : [0x30 -",
"space : [0x30 - 0x37] rtc.write_eeprom_register(register_address=my_reg_address, value=my_data) print(\"Saved {} at address {} in",
"print(\"Saved {} at address {} in eeprom\".format(my_data, my_reg_address)) # give some time to",
"= 0x42 # to write to ram registers you must use rtc.write_register #",
"melopero_RV_3028 as mp import time def main(): # First initialize and create the",
"# to read from ram registers you must use rtc.read_register # to write",
"to eeprom you must use rtc.read_eeprom_register # user eeprom address space : [0x00",
"[0x00 - 0x2A] # configuration eeprom address space : [0x30 - 0x37] my_saved_data",
"time to execute writing operation time.sleep(1) # to read from ram registers you",
"you must use rtc.write_eeprom_register # user eeprom address space : [0x00 - 0x2A]",
"my_saved_data = rtc.read_eeprom_register(register_address=my_reg_address) print(\"Read {} from eeprom address {}\".format(my_saved_data, my_reg_address)) if __name__ ==",
"# setup the rtc to use the eeprom memory (disables the automatic configuration",
"rtc.write_register # to write to eeprom you must use rtc.write_eeprom_register # user eeprom",
"address space : [0x00 - 0x2A] # configuration eeprom address space : [0x30",
"eeprom\".format(my_data, my_reg_address)) # give some time to execute writing operation time.sleep(1) # to",
"operation time.sleep(1) # to read from ram registers you must use rtc.read_register #",
"import melopero_RV_3028 as mp import time def main(): # First initialize and create",
"[0x30 - 0x37] my_saved_data = rtc.read_eeprom_register(register_address=my_reg_address) print(\"Read {} from eeprom address {}\".format(my_saved_data, my_reg_address))",
"= mp.RV_3028() # setup the rtc to use the eeprom memory (disables the",
"to write to eeprom you must use rtc.write_eeprom_register # user eeprom address space",
"0x2A] # configuration eeprom address space : [0x30 - 0x37] rtc.write_eeprom_register(register_address=my_reg_address, value=my_data) print(\"Saved",
"you must use rtc.read_register # to write to eeprom you must use rtc.read_eeprom_register",
"rtc to use the eeprom memory (disables the automatic configuration refresh) rtc.use_eeprom() my_reg_address",
"to write to eeprom you must use rtc.read_eeprom_register # user eeprom address space",
"space : [0x30 - 0x37] my_saved_data = rtc.read_eeprom_register(register_address=my_reg_address) print(\"Read {} from eeprom address",
"rtc.read_eeprom_register # user eeprom address space : [0x00 - 0x2A] # configuration eeprom",
"mp import time def main(): # First initialize and create the rtc device",
"use rtc.write_eeprom_register # user eeprom address space : [0x00 - 0x2A] # configuration",
"you must use rtc.read_eeprom_register # user eeprom address space : [0x00 - 0x2A]",
"@author: <NAME> \"\"\" import melopero_RV_3028 as mp import time def main(): # First",
"the eeprom memory (disables the automatic configuration refresh) rtc.use_eeprom() my_reg_address = 0x00 my_data",
"- 0x37] my_saved_data = rtc.read_eeprom_register(register_address=my_reg_address) print(\"Read {} from eeprom address {}\".format(my_saved_data, my_reg_address)) if",
"automatic configuration refresh) rtc.use_eeprom() my_reg_address = 0x00 my_data = 0x42 # to write",
"utf-8 -*- \"\"\" @author: <NAME> \"\"\" import melopero_RV_3028 as mp import time def",
"[0x30 - 0x37] rtc.write_eeprom_register(register_address=my_reg_address, value=my_data) print(\"Saved {} at address {} in eeprom\".format(my_data, my_reg_address))",
"to use the eeprom memory (disables the automatic configuration refresh) rtc.use_eeprom() my_reg_address =",
"# First initialize and create the rtc device rtc = mp.RV_3028() # setup",
"-*- coding: utf-8 -*- \"\"\" @author: <NAME> \"\"\" import melopero_RV_3028 as mp import",
"time.sleep(1) # to read from ram registers you must use rtc.read_register # to",
"refresh) rtc.use_eeprom() my_reg_address = 0x00 my_data = 0x42 # to write to ram",
"as mp import time def main(): # First initialize and create the rtc",
"mp.RV_3028() # setup the rtc to use the eeprom memory (disables the automatic",
"write to ram registers you must use rtc.write_register # to write to eeprom",
"must use rtc.write_eeprom_register # user eeprom address space : [0x00 - 0x2A] #",
"# user eeprom address space : [0x00 - 0x2A] # configuration eeprom address",
"to ram registers you must use rtc.write_register # to write to eeprom you",
"eeprom memory (disables the automatic configuration refresh) rtc.use_eeprom() my_reg_address = 0x00 my_data =",
"eeprom address space : [0x00 - 0x2A] # configuration eeprom address space :",
"- 0x2A] # configuration eeprom address space : [0x30 - 0x37] rtc.write_eeprom_register(register_address=my_reg_address, value=my_data)",
"in eeprom\".format(my_data, my_reg_address)) # give some time to execute writing operation time.sleep(1) #",
"-*- \"\"\" @author: <NAME> \"\"\" import melopero_RV_3028 as mp import time def main():",
"<NAME> \"\"\" import melopero_RV_3028 as mp import time def main(): # First initialize",
"First initialize and create the rtc device rtc = mp.RV_3028() # setup the",
"rtc.use_eeprom() my_reg_address = 0x00 my_data = 0x42 # to write to ram registers",
"my_reg_address = 0x00 my_data = 0x42 # to write to ram registers you",
"address space : [0x30 - 0x37] my_saved_data = rtc.read_eeprom_register(register_address=my_reg_address) print(\"Read {} from eeprom",
"some time to execute writing operation time.sleep(1) # to read from ram registers",
"ram registers you must use rtc.read_register # to write to eeprom you must",
"execute writing operation time.sleep(1) # to read from ram registers you must use",
"rtc device rtc = mp.RV_3028() # setup the rtc to use the eeprom",
"my_reg_address)) # give some time to execute writing operation time.sleep(1) # to read",
"# -*- coding: utf-8 -*- \"\"\" @author: <NAME> \"\"\" import melopero_RV_3028 as mp",
"must use rtc.read_eeprom_register # user eeprom address space : [0x00 - 0x2A] #",
"configuration refresh) rtc.use_eeprom() my_reg_address = 0x00 my_data = 0x42 # to write to",
"use rtc.read_register # to write to eeprom you must use rtc.read_eeprom_register # user",
"eeprom address space : [0x30 - 0x37] my_saved_data = rtc.read_eeprom_register(register_address=my_reg_address) print(\"Read {} from",
"eeprom you must use rtc.write_eeprom_register # user eeprom address space : [0x00 -",
"# give some time to execute writing operation time.sleep(1) # to read from",
"create the rtc device rtc = mp.RV_3028() # setup the rtc to use",
"address space : [0x30 - 0x37] rtc.write_eeprom_register(register_address=my_reg_address, value=my_data) print(\"Saved {} at address {}",
"write to eeprom you must use rtc.write_eeprom_register # user eeprom address space :",
"at address {} in eeprom\".format(my_data, my_reg_address)) # give some time to execute writing",
"rtc.read_eeprom_register(register_address=my_reg_address) print(\"Read {} from eeprom address {}\".format(my_saved_data, my_reg_address)) if __name__ == \"__main__\": main()",
"rtc.write_eeprom_register(register_address=my_reg_address, value=my_data) print(\"Saved {} at address {} in eeprom\".format(my_data, my_reg_address)) # give some",
"initialize and create the rtc device rtc = mp.RV_3028() # setup the rtc",
"def main(): # First initialize and create the rtc device rtc = mp.RV_3028()",
"\"\"\" @author: <NAME> \"\"\" import melopero_RV_3028 as mp import time def main(): #",
"the automatic configuration refresh) rtc.use_eeprom() my_reg_address = 0x00 my_data = 0x42 # to",
"give some time to execute writing operation time.sleep(1) # to read from ram",
"time def main(): # First initialize and create the rtc device rtc =",
"\"\"\" import melopero_RV_3028 as mp import time def main(): # First initialize and",
"0x42 # to write to ram registers you must use rtc.write_register # to",
"to execute writing operation time.sleep(1) # to read from ram registers you must",
"configuration eeprom address space : [0x30 - 0x37] my_saved_data = rtc.read_eeprom_register(register_address=my_reg_address) print(\"Read {}",
"= 0x00 my_data = 0x42 # to write to ram registers you must"
] |
[
"3.1.13 on 2021-11-28 15:25 from django.db import migrations class Migration(migrations.Migration): dependencies = [",
"dependencies = [ ('clinical_annotations_manager', '0017_auto_20210424_1321'), ] operations = [ migrations.RenameField( model_name='coreannotation', old_name='creation_start_date', new_name='action_start_time',",
"# Generated by Django 3.1.13 on 2021-11-28 15:25 from django.db import migrations class",
"migrations.RenameField( model_name='focusregionannotation', old_name='creation_start_date', new_name='action_start_time', ), migrations.RenameField( model_name='gleasonelement', old_name='creation_start_date', new_name='action_start_time', ), migrations.RenameField( model_name='sliceannotation', old_name='creation_start_date',",
"import migrations class Migration(migrations.Migration): dependencies = [ ('clinical_annotations_manager', '0017_auto_20210424_1321'), ] operations = [",
"old_name='creation_start_date', new_name='action_start_time', ), migrations.RenameField( model_name='gleasonelement', old_name='creation_start_date', new_name='action_start_time', ), migrations.RenameField( model_name='sliceannotation', old_name='creation_start_date', new_name='action_start_time', ),",
"from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('clinical_annotations_manager', '0017_auto_20210424_1321'), ] operations",
"model_name='coreannotation', old_name='creation_start_date', new_name='action_start_time', ), migrations.RenameField( model_name='focusregionannotation', old_name='creation_start_date', new_name='action_start_time', ), migrations.RenameField( model_name='gleasonelement', old_name='creation_start_date', new_name='action_start_time',",
"Django 3.1.13 on 2021-11-28 15:25 from django.db import migrations class Migration(migrations.Migration): dependencies =",
"old_name='creation_start_date', new_name='action_start_time', ), migrations.RenameField( model_name='focusregionannotation', old_name='creation_start_date', new_name='action_start_time', ), migrations.RenameField( model_name='gleasonelement', old_name='creation_start_date', new_name='action_start_time', ),",
"new_name='action_start_time', ), migrations.RenameField( model_name='gleasonelement', old_name='creation_start_date', new_name='action_start_time', ), migrations.RenameField( model_name='sliceannotation', old_name='creation_start_date', new_name='action_start_time', ), ]",
"model_name='focusregionannotation', old_name='creation_start_date', new_name='action_start_time', ), migrations.RenameField( model_name='gleasonelement', old_name='creation_start_date', new_name='action_start_time', ), migrations.RenameField( model_name='sliceannotation', old_name='creation_start_date', new_name='action_start_time',",
"on 2021-11-28 15:25 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('clinical_annotations_manager',",
"), migrations.RenameField( model_name='focusregionannotation', old_name='creation_start_date', new_name='action_start_time', ), migrations.RenameField( model_name='gleasonelement', old_name='creation_start_date', new_name='action_start_time', ), migrations.RenameField( model_name='sliceannotation',",
"] operations = [ migrations.RenameField( model_name='coreannotation', old_name='creation_start_date', new_name='action_start_time', ), migrations.RenameField( model_name='focusregionannotation', old_name='creation_start_date', new_name='action_start_time',",
"= [ migrations.RenameField( model_name='coreannotation', old_name='creation_start_date', new_name='action_start_time', ), migrations.RenameField( model_name='focusregionannotation', old_name='creation_start_date', new_name='action_start_time', ), migrations.RenameField(",
"= [ ('clinical_annotations_manager', '0017_auto_20210424_1321'), ] operations = [ migrations.RenameField( model_name='coreannotation', old_name='creation_start_date', new_name='action_start_time', ),",
"[ ('clinical_annotations_manager', '0017_auto_20210424_1321'), ] operations = [ migrations.RenameField( model_name='coreannotation', old_name='creation_start_date', new_name='action_start_time', ), migrations.RenameField(",
"15:25 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('clinical_annotations_manager', '0017_auto_20210424_1321'), ]",
"migrations.RenameField( model_name='coreannotation', old_name='creation_start_date', new_name='action_start_time', ), migrations.RenameField( model_name='focusregionannotation', old_name='creation_start_date', new_name='action_start_time', ), migrations.RenameField( model_name='gleasonelement', old_name='creation_start_date',",
"class Migration(migrations.Migration): dependencies = [ ('clinical_annotations_manager', '0017_auto_20210424_1321'), ] operations = [ migrations.RenameField( model_name='coreannotation',",
"('clinical_annotations_manager', '0017_auto_20210424_1321'), ] operations = [ migrations.RenameField( model_name='coreannotation', old_name='creation_start_date', new_name='action_start_time', ), migrations.RenameField( model_name='focusregionannotation',",
"operations = [ migrations.RenameField( model_name='coreannotation', old_name='creation_start_date', new_name='action_start_time', ), migrations.RenameField( model_name='focusregionannotation', old_name='creation_start_date', new_name='action_start_time', ),",
"Migration(migrations.Migration): dependencies = [ ('clinical_annotations_manager', '0017_auto_20210424_1321'), ] operations = [ migrations.RenameField( model_name='coreannotation', old_name='creation_start_date',",
"Generated by Django 3.1.13 on 2021-11-28 15:25 from django.db import migrations class Migration(migrations.Migration):",
"[ migrations.RenameField( model_name='coreannotation', old_name='creation_start_date', new_name='action_start_time', ), migrations.RenameField( model_name='focusregionannotation', old_name='creation_start_date', new_name='action_start_time', ), migrations.RenameField( model_name='gleasonelement',",
"2021-11-28 15:25 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('clinical_annotations_manager', '0017_auto_20210424_1321'),",
"new_name='action_start_time', ), migrations.RenameField( model_name='focusregionannotation', old_name='creation_start_date', new_name='action_start_time', ), migrations.RenameField( model_name='gleasonelement', old_name='creation_start_date', new_name='action_start_time', ), migrations.RenameField(",
"migrations class Migration(migrations.Migration): dependencies = [ ('clinical_annotations_manager', '0017_auto_20210424_1321'), ] operations = [ migrations.RenameField(",
"'0017_auto_20210424_1321'), ] operations = [ migrations.RenameField( model_name='coreannotation', old_name='creation_start_date', new_name='action_start_time', ), migrations.RenameField( model_name='focusregionannotation', old_name='creation_start_date',",
"django.db import migrations class Migration(migrations.Migration): dependencies = [ ('clinical_annotations_manager', '0017_auto_20210424_1321'), ] operations =",
"by Django 3.1.13 on 2021-11-28 15:25 from django.db import migrations class Migration(migrations.Migration): dependencies"
] |
[
"from flask import url_for # from flask import session # from flask import",
"@app.route(\"/\", methods= [\"GET\",\"POST\"]) def hosts(): # GET returns the rendered hosts # POST",
"app.secret_key= \"random random RANDOM!\" groups = [{\"hostname\": \"hostA\",\"ip\": \"192.168.30.22\", \"fqdn\": \"hostA.localdomain\"}, {\"hostname\": \"hostB\",",
"<p>Invalid Login.</p> <p><input type = text name = username></p> <p><input type = submit",
"\"random random RANDOM!\" groups = [{\"hostname\": \"hostA\",\"ip\": \"192.168.30.22\", \"fqdn\": \"hostA.localdomain\"}, {\"hostname\": \"hostB\", \"ip\":",
"192.168.30.22 hostA.localdomain # hostA 192.168.30.33 hostB.localdomain # hostB 192.168.30.44 hostC.localdomain # hostB \"\"\"",
"import redirect # from flask import url_for # from flask import session #",
"\"\"\" groups = [{\"hostname\": \"hostA\",\"ip\": \"192.168.30.22\", \"fqdn\": \"hostA.localdomain\"}, {\"hostname\": \"hostB\", \"ip\": \"192.168.30.33\", \"fqdn\":",
"form hostname = request.form.get(\"hostname\") ip = request.form.get(\"ip\") fqdn = request.form.get(\"fqdn\") # create a",
"= [{\"hostname\": \"hostA\",\"ip\": \"192.168.30.22\", \"fqdn\": \"hostA.localdomain\"}, {\"hostname\": \"hostB\", \"ip\": \"192.168.30.33\", \"fqdn\": \"hostB.localdomain\"}, {\"hostname\":",
"request.method == \"POST\": session[\"username\"] = request.form.get(\"username\") if \"username\" in session and session[\"username\"] ==",
"hosts if \"username\" in session and session[\"username\"] == \"admin\": if request.method == \"POST\":",
"RANDOM!\" groups = [{\"hostname\": \"hostA\",\"ip\": \"192.168.30.22\", \"fqdn\": \"hostA.localdomain\"}, {\"hostname\": \"hostB\", \"ip\": \"192.168.30.33\", \"fqdn\":",
"else: return \"\"\" <form action = \"\" method = \"post\"> <p>Invalid Login.</p> <p><input",
"\"\"\" @app.route(\"/logout\") def logout(): # accessing this page pops the value of username",
"192.168.30.33 hostB.localdomain # hostB 192.168.30.44 hostC.localdomain # hostB \"\"\" \"\"\" groups = [{\"hostname\":",
"\"hostC.localdomain\"}] \"\"\" from flask import Flask, request, redirect, url_for, session, render_template # from",
"hosts, then returns rendered hosts if \"username\" in session and session[\"username\"] == \"admin\":",
"render_template(\"formcollector.html.j2\") else: return \"\"\" <form action = \"\" method = \"post\"> <p>Invalid Login.</p>",
"{\"hostname\": \"hostC\", \"ip\": \"192.168.30.44\", \"fqdn\": \"hostC.localdomain\"}] \"\"\" from flask import Flask, request, redirect,",
"return render_template(\"hosts.j2\", groups=groups) @app.route(\"/form\", methods=[\"GET\",\"POST\"]) def form(): # HTML form that collects hostname,",
"\"ip\": \"192.168.30.44\", \"fqdn\": \"hostC.localdomain\"}] @app.route(\"/\", methods= [\"GET\",\"POST\"]) def hosts(): # GET returns the",
"groups.append({\"hostname\": hostname, \"ip\": ip, \"fqdn\": fqdn}) return render_template(\"hosts.j2\", groups=groups) @app.route(\"/form\", methods=[\"GET\",\"POST\"]) def form():",
"\"fqdn\": \"hostB.localdomain\"}, {\"hostname\": \"hostC\", \"ip\": \"192.168.30.44\", \"fqdn\": \"hostC.localdomain\"}] @app.route(\"/\", methods= [\"GET\",\"POST\"]) def hosts():",
"return render_template(\"formcollector.html.j2\") else: return \"\"\" <form action = \"\" method = \"post\"> <p>Invalid",
"@app.route(\"/form\", methods=[\"GET\",\"POST\"]) def form(): # HTML form that collects hostname, ip, and fqdn",
"\"192.168.30.44\", \"fqdn\": \"hostC.localdomain\"}] @app.route(\"/\", methods= [\"GET\",\"POST\"]) def hosts(): # GET returns the rendered",
"in session and session[\"username\"] == \"admin\": if request.method == \"POST\": # pull all",
"from flask import request # from flask import redirect # from flask import",
"from flask import Flask, request, redirect, url_for, session, render_template # from flask import",
"= request.form.get(\"username\") if \"username\" in session and session[\"username\"] == \"admin\": return render_template(\"formcollector.html.j2\") else:",
"<p><input type = text name = username></p> <p><input type = submit value =",
"session, render_template # from flask import request # from flask import redirect #",
"\"username\" in session and session[\"username\"] == \"admin\": if request.method == \"POST\": # pull",
"# from flask import render_template app = Flask(__name__) app.secret_key= \"random random RANDOM!\" groups",
"username of the session session.pop(\"username\", None) return redirect(\"/\") if __name__ == \"__main__\": app.run(host=\"0.0.0.0\",",
"session[\"username\"] == \"admin\": return render_template(\"formcollector.html.j2\") else: return \"\"\" <form action = \"\" method",
"request.form.get(\"hostname\") ip = request.form.get(\"ip\") fqdn = request.form.get(\"fqdn\") # create a new dictionary with",
"session and session[\"username\"] == \"admin\": if request.method == \"POST\": # pull all values",
"\"fqdn\": \"hostC.localdomain\"}] \"\"\" from flask import Flask, request, redirect, url_for, session, render_template #",
"and session[\"username\"] == \"admin\": return render_template(\"formcollector.html.j2\") else: return \"\"\" <form action = \"\"",
"= \"\" method = \"post\"> <p>Invalid Login.</p> <p><input type = text name =",
"= request.form.get(\"fqdn\") # create a new dictionary with values, add to groups groups.append({\"hostname\":",
"# HTML form that collects hostname, ip, and fqdn values if request.method ==",
"\"\"\" from flask import Flask, request, redirect, url_for, session, render_template # from flask",
"import url_for # from flask import session # from flask import render_template app",
"\"ip\": ip, \"fqdn\": fqdn}) return render_template(\"hosts.j2\", groups=groups) @app.route(\"/form\", methods=[\"GET\",\"POST\"]) def form(): # HTML",
"in session and session[\"username\"] == \"admin\": return render_template(\"formcollector.html.j2\") else: return \"\"\" <form action",
"text name = username></p> <p><input type = submit value = Login></p> </form> \"\"\"",
"<p><input type = submit value = Login></p> </form> \"\"\" @app.route(\"/logout\") def logout(): #",
"\"hostC.localdomain\"}] @app.route(\"/\", methods= [\"GET\",\"POST\"]) def hosts(): # GET returns the rendered hosts #",
"\"POST\": # pull all values from posted form hostname = request.form.get(\"hostname\") ip =",
"hosts # POST adds new hosts, then returns rendered hosts if \"username\" in",
"logout(): # accessing this page pops the value of username of the session",
"render_template # from flask import request # from flask import redirect # from",
"of the session session.pop(\"username\", None) return redirect(\"/\") if __name__ == \"__main__\": app.run(host=\"0.0.0.0\", port=2224)",
"url_for # from flask import session # from flask import render_template app =",
"\"192.168.30.44\", \"fqdn\": \"hostC.localdomain\"}] \"\"\" from flask import Flask, request, redirect, url_for, session, render_template",
"returns the rendered hosts # POST adds new hosts, then returns rendered hosts",
"session and session[\"username\"] == \"admin\": return render_template(\"formcollector.html.j2\") else: return \"\"\" <form action =",
"{\"hostname\": \"hostC\", \"ip\": \"192.168.30.44\", \"fqdn\": \"hostC.localdomain\"}] @app.route(\"/\", methods= [\"GET\",\"POST\"]) def hosts(): # GET",
"posted form hostname = request.form.get(\"hostname\") ip = request.form.get(\"ip\") fqdn = request.form.get(\"fqdn\") # create",
"# from flask import request # from flask import redirect # from flask",
"request.form.get(\"fqdn\") # create a new dictionary with values, add to groups groups.append({\"hostname\": hostname,",
"# GET returns the rendered hosts # POST adds new hosts, then returns",
"import render_template app = Flask(__name__) app.secret_key= \"random random RANDOM!\" groups = [{\"hostname\": \"hostA\",\"ip\":",
"request, redirect, url_for, session, render_template # from flask import request # from flask",
"methods= [\"GET\",\"POST\"]) def hosts(): # GET returns the rendered hosts # POST adds",
"adds new hosts, then returns rendered hosts if \"username\" in session and session[\"username\"]",
"Flask, request, redirect, url_for, session, render_template # from flask import request # from",
"# from flask import url_for # from flask import session # from flask",
"groups groups.append({\"hostname\": hostname, \"ip\": ip, \"fqdn\": fqdn}) return render_template(\"hosts.j2\", groups=groups) @app.route(\"/form\", methods=[\"GET\",\"POST\"]) def",
"form that collects hostname, ip, and fqdn values if request.method == \"POST\": session[\"username\"]",
"the rendered hosts # POST adds new hosts, then returns rendered hosts if",
"hostname = request.form.get(\"hostname\") ip = request.form.get(\"ip\") fqdn = request.form.get(\"fqdn\") # create a new",
"{\"hostname\": \"hostB\", \"ip\": \"192.168.30.33\", \"fqdn\": \"hostB.localdomain\"}, {\"hostname\": \"hostC\", \"ip\": \"192.168.30.44\", \"fqdn\": \"hostC.localdomain\"}] \"\"\"",
"\"fqdn\": \"hostB.localdomain\"}, {\"hostname\": \"hostC\", \"ip\": \"192.168.30.44\", \"fqdn\": \"hostC.localdomain\"}] \"\"\" from flask import Flask,",
"ip, and fqdn values if request.method == \"POST\": session[\"username\"] = request.form.get(\"username\") if \"username\"",
"values from posted form hostname = request.form.get(\"hostname\") ip = request.form.get(\"ip\") fqdn = request.form.get(\"fqdn\")",
"if \"username\" in session and session[\"username\"] == \"admin\": return render_template(\"formcollector.html.j2\") else: return \"\"\"",
"methods=[\"GET\",\"POST\"]) def form(): # HTML form that collects hostname, ip, and fqdn values",
"\"hostB\", \"ip\": \"192.168.30.33\", \"fqdn\": \"hostB.localdomain\"}, {\"hostname\": \"hostC\", \"ip\": \"192.168.30.44\", \"fqdn\": \"hostC.localdomain\"}] @app.route(\"/\", methods=",
"# POST adds new hosts, then returns rendered hosts if \"username\" in session",
"import session # from flask import render_template app = Flask(__name__) app.secret_key= \"random random",
"# pull all values from posted form hostname = request.form.get(\"hostname\") ip = request.form.get(\"ip\")",
"flask import redirect # from flask import url_for # from flask import session",
"def hosts(): # GET returns the rendered hosts # POST adds new hosts,",
"value = Login></p> </form> \"\"\" @app.route(\"/logout\") def logout(): # accessing this page pops",
"hostB \"\"\" \"\"\" groups = [{\"hostname\": \"hostA\",\"ip\": \"192.168.30.22\", \"fqdn\": \"hostA.localdomain\"}, {\"hostname\": \"hostB\", \"ip\":",
"== \"POST\": session[\"username\"] = request.form.get(\"username\") if \"username\" in session and session[\"username\"] == \"admin\":",
"hostname, ip, and fqdn values if request.method == \"POST\": session[\"username\"] = request.form.get(\"username\") if",
"of username of the session session.pop(\"username\", None) return redirect(\"/\") if __name__ == \"__main__\":",
"\"admin\": return render_template(\"formcollector.html.j2\") else: return \"\"\" <form action = \"\" method = \"post\">",
"if \"username\" in session and session[\"username\"] == \"admin\": if request.method == \"POST\": #",
"session[\"username\"] == \"admin\": if request.method == \"POST\": # pull all values from posted",
"\"\"\" \"\"\" groups = [{\"hostname\": \"hostA\",\"ip\": \"192.168.30.22\", \"fqdn\": \"hostA.localdomain\"}, {\"hostname\": \"hostB\", \"ip\": \"192.168.30.33\",",
"# hostB \"\"\" \"\"\" groups = [{\"hostname\": \"hostA\",\"ip\": \"192.168.30.22\", \"fqdn\": \"hostA.localdomain\"}, {\"hostname\": \"hostB\",",
"{\"hostname\": \"hostB\", \"ip\": \"192.168.30.33\", \"fqdn\": \"hostB.localdomain\"}, {\"hostname\": \"hostC\", \"ip\": \"192.168.30.44\", \"fqdn\": \"hostC.localdomain\"}] @app.route(\"/\",",
"fqdn = request.form.get(\"fqdn\") # create a new dictionary with values, add to groups",
"form(): # HTML form that collects hostname, ip, and fqdn values if request.method",
"to groups groups.append({\"hostname\": hostname, \"ip\": ip, \"fqdn\": fqdn}) return render_template(\"hosts.j2\", groups=groups) @app.route(\"/form\", methods=[\"GET\",\"POST\"])",
"hostname, \"ip\": ip, \"fqdn\": fqdn}) return render_template(\"hosts.j2\", groups=groups) @app.route(\"/form\", methods=[\"GET\",\"POST\"]) def form(): #",
"hostB.localdomain # hostB 192.168.30.44 hostC.localdomain # hostB \"\"\" \"\"\" groups = [{\"hostname\": \"hostA\",\"ip\":",
"hostA.localdomain # hostA 192.168.30.33 hostB.localdomain # hostB 192.168.30.44 hostC.localdomain # hostB \"\"\" \"\"\"",
"request.form.get(\"username\") if \"username\" in session and session[\"username\"] == \"admin\": return render_template(\"formcollector.html.j2\") else: return",
"\"192.168.30.33\", \"fqdn\": \"hostB.localdomain\"}, {\"hostname\": \"hostC\", \"ip\": \"192.168.30.44\", \"fqdn\": \"hostC.localdomain\"}] @app.route(\"/\", methods= [\"GET\",\"POST\"]) def",
"this page pops the value of username of the session session.pop(\"username\", None) return",
"from flask import session # from flask import render_template app = Flask(__name__) app.secret_key=",
"\"fqdn\": fqdn}) return render_template(\"hosts.j2\", groups=groups) @app.route(\"/form\", methods=[\"GET\",\"POST\"]) def form(): # HTML form that",
"192.168.30.44 hostC.localdomain # hostB \"\"\" \"\"\" groups = [{\"hostname\": \"hostA\",\"ip\": \"192.168.30.22\", \"fqdn\": \"hostA.localdomain\"},",
"redirect, url_for, session, render_template # from flask import request # from flask import",
"import request # from flask import redirect # from flask import url_for #",
"values, add to groups groups.append({\"hostname\": hostname, \"ip\": ip, \"fqdn\": fqdn}) return render_template(\"hosts.j2\", groups=groups)",
"session[\"username\"] = request.form.get(\"username\") if \"username\" in session and session[\"username\"] == \"admin\": return render_template(\"formcollector.html.j2\")",
"\"hostC\", \"ip\": \"192.168.30.44\", \"fqdn\": \"hostC.localdomain\"}] \"\"\" from flask import Flask, request, redirect, url_for,",
"GET returns the rendered hosts # POST adds new hosts, then returns rendered",
"all values from posted form hostname = request.form.get(\"hostname\") ip = request.form.get(\"ip\") fqdn =",
"action = \"\" method = \"post\"> <p>Invalid Login.</p> <p><input type = text name",
"\"\"\" <form action = \"\" method = \"post\"> <p>Invalid Login.</p> <p><input type =",
"request # from flask import redirect # from flask import url_for # from",
"\"hostB.localdomain\"}, {\"hostname\": \"hostC\", \"ip\": \"192.168.30.44\", \"fqdn\": \"hostC.localdomain\"}] \"\"\" from flask import Flask, request,",
"import Flask, request, redirect, url_for, session, render_template # from flask import request #",
"type = text name = username></p> <p><input type = submit value = Login></p>",
"with values, add to groups groups.append({\"hostname\": hostname, \"ip\": ip, \"fqdn\": fqdn}) return render_template(\"hosts.j2\",",
"== \"POST\": # pull all values from posted form hostname = request.form.get(\"hostname\") ip",
"\"fqdn\": \"hostC.localdomain\"}] @app.route(\"/\", methods= [\"GET\",\"POST\"]) def hosts(): # GET returns the rendered hosts",
"= text name = username></p> <p><input type = submit value = Login></p> </form>",
"= username></p> <p><input type = submit value = Login></p> </form> \"\"\" @app.route(\"/logout\") def",
"name = username></p> <p><input type = submit value = Login></p> </form> \"\"\" @app.route(\"/logout\")",
"</form> \"\"\" @app.route(\"/logout\") def logout(): # accessing this page pops the value of",
"\"hostA\",\"ip\": \"192.168.30.22\", \"fqdn\": \"hostA.localdomain\"}, {\"hostname\": \"hostB\", \"ip\": \"192.168.30.33\", \"fqdn\": \"hostB.localdomain\"}, {\"hostname\": \"hostC\", \"ip\":",
"# hostB 192.168.30.44 hostC.localdomain # hostB \"\"\" \"\"\" groups = [{\"hostname\": \"hostA\",\"ip\": \"192.168.30.22\",",
"Login></p> </form> \"\"\" @app.route(\"/logout\") def logout(): # accessing this page pops the value",
"\"POST\": session[\"username\"] = request.form.get(\"username\") if \"username\" in session and session[\"username\"] == \"admin\": return",
"request.form.get(\"ip\") fqdn = request.form.get(\"fqdn\") # create a new dictionary with values, add to",
"== \"admin\": return render_template(\"formcollector.html.j2\") else: return \"\"\" <form action = \"\" method =",
"random RANDOM!\" groups = [{\"hostname\": \"hostA\",\"ip\": \"192.168.30.22\", \"fqdn\": \"hostA.localdomain\"}, {\"hostname\": \"hostB\", \"ip\": \"192.168.30.33\",",
"\"ip\": \"192.168.30.33\", \"fqdn\": \"hostB.localdomain\"}, {\"hostname\": \"hostC\", \"ip\": \"192.168.30.44\", \"fqdn\": \"hostC.localdomain\"}] @app.route(\"/\", methods= [\"GET\",\"POST\"])",
"\"192.168.30.22\", \"fqdn\": \"hostA.localdomain\"}, {\"hostname\": \"hostB\", \"ip\": \"192.168.30.33\", \"fqdn\": \"hostB.localdomain\"}, {\"hostname\": \"hostC\", \"ip\": \"192.168.30.44\",",
"return \"\"\" <form action = \"\" method = \"post\"> <p>Invalid Login.</p> <p><input type",
"that collects hostname, ip, and fqdn values if request.method == \"POST\": session[\"username\"] =",
"a new dictionary with values, add to groups groups.append({\"hostname\": hostname, \"ip\": ip, \"fqdn\":",
"from flask import redirect # from flask import url_for # from flask import",
"page pops the value of username of the session session.pop(\"username\", None) return redirect(\"/\")",
"\"post\"> <p>Invalid Login.</p> <p><input type = text name = username></p> <p><input type =",
"\"hostB\", \"ip\": \"192.168.30.33\", \"fqdn\": \"hostB.localdomain\"}, {\"hostname\": \"hostC\", \"ip\": \"192.168.30.44\", \"fqdn\": \"hostC.localdomain\"}] \"\"\" from",
"username></p> <p><input type = submit value = Login></p> </form> \"\"\" @app.route(\"/logout\") def logout():",
"flask import url_for # from flask import session # from flask import render_template",
"<form action = \"\" method = \"post\"> <p>Invalid Login.</p> <p><input type = text",
"\"fqdn\": \"hostA.localdomain\"}, {\"hostname\": \"hostB\", \"ip\": \"192.168.30.33\", \"fqdn\": \"hostB.localdomain\"}, {\"hostname\": \"hostC\", \"ip\": \"192.168.30.44\", \"fqdn\":",
"new hosts, then returns rendered hosts if \"username\" in session and session[\"username\"] ==",
"# create a new dictionary with values, add to groups groups.append({\"hostname\": hostname, \"ip\":",
"flask import session # from flask import render_template app = Flask(__name__) app.secret_key= \"random",
"and session[\"username\"] == \"admin\": if request.method == \"POST\": # pull all values from",
"groups=groups) @app.route(\"/form\", methods=[\"GET\",\"POST\"]) def form(): # HTML form that collects hostname, ip, and",
"def logout(): # accessing this page pops the value of username of the",
"[{\"hostname\": \"hostA\",\"ip\": \"192.168.30.22\", \"fqdn\": \"hostA.localdomain\"}, {\"hostname\": \"hostB\", \"ip\": \"192.168.30.33\", \"fqdn\": \"hostB.localdomain\"}, {\"hostname\": \"hostC\",",
"url_for, session, render_template # from flask import request # from flask import redirect",
"from posted form hostname = request.form.get(\"hostname\") ip = request.form.get(\"ip\") fqdn = request.form.get(\"fqdn\") #",
"rendered hosts # POST adds new hosts, then returns rendered hosts if \"username\"",
"# hostA 192.168.30.33 hostB.localdomain # hostB 192.168.30.44 hostC.localdomain # hostB \"\"\" \"\"\" groups",
"groups = [{\"hostname\": \"hostA\",\"ip\": \"192.168.30.22\", \"fqdn\": \"hostA.localdomain\"}, {\"hostname\": \"hostB\", \"ip\": \"192.168.30.33\", \"fqdn\": \"hostB.localdomain\"},",
"Flask(__name__) app.secret_key= \"random random RANDOM!\" groups = [{\"hostname\": \"hostA\",\"ip\": \"192.168.30.22\", \"fqdn\": \"hostA.localdomain\"}, {\"hostname\":",
"values if request.method == \"POST\": session[\"username\"] = request.form.get(\"username\") if \"username\" in session and",
"\"username\" in session and session[\"username\"] == \"admin\": return render_template(\"formcollector.html.j2\") else: return \"\"\" <form",
"Login.</p> <p><input type = text name = username></p> <p><input type = submit value",
"= request.form.get(\"ip\") fqdn = request.form.get(\"fqdn\") # create a new dictionary with values, add",
"the value of username of the session session.pop(\"username\", None) return redirect(\"/\") if __name__",
"\"ip\": \"192.168.30.33\", \"fqdn\": \"hostB.localdomain\"}, {\"hostname\": \"hostC\", \"ip\": \"192.168.30.44\", \"fqdn\": \"hostC.localdomain\"}] \"\"\" from flask",
"\"hostB.localdomain\"}, {\"hostname\": \"hostC\", \"ip\": \"192.168.30.44\", \"fqdn\": \"hostC.localdomain\"}] @app.route(\"/\", methods= [\"GET\",\"POST\"]) def hosts(): #",
"\"hostA.localdomain\"}, {\"hostname\": \"hostB\", \"ip\": \"192.168.30.33\", \"fqdn\": \"hostB.localdomain\"}, {\"hostname\": \"hostC\", \"ip\": \"192.168.30.44\", \"fqdn\": \"hostC.localdomain\"}]",
"session # from flask import render_template app = Flask(__name__) app.secret_key= \"random random RANDOM!\"",
"[\"GET\",\"POST\"]) def hosts(): # GET returns the rendered hosts # POST adds new",
"def form(): # HTML form that collects hostname, ip, and fqdn values if",
"flask import render_template app = Flask(__name__) app.secret_key= \"random random RANDOM!\" groups = [{\"hostname\":",
"rendered hosts if \"username\" in session and session[\"username\"] == \"admin\": if request.method ==",
"flask import Flask, request, redirect, url_for, session, render_template # from flask import request",
"fqdn values if request.method == \"POST\": session[\"username\"] = request.form.get(\"username\") if \"username\" in session",
"= Flask(__name__) app.secret_key= \"random random RANDOM!\" groups = [{\"hostname\": \"hostA\",\"ip\": \"192.168.30.22\", \"fqdn\": \"hostA.localdomain\"},",
"then returns rendered hosts if \"username\" in session and session[\"username\"] == \"admin\": if",
"== \"admin\": if request.method == \"POST\": # pull all values from posted form",
"= submit value = Login></p> </form> \"\"\" @app.route(\"/logout\") def logout(): # accessing this",
"hosts(): # GET returns the rendered hosts # POST adds new hosts, then",
"ip = request.form.get(\"ip\") fqdn = request.form.get(\"fqdn\") # create a new dictionary with values,",
"dictionary with values, add to groups groups.append({\"hostname\": hostname, \"ip\": ip, \"fqdn\": fqdn}) return",
"if request.method == \"POST\": # pull all values from posted form hostname =",
"HTML form that collects hostname, ip, and fqdn values if request.method == \"POST\":",
"hostC.localdomain # hostB \"\"\" \"\"\" groups = [{\"hostname\": \"hostA\",\"ip\": \"192.168.30.22\", \"fqdn\": \"hostA.localdomain\"}, {\"hostname\":",
"hostA 192.168.30.33 hostB.localdomain # hostB 192.168.30.44 hostC.localdomain # hostB \"\"\" \"\"\" groups =",
"value of username of the session session.pop(\"username\", None) return redirect(\"/\") if __name__ ==",
"create a new dictionary with values, add to groups groups.append({\"hostname\": hostname, \"ip\": ip,",
"pull all values from posted form hostname = request.form.get(\"hostname\") ip = request.form.get(\"ip\") fqdn",
"hostB 192.168.30.44 hostC.localdomain # hostB \"\"\" \"\"\" groups = [{\"hostname\": \"hostA\",\"ip\": \"192.168.30.22\", \"fqdn\":",
"# from flask import redirect # from flask import url_for # from flask",
"fqdn}) return render_template(\"hosts.j2\", groups=groups) @app.route(\"/form\", methods=[\"GET\",\"POST\"]) def form(): # HTML form that collects",
"accessing this page pops the value of username of the session session.pop(\"username\", None)",
"new dictionary with values, add to groups groups.append({\"hostname\": hostname, \"ip\": ip, \"fqdn\": fqdn})",
"= Login></p> </form> \"\"\" @app.route(\"/logout\") def logout(): # accessing this page pops the",
"flask import request # from flask import redirect # from flask import url_for",
"submit value = Login></p> </form> \"\"\" @app.route(\"/logout\") def logout(): # accessing this page",
"pops the value of username of the session session.pop(\"username\", None) return redirect(\"/\") if",
"if request.method == \"POST\": session[\"username\"] = request.form.get(\"username\") if \"username\" in session and session[\"username\"]",
"app = Flask(__name__) app.secret_key= \"random random RANDOM!\" groups = [{\"hostname\": \"hostA\",\"ip\": \"192.168.30.22\", \"fqdn\":",
"\"\" method = \"post\"> <p>Invalid Login.</p> <p><input type = text name = username></p>",
"= \"post\"> <p>Invalid Login.</p> <p><input type = text name = username></p> <p><input type",
"type = submit value = Login></p> </form> \"\"\" @app.route(\"/logout\") def logout(): # accessing",
"redirect # from flask import url_for # from flask import session # from",
"render_template(\"hosts.j2\", groups=groups) @app.route(\"/form\", methods=[\"GET\",\"POST\"]) def form(): # HTML form that collects hostname, ip,",
"method = \"post\"> <p>Invalid Login.</p> <p><input type = text name = username></p> <p><input",
"returns rendered hosts if \"username\" in session and session[\"username\"] == \"admin\": if request.method",
"\"192.168.30.33\", \"fqdn\": \"hostB.localdomain\"}, {\"hostname\": \"hostC\", \"ip\": \"192.168.30.44\", \"fqdn\": \"hostC.localdomain\"}] \"\"\" from flask import",
"\"ip\": \"192.168.30.44\", \"fqdn\": \"hostC.localdomain\"}] \"\"\" from flask import Flask, request, redirect, url_for, session,",
"from flask import render_template app = Flask(__name__) app.secret_key= \"random random RANDOM!\" groups =",
"\"admin\": if request.method == \"POST\": # pull all values from posted form hostname",
"add to groups groups.append({\"hostname\": hostname, \"ip\": ip, \"fqdn\": fqdn}) return render_template(\"hosts.j2\", groups=groups) @app.route(\"/form\",",
"collects hostname, ip, and fqdn values if request.method == \"POST\": session[\"username\"] = request.form.get(\"username\")",
"@app.route(\"/logout\") def logout(): # accessing this page pops the value of username of",
"# accessing this page pops the value of username of the session session.pop(\"username\",",
"\"hostC\", \"ip\": \"192.168.30.44\", \"fqdn\": \"hostC.localdomain\"}] @app.route(\"/\", methods= [\"GET\",\"POST\"]) def hosts(): # GET returns",
"# from flask import session # from flask import render_template app = Flask(__name__)",
"and fqdn values if request.method == \"POST\": session[\"username\"] = request.form.get(\"username\") if \"username\" in",
"\"\"\" 192.168.30.22 hostA.localdomain # hostA 192.168.30.33 hostB.localdomain # hostB 192.168.30.44 hostC.localdomain # hostB",
"= request.form.get(\"hostname\") ip = request.form.get(\"ip\") fqdn = request.form.get(\"fqdn\") # create a new dictionary",
"request.method == \"POST\": # pull all values from posted form hostname = request.form.get(\"hostname\")",
"ip, \"fqdn\": fqdn}) return render_template(\"hosts.j2\", groups=groups) @app.route(\"/form\", methods=[\"GET\",\"POST\"]) def form(): # HTML form",
"render_template app = Flask(__name__) app.secret_key= \"random random RANDOM!\" groups = [{\"hostname\": \"hostA\",\"ip\": \"192.168.30.22\",",
"POST adds new hosts, then returns rendered hosts if \"username\" in session and"
] |
[
"= prediction ,labels = self.Y) optimizer = tf.train.AdamOptimizer(learning_rate = self.learning_rate) train_op = optimizer.minimize(loss_op,name=\"train_op\")",
"graph.get_tensor_by_name(\"Xe:0\"): batch_tr_xe, graph.get_tensor_by_name(\"Y:0\"): batch_tr_y, graph.get_tensor_by_name(\"keep_prob:0\"): 1.0}) test_l = sess.run(\"mean_squared_error_1/value:0\", feed_dict={graph.get_tensor_by_name(\"Xb_test:0\"): batch_test_xb, graph.get_tensor_by_name(\"Xe_test:0\"): batch_test_xe,",
"for cnn 'wd1': tf.Variable(tf.random_normal([self.steps_back*self.cnn_num_input*64//4, 1024])), 'wd11': tf.Variable(tf.random_normal([1024, 20])), # fully connected for fl_net,",
"plt.plot(range(len(self.validation_loss)), self.validation_loss, label='Validation') # plt.xlabel('Steps') # # plt.ylabel('Loss') # # plt.title(\"Loss function\") #",
"xe, y,sess): # saver.restore(sess, \"./model.ckpt\") # self.run_sess(sess,xb,xe,y) def predict(self, xb, xe, sess): #",
"digits) self.dropout = 0.85 # Dropout, probability to keep units # Placeholders self.Xb",
"overfitting=0 for step in range(1, self.num_steps + 1): # Run optimization op (backprop)",
"= batch_y[self.batch_tr_size:] overfitting=0 for step in range(1, self.num_steps + 1): # Run optimization",
"Convolution Layer conv1 = self.conv2d(xb, self.weights['wc1'],self.biases['bc1']) # Max Pooling (down-sampling) conv1 = self.maxpool2d(conv1,",
"as tf from read_data import get_X_y from sklearn.preprocessing import MinMaxScaler import matplotlib.pyplot as",
"MNIST total classes (0-9 digits) self.dropout = 0.85 # Dropout, probability to keep",
"Calculate batch loss training_l = sess.run(\"mean_squared_error/value:0\", feed_dict={graph.get_tensor_by_name(\"Xb:0\"): batch_tr_xb, graph.get_tensor_by_name(\"Xe:0\"): batch_tr_xe, graph.get_tensor_by_name(\"Y:0\"): batch_tr_y, graph.get_tensor_by_name(\"keep_prob:0\"):",
"# # plt.title(\"Loss function\") # # plt.legend() # # plt.show() # def retrain(self,xb,",
"# Store layers weight & bias self.weights = { # 5x5 conv 'wc1':",
"self.steps_back, self.cnn_num_input]) batch_y = np.reshape(batch_y,[-1,self.num_output]) batch_tr_xe = batch_xe[:self.batch_tr_size] batch_test_xe = batch_xe[self.batch_tr_size:] batch_tr_xb =",
"* (1 - self.test_proportion)) self.test_size = int(self.test_proportion*self.batch_size) self.keep_prob = tf.placeholder(tf.float32, name='keep_prob') # dropout",
"another fc net with sigmoid fc3_test = tf.add(tf.matmul(fc_test, self.weights['out']), self.biases['out']) fc3_sigmoided_test = tf.nn.sigmoid(fc3_test)",
"0.85 # Dropout, probability to keep units # Placeholders self.Xb = tf.placeholder(tf.float32, [self.batch_tr_size,",
"= optimizer.minimize(loss_op,name=\"train_op\") if self.test_proportion != 0: # Test graph conv_component_test = self.conv_net(graph.get_tensor_by_name(\"Xb_test:0\")) fc_component_test",
"\" + str(test_l)) if test_l - training_l> 0.015: overfitting += 1 else: overfitting",
"scaler1[i].fit_transform(xb[:,i,:]) scaler2 = MinMaxScaler(feature_range=(0,1), copy=True).fit(xe) scaler3 = MinMaxScaler(feature_range=(0, 1), copy=True).fit(y.reshape(-1,1)) xe= scaler2.transform(xe) y=",
"0.009 : print(\"condition satisfied\") break # self.training_loss.append(training_l) # self.validation_loss.append(test_l) print(\"Optimization Finished!\") # Save",
"= np.reshape(batch_xe,[-1,1,self.fc_num_input]) batch_xb = np.reshape(batch_xb, [-1, self.steps_back, self.cnn_num_input]) batch_y = np.reshape(batch_y,[-1,self.num_output]) batch_tr_xe =",
"batch_size if batch_size==1: self.test_proportion = 0 else: self.test_proportion = test_size self.batch_tr_size = int(self.batch_size",
"saver, name): graph = sess.graph batch_xe = np.reshape(batch_xe,[-1,1,self.fc_num_input]) batch_xb = np.reshape(batch_xb, [-1, self.steps_back,",
"np.reshape(batch_y,[-1,self.num_output]) batch_tr_xe = batch_xe[:self.batch_tr_size] batch_test_xe = batch_xe[self.batch_tr_size:] batch_tr_xb = batch_xb[:self.batch_tr_size] batch_test_xb = batch_xb[self.batch_tr_size:]",
"def combined_net(self, graph = tf.get_default_graph()): with graph.as_default(): conv_component = self.conv_net(self.Xb) fc_component = self.fc_net(self.Xe)",
"self.conv2d(xb, self.weights['wc1'],self.biases['bc1']) # Max Pooling (down-sampling) conv1 = self.maxpool2d(conv1, k=2) # Convolution Layer",
"\"./model0.ckpt\", graph = tf.get_default_graph() ): self.training_loss = [] self.validation_loss = [] with tf.Session(graph=graph)",
"# Create model def conv_net(self,xb): xb = tf.reshape(xb, shape=[-1, self.steps_back, self.num_TCL, 1]) #",
"tf.add(tf.matmul(fc, self.weights['out']), self.biases['out']) fc3_sigmoided = tf.nn.sigmoid(fc3) #linear fc prediction = tf.add(tf.matmul(fc3_sigmoided, self.weights['out2']), self.biases['out2'],",
"fuly connected layer 100 inputs and 1 output 'out2': tf.Variable(tf.random_normal([50, self.num_output])) } self.biases",
"tf.nn.relu(fc2) def combined_net(self, graph = tf.get_default_graph()): with graph.as_default(): conv_component = self.conv_net(self.Xb) fc_component =",
"conv1 = self.maxpool2d(conv1, k=2) # Convolution Layer conv2 = self.conv2d(conv1, self.weights['wc2'], self.biases['bc2']) #",
"self.weights['wd11']), self.biases['bd11']) fc11_relued = tf.nn.relu(fc11) ## Apply Dropout return tf.nn.dropout(fc11_relued, self.keep_prob) def fc_net(self,xe):",
"tf.nn.sigmoid(fc3_test) # linear fc prediction_test = tf.add(tf.matmul(fc3_sigmoided_test, self.weights['out2']), self.biases['out2'], name=\"prediction_test\") loss_op_test = tf.losses.mean_squared_error(predictions=prediction_test,",
"1), copy=True).fit(y.reshape(-1,1)) xe= scaler2.transform(xe) y= scaler3.transform(y.reshape(-1,1)) # graph = tf.Graph() neural_net.combined_net() # saver",
"name='keep_prob') # dropout (keep probability) # display_step = 10 # Network Parameters self.cnn_num_input",
"plt.show() # def retrain(self,xb, xe, y,sess): # saver.restore(sess, \"./model.ckpt\") # self.run_sess(sess,xb,xe,y) def predict(self,",
"satisfied\") break if test_l < 0.009 and training_l < 0.009 : print(\"condition satisfied\")",
"tf from read_data import get_X_y from sklearn.preprocessing import MinMaxScaler import matplotlib.pyplot as plt",
"= sess.graph batch_xe = np.reshape(batch_xe,[-1,1,self.fc_num_input]) batch_xb = np.reshape(batch_xb, [-1, self.steps_back, self.cnn_num_input]) batch_y =",
"batch_y = np.reshape(batch_y,[-1,self.num_output]) batch_tr_xe = batch_xe[:self.batch_tr_size] batch_test_xe = batch_xe[self.batch_tr_size:] batch_tr_xb = batch_xb[:self.batch_tr_size] batch_test_xb",
"# 1024+10 inputs, 1 output (class prediction) 'out': tf.Variable(tf.random_normal([20+20, 50])), # second fuly",
"= int(self.batch_size * (1 - self.test_proportion)) self.test_size = int(self.test_proportion*self.batch_size) self.keep_prob = tf.placeholder(tf.float32, name='keep_prob')",
"batch_test_xe = batch_xe[self.batch_tr_size:] batch_tr_xb = batch_xb[:self.batch_tr_size] batch_test_xb = batch_xb[self.batch_tr_size:] batch_tr_y = batch_y[:self.batch_tr_size] batch_test_y",
"xe, y = get_X_y(steps_back=7, filename=\"Q_data0.csv\") neural_net = NN(batch_size = 100, steps_back=8) scaler1 =",
"inputs, 1 output (class prediction) 'out': tf.Variable(tf.random_normal([20+20, 50])), # second fuly connected layer",
"# Reshape conv2 output to fit fully connected layer input conv2_reshaped = tf.reshape(conv2,",
"tf.placeholder(tf.float32, [self.test_size, self.steps_back, self.cnn_num_input],name='Xb_test') self.Xe_test = tf.placeholder(tf.float32, [self.test_size, 1, 4], name='Xe_test') self.Y_test =",
"'wc1': tf.Variable(tf.random_normal([2, 8, 1, 32])), # 5x5 conv, 32 inputs, 64 outputs 'wc2':",
"32])), # 5x5 conv, 32 inputs, 64 outputs 'wc2': tf.Variable(tf.random_normal([2, 8, 32, 64])),",
": print(\"condition satisfied\") break # self.training_loss.append(training_l) # self.validation_loss.append(test_l) print(\"Optimization Finished!\") # Save the",
"= sess.run(\"prediction:0\", feed_dict={graph.get_tensor_by_name(\"Xb:0\"): xb, graph.get_tensor_by_name(\"Xe:0\"): xe, graph.get_tensor_by_name(\"keep_prob:0\"): 1.0}) return p if __name__ ==",
"sigmoid fc3_test = tf.add(tf.matmul(fc_test, self.weights['out']), self.biases['out']) fc3_sigmoided_test = tf.nn.sigmoid(fc3_test) # linear fc prediction_test",
"neural_net.combined_net() # saver = tf.train.Saver() # keep_prob = neural_net.keep_prob # init = tf.global_variables_initializer()",
"training Loss= \" + str(training_l)) print(\"Step \" + str(step) + \", Minibatch validation",
"tf.Variable(tf.random_normal([20+20, 50])), # second fuly connected layer 100 inputs and 1 output 'out2':",
"= 100, steps_back=8) scaler1 = {} for i in range(xb.shape[1]): scaler1[i] = MinMaxScaler(feature_range=(0,1),",
"plt.legend() # # plt.show() # def retrain(self,xb, xe, y,sess): # saver.restore(sess, \"./model.ckpt\") #",
"= 4 self.num_output = 1 # MNIST total classes (0-9 digits) self.dropout =",
"Finished!\") # Save the variables to disk. save_path = saver.save(sess, name) print(\"Model saved",
"self.num_output], name='Y_test') # Store layers weight & bias self.weights = { # 5x5",
"[-1, 1, self.fc_num_input]) p = sess.run(\"prediction:0\", feed_dict={graph.get_tensor_by_name(\"Xb:0\"): xb, graph.get_tensor_by_name(\"Xe:0\"): xe, graph.get_tensor_by_name(\"keep_prob:0\"): 1.0}) return",
"self.steps_back, self.num_TCL, 1]) # Convolution Layer conv1 = self.conv2d(xb, self.weights['wc1'],self.biases['bc1']) # Max Pooling",
"__init__(self, batch_size = 300, graph = tf.get_default_graph(),test_size = 0.1, steps_back=8, num_TCL=30): self.num_TCL =",
"20])), # fully connected for fl_net, 'wd2': tf.Variable(tf.random_normal([4, 20])), # 1024+10 inputs, 1",
"# Convolution Layer conv2 = self.conv2d(conv1, self.weights['wc2'], self.biases['bc2']) # Max Pooling (down-sampling) #",
"for fl_net, 'wd2': tf.Variable(tf.random_normal([4, 20])), # 1024+10 inputs, 1 output (class prediction) 'out':",
"sess.run(\"train_op\", feed_dict={graph.get_tensor_by_name(\"Xb:0\"): batch_tr_xb, graph.get_tensor_by_name(\"Xe:0\"): batch_tr_xe, graph.get_tensor_by_name(\"Y:0\"): batch_tr_y, graph.get_tensor_by_name(\"keep_prob:0\"): self.dropout}) # Calculate batch loss",
"tf.Variable(tf.random_normal([self.steps_back*self.cnn_num_input*64//4, 1024])), 'wd11': tf.Variable(tf.random_normal([1024, 20])), # fully connected for fl_net, 'wd2': tf.Variable(tf.random_normal([4, 20])),",
"+ str(step) + \", Minibatch validation Loss= \" + str(test_l)) if test_l -",
"self.num_output], name='Y') if self.test_proportion != 0: # Test Placeholders self.Xb_test = tf.placeholder(tf.float32, [self.test_size,",
"self.training_loss = [] self.validation_loss = [] with tf.Session(graph=graph) as sess: saver = tf.train.Saver()",
"print(\"condition satisfied\") break if test_l < 0.009 and training_l < 0.009 : print(\"condition",
"#linear fc prediction = tf.add(tf.matmul(fc3_sigmoided, self.weights['out2']), self.biases['out2'], name=\"prediction\") # Define loss and optimizer",
"tf.reshape(conv2, [-1, self.weights['wd1'].get_shape().as_list()[0]]) fc1 = tf.add(tf.matmul(conv2_reshaped, self.weights['wd1']), self.biases['bd1']) fc1_relued = tf.nn.relu(fc1) fc11 =",
"fit fully connected layer input conv2_reshaped = tf.reshape(conv2, [-1, self.weights['wd1'].get_shape().as_list()[0]]) fc1 = tf.add(tf.matmul(conv2_reshaped,",
"weight & bias self.weights = { # 5x5 conv 'wc1': tf.Variable(tf.random_normal([2, 8, 1,",
"num_TCL=30): self.num_TCL = num_TCL with graph.as_default(): # Training Parameters self.learning_rate = 0.1 self.num_steps",
"Max Pooling (down-sampling) # conv2 = self.maxpool2d(conv2, k=2) # Fully connected layer #",
"in range(xb.shape[1]): scaler1[i] = MinMaxScaler(feature_range=(0,1), copy=True) xb[:,i,:] = scaler1[i].fit_transform(xb[:,i,:]) scaler2 = MinMaxScaler(feature_range=(0,1), copy=True).fit(xe)",
"'bc1': tf.Variable(tf.random_normal([32])), 'bc2': tf.Variable(tf.random_normal([64])), 'bd1': tf.Variable(tf.random_normal([1024])), 'bd11': tf.Variable(tf.random_normal([20])), 'bd2': tf.Variable(tf.random_normal([20])), 'out': tf.Variable(tf.random_normal([50])), 'out2':",
"graph conv_component_test = self.conv_net(graph.get_tensor_by_name(\"Xb_test:0\")) fc_component_test = self.fc_net(graph.get_tensor_by_name(\"Xe_test:0\")) # concatenate the to components fc_test",
"fc prediction_test = tf.add(tf.matmul(fc3_sigmoided_test, self.weights['out2']), self.biases['out2'], name=\"prediction_test\") loss_op_test = tf.losses.mean_squared_error(predictions=prediction_test, labels=self.Y_test) def run_sess(self,",
"tf.add(tf.matmul(fc3_sigmoided_test, self.weights['out2']), self.biases['out2'], name=\"prediction_test\") loss_op_test = tf.losses.mean_squared_error(predictions=prediction_test, labels=self.Y_test) def run_sess(self, sess, batch_xb, batch_xe,",
"k, 1], strides=[1, k, k, 1], padding='SAME') # Create model def conv_net(self,xb): xb",
"steps_back self.batch_size = batch_size if batch_size==1: self.test_proportion = 0 else: self.test_proportion = test_size",
"tf.train.AdamOptimizer(learning_rate = self.learning_rate) train_op = optimizer.minimize(loss_op,name=\"train_op\") if self.test_proportion != 0: # Test graph",
"self.cnn_num_input],name='Xb_test') self.Xe_test = tf.placeholder(tf.float32, [self.test_size, 1, 4], name='Xe_test') self.Y_test = tf.placeholder(tf.float32, [self.test_size, self.num_output],",
"= tf.add(tf.matmul(fc3_sigmoided, self.weights['out2']), self.biases['out2'], name=\"prediction\") # Define loss and optimizer loss_op = tf.losses.mean_squared_error(predictions",
"= saver.save(sess, name) print(\"Model saved in path: %s\" % save_path) def train(self,xb, xe,",
"import numpy as np import tensorflow as tf from read_data import get_X_y from",
"= self.conv2d(xb, self.weights['wc1'],self.biases['bc1']) # Max Pooling (down-sampling) conv1 = self.maxpool2d(conv1, k=2) # Convolution",
"output (class prediction) 'out': tf.Variable(tf.random_normal([20+20, 50])), # second fuly connected layer 100 inputs",
"xe = tf.reshape(xe, shape=[-1, self.weights['wd2'].get_shape().as_list()[0]]) fc2 = tf.add(tf.matmul(xe, self.weights['wd2']), self.biases['bd2']) return tf.nn.relu(fc2) def",
"# self.run_sess(sess,xb,xe,y) def predict(self, xb, xe, sess): # tf Graph input graph =",
"sess.graph batch_xe = np.reshape(batch_xe,[-1,1,self.fc_num_input]) batch_xb = np.reshape(batch_xb, [-1, self.steps_back, self.cnn_num_input]) batch_y = np.reshape(batch_y,[-1,self.num_output])",
"fc_component_test = self.fc_net(graph.get_tensor_by_name(\"Xe_test:0\")) # concatenate the to components fc_test = tf.concat([conv_component_test, fc_component_test], axis=1)",
"def run_sess(self, sess, batch_xb, batch_xe, batch_y, saver, name): graph = sess.graph batch_xe =",
"with tf.Session(graph=graph) as sess: saver = tf.train.Saver() try: saver.restore(sess, name) except: sess.run(tf.global_variables_initializer()) for",
"= { 'bc1': tf.Variable(tf.random_normal([32])), 'bc2': tf.Variable(tf.random_normal([64])), 'bd1': tf.Variable(tf.random_normal([1024])), 'bd11': tf.Variable(tf.random_normal([20])), 'bd2': tf.Variable(tf.random_normal([20])), 'out':",
"op (backprop) sess.run(\"train_op\", feed_dict={graph.get_tensor_by_name(\"Xb:0\"): batch_tr_xb, graph.get_tensor_by_name(\"Xe:0\"): batch_tr_xe, graph.get_tensor_by_name(\"Y:0\"): batch_tr_y, graph.get_tensor_by_name(\"keep_prob:0\"): self.dropout}) # Calculate",
"initializer index = i*self.batch_size self.run_sess(sess, xb[index:index+self.batch_size],xe[index:index+self.batch_size],y[index:index+self.batch_size], saver, name= name) # plt.plot(range(len(self.training_loss)), self.training_loss, label='Training')",
"# MaxPool2D wrapper return tf.nn.max_pool(x, ksize=[1, k, k, 1], strides=[1, k, k, 1],",
"Minibatch validation Loss= \" + str(test_l)) if test_l - training_l> 0.015: overfitting +=",
"- self.test_proportion)) self.test_size = int(self.test_proportion*self.batch_size) self.keep_prob = tf.placeholder(tf.float32, name='keep_prob') # dropout (keep probability)",
"np.reshape(xb, [-1, self.steps_back, self.cnn_num_input]) xe = np.reshape(xe, [-1, 1, self.fc_num_input]) p = sess.run(\"prediction:0\",",
"& bias self.weights = { # 5x5 conv 'wc1': tf.Variable(tf.random_normal([2, 8, 1, 32])),",
"= tf.add(tf.matmul(fc3_sigmoided_test, self.weights['out2']), self.biases['out2'], name=\"prediction_test\") loss_op_test = tf.losses.mean_squared_error(predictions=prediction_test, labels=self.Y_test) def run_sess(self, sess, batch_xb,",
"and training_l < 0.009 : print(\"condition satisfied\") break # self.training_loss.append(training_l) # self.validation_loss.append(test_l) print(\"Optimization",
"# plt.show() # def retrain(self,xb, xe, y,sess): # saver.restore(sess, \"./model.ckpt\") # self.run_sess(sess,xb,xe,y) def",
"tf.Variable(tf.random_normal([4, 20])), # 1024+10 inputs, 1 output (class prediction) 'out': tf.Variable(tf.random_normal([20+20, 50])), #",
"Layer conv1 = self.conv2d(xb, self.weights['wc1'],self.biases['bc1']) # Max Pooling (down-sampling) conv1 = self.maxpool2d(conv1, k=2)",
"Minibatch training Loss= \" + str(training_l)) print(\"Step \" + str(step) + \", Minibatch",
"= tf.get_default_graph() ): self.training_loss = [] self.validation_loss = [] with tf.Session(graph=graph) as sess:",
"tf.train.Saver() # keep_prob = neural_net.keep_prob # init = tf.global_variables_initializer() # graph = tf.get_default_graph()",
"if overfitting >= 30 and training_l <= 0.01 : print(\"condition satisfied\") break if",
"tf.Variable(tf.random_normal([2, 8, 32, 64])), # fully connected for cnn 'wd1': tf.Variable(tf.random_normal([self.steps_back*self.cnn_num_input*64//4, 1024])), 'wd11':",
"# graph = tf.Graph() neural_net.combined_net() # saver = tf.train.Saver() # keep_prob = neural_net.keep_prob",
"= 0.1 self.num_steps = 100000 self.steps_back = steps_back self.batch_size = batch_size if batch_size==1:",
"tf.Variable(tf.random_normal([50])), 'out2': tf.Variable(tf.random_normal([self.num_output])) } # Create some wrappers for simplicity def conv2d(self, x,",
"test_l = sess.run(\"mean_squared_error_1/value:0\", feed_dict={graph.get_tensor_by_name(\"Xb_test:0\"): batch_test_xb, graph.get_tensor_by_name(\"Xe_test:0\"): batch_test_xe, graph.get_tensor_by_name(\"Y_test:0\"): batch_test_y, graph.get_tensor_by_name(\"keep_prob:0\"): 1.0}) if step",
"= np.reshape(xb, [-1, self.steps_back, self.cnn_num_input]) xe = np.reshape(xe, [-1, 1, self.fc_num_input]) p =",
"graph.get_tensor_by_name(\"Xe_test:0\"): batch_test_xe, graph.get_tensor_by_name(\"Y_test:0\"): batch_test_y, graph.get_tensor_by_name(\"keep_prob:0\"): 1.0}) if step % 10 == 0 or",
"k, k, 1], strides=[1, k, k, 1], padding='SAME') # Create model def conv_net(self,xb):",
"self.weights['out2']), self.biases['out2'], name=\"prediction\") # Define loss and optimizer loss_op = tf.losses.mean_squared_error(predictions = prediction",
"# fully connected for fl_net, 'wd2': tf.Variable(tf.random_normal([4, 20])), # 1024+10 inputs, 1 output",
"tf.get_default_graph(),test_size = 0.1, steps_back=8, num_TCL=30): self.num_TCL = num_TCL with graph.as_default(): # Training Parameters",
"as sess: saver = tf.train.Saver() try: saver.restore(sess, name) except: sess.run(tf.global_variables_initializer()) for i in",
"in path: %s\" % save_path) def train(self,xb, xe, y, name = \"./model0.ckpt\", graph",
"batch loss training_l = sess.run(\"mean_squared_error/value:0\", feed_dict={graph.get_tensor_by_name(\"Xb:0\"): batch_tr_xb, graph.get_tensor_by_name(\"Xe:0\"): batch_tr_xe, graph.get_tensor_by_name(\"Y:0\"): batch_tr_y, graph.get_tensor_by_name(\"keep_prob:0\"): 1.0})",
"xb, graph.get_tensor_by_name(\"Xe:0\"): xe, graph.get_tensor_by_name(\"keep_prob:0\"): 1.0}) return p if __name__ == '__main__': xb, xe,",
"= tf.reshape(xe, shape=[-1, self.weights['wd2'].get_shape().as_list()[0]]) fc2 = tf.add(tf.matmul(xe, self.weights['wd2']), self.biases['bd2']) return tf.nn.relu(fc2) def combined_net(self,",
"\", Minibatch validation Loss= \" + str(test_l)) if test_l - training_l> 0.015: overfitting",
"# keep_prob = neural_net.keep_prob # init = tf.global_variables_initializer() # graph = tf.get_default_graph() neural_net.train(xb,",
"1, 32])), # 5x5 conv, 32 inputs, 64 outputs 'wc2': tf.Variable(tf.random_normal([2, 8, 32,",
"return p if __name__ == '__main__': xb, xe, y = get_X_y(steps_back=7, filename=\"Q_data0.csv\") neural_net",
"to keep units # Placeholders self.Xb = tf.placeholder(tf.float32, [self.batch_tr_size, self.steps_back, self.cnn_num_input],name='Xb') self.Xe =",
"the to components fc = tf.concat([conv_component,fc_component], axis=1) # another fc net with sigmoid",
"conv 'wc1': tf.Variable(tf.random_normal([2, 8, 1, 32])), # 5x5 conv, 32 inputs, 64 outputs",
"W, b, strides=1): # Conv2D wrapper, with bias and relu activation x =",
"Create some wrappers for simplicity def conv2d(self, x, W, b, strides=1): # Conv2D",
"xb = np.reshape(xb, [-1, self.steps_back, self.cnn_num_input]) xe = np.reshape(xe, [-1, 1, self.fc_num_input]) p",
"tensorflow as tf from read_data import get_X_y from sklearn.preprocessing import MinMaxScaler import matplotlib.pyplot",
"tf.Graph() neural_net.combined_net() # saver = tf.train.Saver() # keep_prob = neural_net.keep_prob # init =",
"str(training_l)) print(\"Step \" + str(step) + \", Minibatch validation Loss= \" + str(test_l))",
"tf.placeholder(tf.float32, [self.batch_tr_size, self.num_output], name='Y') if self.test_proportion != 0: # Test Placeholders self.Xb_test =",
"batch_xe[self.batch_tr_size:] batch_tr_xb = batch_xb[:self.batch_tr_size] batch_test_xb = batch_xb[self.batch_tr_size:] batch_tr_y = batch_y[:self.batch_tr_size] batch_test_y = batch_y[self.batch_tr_size:]",
"MNIST data input self.fc_num_input = 4 self.num_output = 1 # MNIST total classes",
"axis=1) # another fc net with sigmoid fc3_test = tf.add(tf.matmul(fc_test, self.weights['out']), self.biases['out']) fc3_sigmoided_test",
"components fc = tf.concat([conv_component,fc_component], axis=1) # another fc net with sigmoid fc3 =",
"loss_op_test = tf.losses.mean_squared_error(predictions=prediction_test, labels=self.Y_test) def run_sess(self, sess, batch_xb, batch_xe, batch_y, saver, name): graph",
"= num_TCL # MNIST data input self.fc_num_input = 4 self.num_output = 1 #",
"sess: saver = tf.train.Saver() try: saver.restore(sess, name) except: sess.run(tf.global_variables_initializer()) for i in range(xb.shape[0]//self.batch_size):",
"num_TCL # MNIST data input self.fc_num_input = 4 self.num_output = 1 # MNIST",
"xe, sess): # tf Graph input graph = sess.graph xb = np.reshape(xb, [-1,",
"= np.reshape(xe, [-1, 1, self.fc_num_input]) p = sess.run(\"prediction:0\", feed_dict={graph.get_tensor_by_name(\"Xb:0\"): xb, graph.get_tensor_by_name(\"Xe:0\"): xe, graph.get_tensor_by_name(\"keep_prob:0\"):",
"= tf.placeholder(tf.float32, [self.batch_tr_size, self.steps_back, self.cnn_num_input],name='Xb') self.Xe = tf.placeholder(tf.float32, [self.batch_tr_size, 1, 4], name='Xe') self.Y",
"cnn 'wd1': tf.Variable(tf.random_normal([self.steps_back*self.cnn_num_input*64//4, 1024])), 'wd11': tf.Variable(tf.random_normal([1024, 20])), # fully connected for fl_net, 'wd2':",
"batch_tr_y, graph.get_tensor_by_name(\"keep_prob:0\"): self.dropout}) # Calculate batch loss training_l = sess.run(\"mean_squared_error/value:0\", feed_dict={graph.get_tensor_by_name(\"Xb:0\"): batch_tr_xb, graph.get_tensor_by_name(\"Xe:0\"):",
"train(self,xb, xe, y, name = \"./model0.ckpt\", graph = tf.get_default_graph() ): self.training_loss = []",
"!= 0: # Test Placeholders self.Xb_test = tf.placeholder(tf.float32, [self.test_size, self.steps_back, self.cnn_num_input],name='Xb_test') self.Xe_test =",
"get_X_y(steps_back=7, filename=\"Q_data0.csv\") neural_net = NN(batch_size = 100, steps_back=8) scaler1 = {} for i",
"= tf.Graph() neural_net.combined_net() # saver = tf.train.Saver() # keep_prob = neural_net.keep_prob # init",
"tf.placeholder(tf.float32, [self.test_size, 1, 4], name='Xe_test') self.Y_test = tf.placeholder(tf.float32, [self.test_size, self.num_output], name='Y_test') # Store",
"self.fc_net(self.Xe) # concatenate the to components fc = tf.concat([conv_component,fc_component], axis=1) # another fc",
"1): # Run optimization op (backprop) sess.run(\"train_op\", feed_dict={graph.get_tensor_by_name(\"Xb:0\"): batch_tr_xb, graph.get_tensor_by_name(\"Xe:0\"): batch_tr_xe, graph.get_tensor_by_name(\"Y:0\"): batch_tr_y,",
"name = \"./model0.ckpt\", graph = tf.get_default_graph() ): self.training_loss = [] self.validation_loss = []",
"y,sess): # saver.restore(sess, \"./model.ckpt\") # self.run_sess(sess,xb,xe,y) def predict(self, xb, xe, sess): # tf",
"= sess.run(\"mean_squared_error_1/value:0\", feed_dict={graph.get_tensor_by_name(\"Xb_test:0\"): batch_test_xb, graph.get_tensor_by_name(\"Xe_test:0\"): batch_test_xe, graph.get_tensor_by_name(\"Y_test:0\"): batch_test_y, graph.get_tensor_by_name(\"keep_prob:0\"): 1.0}) if step %",
"tf Graph input graph = sess.graph xb = np.reshape(xb, [-1, self.steps_back, self.cnn_num_input]) xe",
"if step % 10 == 0 or step == 1: print(\"Step \" +",
"name='Y') if self.test_proportion != 0: # Test Placeholders self.Xb_test = tf.placeholder(tf.float32, [self.test_size, self.steps_back,",
"xb, xe, sess): # tf Graph input graph = sess.graph xb = np.reshape(xb,",
"self.fc_num_input]) p = sess.run(\"prediction:0\", feed_dict={graph.get_tensor_by_name(\"Xb:0\"): xb, graph.get_tensor_by_name(\"Xe:0\"): xe, graph.get_tensor_by_name(\"keep_prob:0\"): 1.0}) return p if",
"k=2): # MaxPool2D wrapper return tf.nn.max_pool(x, ksize=[1, k, k, 1], strides=[1, k, k,",
"batch_tr_y = batch_y[:self.batch_tr_size] batch_test_y = batch_y[self.batch_tr_size:] overfitting=0 for step in range(1, self.num_steps +",
"\"./model.ckpt\") # self.run_sess(sess,xb,xe,y) def predict(self, xb, xe, sess): # tf Graph input graph",
"if __name__ == '__main__': xb, xe, y = get_X_y(steps_back=7, filename=\"Q_data0.csv\") neural_net = NN(batch_size",
"from sklearn.preprocessing import MinMaxScaler import matplotlib.pyplot as plt import pickle class NN(): def",
"test_l < 0.009 and training_l < 0.009 : print(\"condition satisfied\") break # self.training_loss.append(training_l)",
"= 0.85 # Dropout, probability to keep units # Placeholders self.Xb = tf.placeholder(tf.float32,",
"if self.test_proportion != 0: # Test graph conv_component_test = self.conv_net(graph.get_tensor_by_name(\"Xb_test:0\")) fc_component_test = self.fc_net(graph.get_tensor_by_name(\"Xe_test:0\"))",
"and 1 output 'out2': tf.Variable(tf.random_normal([50, self.num_output])) } self.biases = { 'bc1': tf.Variable(tf.random_normal([32])), 'bc2':",
"tf.Variable(tf.random_normal([64])), 'bd1': tf.Variable(tf.random_normal([1024])), 'bd11': tf.Variable(tf.random_normal([20])), 'bd2': tf.Variable(tf.random_normal([20])), 'out': tf.Variable(tf.random_normal([50])), 'out2': tf.Variable(tf.random_normal([self.num_output])) } #",
"# Max Pooling (down-sampling) conv1 = self.maxpool2d(conv1, k=2) # Convolution Layer conv2 =",
"self.weights['out2']), self.biases['out2'], name=\"prediction_test\") loss_op_test = tf.losses.mean_squared_error(predictions=prediction_test, labels=self.Y_test) def run_sess(self, sess, batch_xb, batch_xe, batch_y,",
"feed_dict={graph.get_tensor_by_name(\"Xb:0\"): batch_tr_xb, graph.get_tensor_by_name(\"Xe:0\"): batch_tr_xe, graph.get_tensor_by_name(\"Y:0\"): batch_tr_y, graph.get_tensor_by_name(\"keep_prob:0\"): self.dropout}) # Calculate batch loss training_l",
"batch_test_xe, graph.get_tensor_by_name(\"Y_test:0\"): batch_test_y, graph.get_tensor_by_name(\"keep_prob:0\"): 1.0}) if step % 10 == 0 or step",
"= tf.placeholder(tf.float32, [self.test_size, 1, 4], name='Xe_test') self.Y_test = tf.placeholder(tf.float32, [self.test_size, self.num_output], name='Y_test') #",
"'wc2': tf.Variable(tf.random_normal([2, 8, 32, 64])), # fully connected for cnn 'wd1': tf.Variable(tf.random_normal([self.steps_back*self.cnn_num_input*64//4, 1024])),",
"= self.learning_rate) train_op = optimizer.minimize(loss_op,name=\"train_op\") if self.test_proportion != 0: # Test graph conv_component_test",
"64])), # fully connected for cnn 'wd1': tf.Variable(tf.random_normal([self.steps_back*self.cnn_num_input*64//4, 1024])), 'wd11': tf.Variable(tf.random_normal([1024, 20])), #",
"import tensorflow as tf from read_data import get_X_y from sklearn.preprocessing import MinMaxScaler import",
"fc1_relued = tf.nn.relu(fc1) fc11 = tf.add(tf.matmul(fc1_relued, self.weights['wd11']), self.biases['bd11']) fc11_relued = tf.nn.relu(fc11) ## Apply",
"1024+10 inputs, 1 output (class prediction) 'out': tf.Variable(tf.random_normal([20+20, 50])), # second fuly connected",
"{ 'bc1': tf.Variable(tf.random_normal([32])), 'bc2': tf.Variable(tf.random_normal([64])), 'bd1': tf.Variable(tf.random_normal([1024])), 'bd11': tf.Variable(tf.random_normal([20])), 'bd2': tf.Variable(tf.random_normal([20])), 'out': tf.Variable(tf.random_normal([50])),",
"self.steps_back, self.cnn_num_input],name='Xb_test') self.Xe_test = tf.placeholder(tf.float32, [self.test_size, 1, 4], name='Xe_test') self.Y_test = tf.placeholder(tf.float32, [self.test_size,",
"tf.nn.sigmoid(fc3) #linear fc prediction = tf.add(tf.matmul(fc3_sigmoided, self.weights['out2']), self.biases['out2'], name=\"prediction\") # Define loss and",
"self.num_output = 1 # MNIST total classes (0-9 digits) self.dropout = 0.85 #",
"tf.Session(graph=graph) as sess: saver = tf.train.Saver() try: saver.restore(sess, name) except: sess.run(tf.global_variables_initializer()) for i",
"MinMaxScaler import matplotlib.pyplot as plt import pickle class NN(): def __init__(self, batch_size =",
"def train(self,xb, xe, y, name = \"./model0.ckpt\", graph = tf.get_default_graph() ): self.training_loss =",
"# Convolution Layer conv1 = self.conv2d(xb, self.weights['wc1'],self.biases['bc1']) # Max Pooling (down-sampling) conv1 =",
"self.test_proportion != 0: # Test graph conv_component_test = self.conv_net(graph.get_tensor_by_name(\"Xb_test:0\")) fc_component_test = self.fc_net(graph.get_tensor_by_name(\"Xe_test:0\")) #",
"Network Parameters self.cnn_num_input = num_TCL # MNIST data input self.fc_num_input = 4 self.num_output",
"= self.fc_net(self.Xe) # concatenate the to components fc = tf.concat([conv_component,fc_component], axis=1) # another",
"(0-9 digits) self.dropout = 0.85 # Dropout, probability to keep units # Placeholders",
"connected layer 100 inputs and 1 output 'out2': tf.Variable(tf.random_normal([50, self.num_output])) } self.biases =",
"xe, graph.get_tensor_by_name(\"keep_prob:0\"): 1.0}) return p if __name__ == '__main__': xb, xe, y =",
"fc11_relued = tf.nn.relu(fc11) ## Apply Dropout return tf.nn.dropout(fc11_relued, self.keep_prob) def fc_net(self,xe): xe =",
"conv, 32 inputs, 64 outputs 'wc2': tf.Variable(tf.random_normal([2, 8, 32, 64])), # fully connected",
"graph.get_tensor_by_name(\"Xe:0\"): xe, graph.get_tensor_by_name(\"keep_prob:0\"): 1.0}) return p if __name__ == '__main__': xb, xe, y",
"{ # 5x5 conv 'wc1': tf.Variable(tf.random_normal([2, 8, 1, 32])), # 5x5 conv, 32",
"conv1 = self.conv2d(xb, self.weights['wc1'],self.biases['bc1']) # Max Pooling (down-sampling) conv1 = self.maxpool2d(conv1, k=2) #",
"Define loss and optimizer loss_op = tf.losses.mean_squared_error(predictions = prediction ,labels = self.Y) optimizer",
"prediction_test = tf.add(tf.matmul(fc3_sigmoided_test, self.weights['out2']), self.biases['out2'], name=\"prediction_test\") loss_op_test = tf.losses.mean_squared_error(predictions=prediction_test, labels=self.Y_test) def run_sess(self, sess,",
"self.num_TCL, 1]) # Convolution Layer conv1 = self.conv2d(xb, self.weights['wc1'],self.biases['bc1']) # Max Pooling (down-sampling)",
"graph.get_tensor_by_name(\"keep_prob:0\"): 1.0}) return p if __name__ == '__main__': xb, xe, y = get_X_y(steps_back=7,",
"32 inputs, 64 outputs 'wc2': tf.Variable(tf.random_normal([2, 8, 32, 64])), # fully connected for",
"self.cnn_num_input = num_TCL # MNIST data input self.fc_num_input = 4 self.num_output = 1",
"return tf.nn.dropout(fc11_relued, self.keep_prob) def fc_net(self,xe): xe = tf.reshape(xe, shape=[-1, self.weights['wd2'].get_shape().as_list()[0]]) fc2 = tf.add(tf.matmul(xe,",
"= batch_xe[self.batch_tr_size:] batch_tr_xb = batch_xb[:self.batch_tr_size] batch_test_xb = batch_xb[self.batch_tr_size:] batch_tr_y = batch_y[:self.batch_tr_size] batch_test_y =",
"+ 1): # Run optimization op (backprop) sess.run(\"train_op\", feed_dict={graph.get_tensor_by_name(\"Xb:0\"): batch_tr_xb, graph.get_tensor_by_name(\"Xe:0\"): batch_tr_xe, graph.get_tensor_by_name(\"Y:0\"):",
"20])), # 1024+10 inputs, 1 output (class prediction) 'out': tf.Variable(tf.random_normal([20+20, 50])), # second",
"batch_tr_xe = batch_xe[:self.batch_tr_size] batch_test_xe = batch_xe[self.batch_tr_size:] batch_tr_xb = batch_xb[:self.batch_tr_size] batch_test_xb = batch_xb[self.batch_tr_size:] batch_tr_y",
"= sess.graph xb = np.reshape(xb, [-1, self.steps_back, self.cnn_num_input]) xe = np.reshape(xe, [-1, 1,",
"test_size self.batch_tr_size = int(self.batch_size * (1 - self.test_proportion)) self.test_size = int(self.test_proportion*self.batch_size) self.keep_prob =",
"scaler1 = {} for i in range(xb.shape[1]): scaler1[i] = MinMaxScaler(feature_range=(0,1), copy=True) xb[:,i,:] =",
"} self.biases = { 'bc1': tf.Variable(tf.random_normal([32])), 'bc2': tf.Variable(tf.random_normal([64])), 'bd1': tf.Variable(tf.random_normal([1024])), 'bd11': tf.Variable(tf.random_normal([20])), 'bd2':",
"graph = sess.graph xb = np.reshape(xb, [-1, self.steps_back, self.cnn_num_input]) xe = np.reshape(xe, [-1,",
"self.test_proportion = 0 else: self.test_proportion = test_size self.batch_tr_size = int(self.batch_size * (1 -",
"steps_back=8) scaler1 = {} for i in range(xb.shape[1]): scaler1[i] = MinMaxScaler(feature_range=(0,1), copy=True) xb[:,i,:]",
"= steps_back self.batch_size = batch_size if batch_size==1: self.test_proportion = 0 else: self.test_proportion =",
"layer input conv2_reshaped = tf.reshape(conv2, [-1, self.weights['wd1'].get_shape().as_list()[0]]) fc1 = tf.add(tf.matmul(conv2_reshaped, self.weights['wd1']), self.biases['bd1']) fc1_relued",
"p if __name__ == '__main__': xb, xe, y = get_X_y(steps_back=7, filename=\"Q_data0.csv\") neural_net =",
"connected layer # Reshape conv2 output to fit fully connected layer input conv2_reshaped",
"tf.concat([conv_component_test, fc_component_test], axis=1) # another fc net with sigmoid fc3_test = tf.add(tf.matmul(fc_test, self.weights['out']),",
"sess.run(\"mean_squared_error/value:0\", feed_dict={graph.get_tensor_by_name(\"Xb:0\"): batch_tr_xb, graph.get_tensor_by_name(\"Xe:0\"): batch_tr_xe, graph.get_tensor_by_name(\"Y:0\"): batch_tr_y, graph.get_tensor_by_name(\"keep_prob:0\"): 1.0}) test_l = sess.run(\"mean_squared_error_1/value:0\", feed_dict={graph.get_tensor_by_name(\"Xb_test:0\"):",
"self.conv_net(self.Xb) fc_component = self.fc_net(self.Xe) # concatenate the to components fc = tf.concat([conv_component,fc_component], axis=1)",
"300, graph = tf.get_default_graph(),test_size = 0.1, steps_back=8, num_TCL=30): self.num_TCL = num_TCL with graph.as_default():",
"fl_net, 'wd2': tf.Variable(tf.random_normal([4, 20])), # 1024+10 inputs, 1 output (class prediction) 'out': tf.Variable(tf.random_normal([20+20,",
"= self.conv_net(self.Xb) fc_component = self.fc_net(self.Xe) # concatenate the to components fc = tf.concat([conv_component,fc_component],",
"name): graph = sess.graph batch_xe = np.reshape(batch_xe,[-1,1,self.fc_num_input]) batch_xb = np.reshape(batch_xb, [-1, self.steps_back, self.cnn_num_input])",
"NN(batch_size = 100, steps_back=8) scaler1 = {} for i in range(xb.shape[1]): scaler1[i] =",
"copy=True) xb[:,i,:] = scaler1[i].fit_transform(xb[:,i,:]) scaler2 = MinMaxScaler(feature_range=(0,1), copy=True).fit(xe) scaler3 = MinMaxScaler(feature_range=(0, 1), copy=True).fit(y.reshape(-1,1))",
"def maxpool2d(self, x, k=2): # MaxPool2D wrapper return tf.nn.max_pool(x, ksize=[1, k, k, 1],",
"np.reshape(batch_xb, [-1, self.steps_back, self.cnn_num_input]) batch_y = np.reshape(batch_y,[-1,self.num_output]) batch_tr_xe = batch_xe[:self.batch_tr_size] batch_test_xe = batch_xe[self.batch_tr_size:]",
"MinMaxScaler(feature_range=(0,1), copy=True).fit(xe) scaler3 = MinMaxScaler(feature_range=(0, 1), copy=True).fit(y.reshape(-1,1)) xe= scaler2.transform(xe) y= scaler3.transform(y.reshape(-1,1)) # graph",
"for simplicity def conv2d(self, x, W, b, strides=1): # Conv2D wrapper, with bias",
"return tf.nn.relu(fc2) def combined_net(self, graph = tf.get_default_graph()): with graph.as_default(): conv_component = self.conv_net(self.Xb) fc_component",
"0.1 self.num_steps = 100000 self.steps_back = steps_back self.batch_size = batch_size if batch_size==1: self.test_proportion",
"fc prediction = tf.add(tf.matmul(fc3_sigmoided, self.weights['out2']), self.biases['out2'], name=\"prediction\") # Define loss and optimizer loss_op",
"self.Y_test = tf.placeholder(tf.float32, [self.test_size, self.num_output], name='Y_test') # Store layers weight & bias self.weights",
"p = sess.run(\"prediction:0\", feed_dict={graph.get_tensor_by_name(\"Xb:0\"): xb, graph.get_tensor_by_name(\"Xe:0\"): xe, graph.get_tensor_by_name(\"keep_prob:0\"): 1.0}) return p if __name__",
"plt.plot(range(len(self.training_loss)), self.training_loss, label='Training') # plt.plot(range(len(self.validation_loss)), self.validation_loss, label='Validation') # plt.xlabel('Steps') # # plt.ylabel('Loss') #",
"self.weights['wd2']), self.biases['bd2']) return tf.nn.relu(fc2) def combined_net(self, graph = tf.get_default_graph()): with graph.as_default(): conv_component =",
"feed_dict={graph.get_tensor_by_name(\"Xb:0\"): xb, graph.get_tensor_by_name(\"Xe:0\"): xe, graph.get_tensor_by_name(\"keep_prob:0\"): 1.0}) return p if __name__ == '__main__': xb,",
"Parameters self.learning_rate = 0.1 self.num_steps = 100000 self.steps_back = steps_back self.batch_size = batch_size",
"Loss= \" + str(test_l)) if test_l - training_l> 0.015: overfitting += 1 else:",
"range(1, self.num_steps + 1): # Run optimization op (backprop) sess.run(\"train_op\", feed_dict={graph.get_tensor_by_name(\"Xb:0\"): batch_tr_xb, graph.get_tensor_by_name(\"Xe:0\"):",
"+= 1 else: overfitting = 0 if overfitting >= 30 and training_l <=",
"second fuly connected layer 100 inputs and 1 output 'out2': tf.Variable(tf.random_normal([50, self.num_output])) }",
"import pickle class NN(): def __init__(self, batch_size = 300, graph = tf.get_default_graph(),test_size =",
"graph = tf.get_default_graph()): with graph.as_default(): conv_component = self.conv_net(self.Xb) fc_component = self.fc_net(self.Xe) # concatenate",
"# Test Placeholders self.Xb_test = tf.placeholder(tf.float32, [self.test_size, self.steps_back, self.cnn_num_input],name='Xb_test') self.Xe_test = tf.placeholder(tf.float32, [self.test_size,",
"- training_l> 0.015: overfitting += 1 else: overfitting = 0 if overfitting >=",
"the to components fc_test = tf.concat([conv_component_test, fc_component_test], axis=1) # another fc net with",
"total classes (0-9 digits) self.dropout = 0.85 # Dropout, probability to keep units",
"some wrappers for simplicity def conv2d(self, x, W, b, strides=1): # Conv2D wrapper,",
"# saver = tf.train.Saver() # keep_prob = neural_net.keep_prob # init = tf.global_variables_initializer() #",
"graph.get_tensor_by_name(\"keep_prob:0\"): 1.0}) test_l = sess.run(\"mean_squared_error_1/value:0\", feed_dict={graph.get_tensor_by_name(\"Xb_test:0\"): batch_test_xb, graph.get_tensor_by_name(\"Xe_test:0\"): batch_test_xe, graph.get_tensor_by_name(\"Y_test:0\"): batch_test_y, graph.get_tensor_by_name(\"keep_prob:0\"): 1.0})",
"else: self.test_proportion = test_size self.batch_tr_size = int(self.batch_size * (1 - self.test_proportion)) self.test_size =",
"Placeholders self.Xb = tf.placeholder(tf.float32, [self.batch_tr_size, self.steps_back, self.cnn_num_input],name='Xb') self.Xe = tf.placeholder(tf.float32, [self.batch_tr_size, 1, 4],",
"= tf.placeholder(tf.float32, [self.batch_tr_size, self.num_output], name='Y') if self.test_proportion != 0: # Test Placeholders self.Xb_test",
"scaler1[i] = MinMaxScaler(feature_range=(0,1), copy=True) xb[:,i,:] = scaler1[i].fit_transform(xb[:,i,:]) scaler2 = MinMaxScaler(feature_range=(0,1), copy=True).fit(xe) scaler3 =",
"+ str(training_l)) print(\"Step \" + str(step) + \", Minibatch validation Loss= \" +",
"fc3 = tf.add(tf.matmul(fc, self.weights['out']), self.biases['out']) fc3_sigmoided = tf.nn.sigmoid(fc3) #linear fc prediction = tf.add(tf.matmul(fc3_sigmoided,",
"conv2 = self.maxpool2d(conv2, k=2) # Fully connected layer # Reshape conv2 output to",
"= tf.placeholder(tf.float32, [self.test_size, self.steps_back, self.cnn_num_input],name='Xb_test') self.Xe_test = tf.placeholder(tf.float32, [self.test_size, 1, 4], name='Xe_test') self.Y_test",
"plt.ylabel('Loss') # # plt.title(\"Loss function\") # # plt.legend() # # plt.show() # def",
"(keep probability) # display_step = 10 # Network Parameters self.cnn_num_input = num_TCL #",
"import matplotlib.pyplot as plt import pickle class NN(): def __init__(self, batch_size = 300,",
"tf.placeholder(tf.float32, [self.batch_tr_size, self.steps_back, self.cnn_num_input],name='Xb') self.Xe = tf.placeholder(tf.float32, [self.batch_tr_size, 1, 4], name='Xe') self.Y =",
"[self.batch_tr_size, self.steps_back, self.cnn_num_input],name='Xb') self.Xe = tf.placeholder(tf.float32, [self.batch_tr_size, 1, 4], name='Xe') self.Y = tf.placeholder(tf.float32,",
"self.training_loss.append(training_l) # self.validation_loss.append(test_l) print(\"Optimization Finished!\") # Save the variables to disk. save_path =",
"self.test_proportion != 0: # Test Placeholders self.Xb_test = tf.placeholder(tf.float32, [self.test_size, self.steps_back, self.cnn_num_input],name='Xb_test') self.Xe_test",
"def retrain(self,xb, xe, y,sess): # saver.restore(sess, \"./model.ckpt\") # self.run_sess(sess,xb,xe,y) def predict(self, xb, xe,",
"output 'out2': tf.Variable(tf.random_normal([50, self.num_output])) } self.biases = { 'bc1': tf.Variable(tf.random_normal([32])), 'bc2': tf.Variable(tf.random_normal([64])), 'bd1':",
"scaler2 = MinMaxScaler(feature_range=(0,1), copy=True).fit(xe) scaler3 = MinMaxScaler(feature_range=(0, 1), copy=True).fit(y.reshape(-1,1)) xe= scaler2.transform(xe) y= scaler3.transform(y.reshape(-1,1))",
"# Define loss and optimizer loss_op = tf.losses.mean_squared_error(predictions = prediction ,labels = self.Y)",
"from read_data import get_X_y from sklearn.preprocessing import MinMaxScaler import matplotlib.pyplot as plt import",
"self.cnn_num_input],name='Xb') self.Xe = tf.placeholder(tf.float32, [self.batch_tr_size, 1, 4], name='Xe') self.Y = tf.placeholder(tf.float32, [self.batch_tr_size, self.num_output],",
"= tf.placeholder(tf.float32, name='keep_prob') # dropout (keep probability) # display_step = 10 # Network",
"+ str(step) + \", Minibatch training Loss= \" + str(training_l)) print(\"Step \" +",
"units # Placeholders self.Xb = tf.placeholder(tf.float32, [self.batch_tr_size, self.steps_back, self.cnn_num_input],name='Xb') self.Xe = tf.placeholder(tf.float32, [self.batch_tr_size,",
",labels = self.Y) optimizer = tf.train.AdamOptimizer(learning_rate = self.learning_rate) train_op = optimizer.minimize(loss_op,name=\"train_op\") if self.test_proportion",
"tf.train.Saver() try: saver.restore(sess, name) except: sess.run(tf.global_variables_initializer()) for i in range(xb.shape[0]//self.batch_size): # Run the",
"4], name='Xe') self.Y = tf.placeholder(tf.float32, [self.batch_tr_size, self.num_output], name='Y') if self.test_proportion != 0: #",
"64 outputs 'wc2': tf.Variable(tf.random_normal([2, 8, 32, 64])), # fully connected for cnn 'wd1':",
"= tf.losses.mean_squared_error(predictions = prediction ,labels = self.Y) optimizer = tf.train.AdamOptimizer(learning_rate = self.learning_rate) train_op",
"= tf.concat([conv_component,fc_component], axis=1) # another fc net with sigmoid fc3 = tf.add(tf.matmul(fc, self.weights['out']),",
"= batch_y[:self.batch_tr_size] batch_test_y = batch_y[self.batch_tr_size:] overfitting=0 for step in range(1, self.num_steps + 1):",
"print(\"Step \" + str(step) + \", Minibatch training Loss= \" + str(training_l)) print(\"Step",
"batch_xb = np.reshape(batch_xb, [-1, self.steps_back, self.cnn_num_input]) batch_y = np.reshape(batch_y,[-1,self.num_output]) batch_tr_xe = batch_xe[:self.batch_tr_size] batch_test_xe",
"prediction) 'out': tf.Variable(tf.random_normal([20+20, 50])), # second fuly connected layer 100 inputs and 1",
"batch_size==1: self.test_proportion = 0 else: self.test_proportion = test_size self.batch_tr_size = int(self.batch_size * (1",
"y = get_X_y(steps_back=7, filename=\"Q_data0.csv\") neural_net = NN(batch_size = 100, steps_back=8) scaler1 = {}",
"linear fc prediction_test = tf.add(tf.matmul(fc3_sigmoided_test, self.weights['out2']), self.biases['out2'], name=\"prediction_test\") loss_op_test = tf.losses.mean_squared_error(predictions=prediction_test, labels=self.Y_test) def",
"tf.Variable(tf.random_normal([50, self.num_output])) } self.biases = { 'bc1': tf.Variable(tf.random_normal([32])), 'bc2': tf.Variable(tf.random_normal([64])), 'bd1': tf.Variable(tf.random_normal([1024])), 'bd11':",
"xb = tf.reshape(xb, shape=[-1, self.steps_back, self.num_TCL, 1]) # Convolution Layer conv1 = self.conv2d(xb,",
"= tf.add(tf.matmul(xe, self.weights['wd2']), self.biases['bd2']) return tf.nn.relu(fc2) def combined_net(self, graph = tf.get_default_graph()): with graph.as_default():",
"= tf.reshape(xb, shape=[-1, self.steps_back, self.num_TCL, 1]) # Convolution Layer conv1 = self.conv2d(xb, self.weights['wc1'],self.biases['bc1'])",
"xe= scaler2.transform(xe) y= scaler3.transform(y.reshape(-1,1)) # graph = tf.Graph() neural_net.combined_net() # saver = tf.train.Saver()",
"tf.placeholder(tf.float32, [self.test_size, self.num_output], name='Y_test') # Store layers weight & bias self.weights = {",
"sess.run(\"mean_squared_error_1/value:0\", feed_dict={graph.get_tensor_by_name(\"Xb_test:0\"): batch_test_xb, graph.get_tensor_by_name(\"Xe_test:0\"): batch_test_xe, graph.get_tensor_by_name(\"Y_test:0\"): batch_test_y, graph.get_tensor_by_name(\"keep_prob:0\"): 1.0}) if step % 10",
"graph = tf.get_default_graph(),test_size = 0.1, steps_back=8, num_TCL=30): self.num_TCL = num_TCL with graph.as_default(): #",
"= sess.run(\"mean_squared_error/value:0\", feed_dict={graph.get_tensor_by_name(\"Xb:0\"): batch_tr_xb, graph.get_tensor_by_name(\"Xe:0\"): batch_tr_xe, graph.get_tensor_by_name(\"Y:0\"): batch_tr_y, graph.get_tensor_by_name(\"keep_prob:0\"): 1.0}) test_l = sess.run(\"mean_squared_error_1/value:0\",",
"# self.training_loss.append(training_l) # self.validation_loss.append(test_l) print(\"Optimization Finished!\") # Save the variables to disk. save_path",
"5x5 conv 'wc1': tf.Variable(tf.random_normal([2, 8, 1, 32])), # 5x5 conv, 32 inputs, 64",
"tf.add(tf.matmul(fc1_relued, self.weights['wd11']), self.biases['bd11']) fc11_relued = tf.nn.relu(fc11) ## Apply Dropout return tf.nn.dropout(fc11_relued, self.keep_prob) def",
"= tf.add(tf.matmul(conv2_reshaped, self.weights['wd1']), self.biases['bd1']) fc1_relued = tf.nn.relu(fc1) fc11 = tf.add(tf.matmul(fc1_relued, self.weights['wd11']), self.biases['bd11']) fc11_relued",
"tf.nn.max_pool(x, ksize=[1, k, k, 1], strides=[1, k, k, 1], padding='SAME') # Create model",
"<= 0.01 : print(\"condition satisfied\") break if test_l < 0.009 and training_l <",
"saver.restore(sess, name) except: sess.run(tf.global_variables_initializer()) for i in range(xb.shape[0]//self.batch_size): # Run the initializer index",
"1], padding='SAME') # Create model def conv_net(self,xb): xb = tf.reshape(xb, shape=[-1, self.steps_back, self.num_TCL,",
"optimizer loss_op = tf.losses.mean_squared_error(predictions = prediction ,labels = self.Y) optimizer = tf.train.AdamOptimizer(learning_rate =",
"# Calculate batch loss training_l = sess.run(\"mean_squared_error/value:0\", feed_dict={graph.get_tensor_by_name(\"Xb:0\"): batch_tr_xb, graph.get_tensor_by_name(\"Xe:0\"): batch_tr_xe, graph.get_tensor_by_name(\"Y:0\"): batch_tr_y,",
"1: print(\"Step \" + str(step) + \", Minibatch training Loss= \" + str(training_l))",
"1, self.fc_num_input]) p = sess.run(\"prediction:0\", feed_dict={graph.get_tensor_by_name(\"Xb:0\"): xb, graph.get_tensor_by_name(\"Xe:0\"): xe, graph.get_tensor_by_name(\"keep_prob:0\"): 1.0}) return p",
"tf.reshape(xe, shape=[-1, self.weights['wd2'].get_shape().as_list()[0]]) fc2 = tf.add(tf.matmul(xe, self.weights['wd2']), self.biases['bd2']) return tf.nn.relu(fc2) def combined_net(self, graph",
"MinMaxScaler(feature_range=(0, 1), copy=True).fit(y.reshape(-1,1)) xe= scaler2.transform(xe) y= scaler3.transform(y.reshape(-1,1)) # graph = tf.Graph() neural_net.combined_net() #",
"# # plt.legend() # # plt.show() # def retrain(self,xb, xe, y,sess): # saver.restore(sess,",
"str(step) + \", Minibatch training Loss= \" + str(training_l)) print(\"Step \" + str(step)",
"int(self.test_proportion*self.batch_size) self.keep_prob = tf.placeholder(tf.float32, name='keep_prob') # dropout (keep probability) # display_step = 10",
"def fc_net(self,xe): xe = tf.reshape(xe, shape=[-1, self.weights['wd2'].get_shape().as_list()[0]]) fc2 = tf.add(tf.matmul(xe, self.weights['wd2']), self.biases['bd2']) return",
"= [] self.validation_loss = [] with tf.Session(graph=graph) as sess: saver = tf.train.Saver() try:",
"get_X_y from sklearn.preprocessing import MinMaxScaler import matplotlib.pyplot as plt import pickle class NN():",
"tf.nn.bias_add(x, b) return tf.nn.relu(x) def maxpool2d(self, x, k=2): # MaxPool2D wrapper return tf.nn.max_pool(x,",
"# MNIST total classes (0-9 digits) self.dropout = 0.85 # Dropout, probability to",
"0.015: overfitting += 1 else: overfitting = 0 if overfitting >= 30 and",
"print(\"condition satisfied\") break # self.training_loss.append(training_l) # self.validation_loss.append(test_l) print(\"Optimization Finished!\") # Save the variables",
"tf.nn.relu(x) def maxpool2d(self, x, k=2): # MaxPool2D wrapper return tf.nn.max_pool(x, ksize=[1, k, k,",
"k=2) # Convolution Layer conv2 = self.conv2d(conv1, self.weights['wc2'], self.biases['bc2']) # Max Pooling (down-sampling)",
"feed_dict={graph.get_tensor_by_name(\"Xb:0\"): batch_tr_xb, graph.get_tensor_by_name(\"Xe:0\"): batch_tr_xe, graph.get_tensor_by_name(\"Y:0\"): batch_tr_y, graph.get_tensor_by_name(\"keep_prob:0\"): 1.0}) test_l = sess.run(\"mean_squared_error_1/value:0\", feed_dict={graph.get_tensor_by_name(\"Xb_test:0\"): batch_test_xb,",
"data input self.fc_num_input = 4 self.num_output = 1 # MNIST total classes (0-9",
"'wd1': tf.Variable(tf.random_normal([self.steps_back*self.cnn_num_input*64//4, 1024])), 'wd11': tf.Variable(tf.random_normal([1024, 20])), # fully connected for fl_net, 'wd2': tf.Variable(tf.random_normal([4,",
"step == 1: print(\"Step \" + str(step) + \", Minibatch training Loss= \"",
"= batch_xb[:self.batch_tr_size] batch_test_xb = batch_xb[self.batch_tr_size:] batch_tr_y = batch_y[:self.batch_tr_size] batch_test_y = batch_y[self.batch_tr_size:] overfitting=0 for",
"plt.title(\"Loss function\") # # plt.legend() # # plt.show() # def retrain(self,xb, xe, y,sess):",
"probability to keep units # Placeholders self.Xb = tf.placeholder(tf.float32, [self.batch_tr_size, self.steps_back, self.cnn_num_input],name='Xb') self.Xe",
"Conv2D wrapper, with bias and relu activation x = tf.nn.conv2d(x, W, strides=[1, strides,",
"= int(self.test_proportion*self.batch_size) self.keep_prob = tf.placeholder(tf.float32, name='keep_prob') # dropout (keep probability) # display_step =",
"0: # Test Placeholders self.Xb_test = tf.placeholder(tf.float32, [self.test_size, self.steps_back, self.cnn_num_input],name='Xb_test') self.Xe_test = tf.placeholder(tf.float32,",
"connected layer input conv2_reshaped = tf.reshape(conv2, [-1, self.weights['wd1'].get_shape().as_list()[0]]) fc1 = tf.add(tf.matmul(conv2_reshaped, self.weights['wd1']), self.biases['bd1'])",
"graph.as_default(): conv_component = self.conv_net(self.Xb) fc_component = self.fc_net(self.Xe) # concatenate the to components fc",
"+ \", Minibatch training Loss= \" + str(training_l)) print(\"Step \" + str(step) +",
"+ \", Minibatch validation Loss= \" + str(test_l)) if test_l - training_l> 0.015:",
"graph = tf.Graph() neural_net.combined_net() # saver = tf.train.Saver() # keep_prob = neural_net.keep_prob #",
"int(self.batch_size * (1 - self.test_proportion)) self.test_size = int(self.test_proportion*self.batch_size) self.keep_prob = tf.placeholder(tf.float32, name='keep_prob') #",
"'wd2': tf.Variable(tf.random_normal([4, 20])), # 1024+10 inputs, 1 output (class prediction) 'out': tf.Variable(tf.random_normal([20+20, 50])),",
"= tf.nn.relu(fc11) ## Apply Dropout return tf.nn.dropout(fc11_relued, self.keep_prob) def fc_net(self,xe): xe = tf.reshape(xe,",
"overfitting = 0 if overfitting >= 30 and training_l <= 0.01 : print(\"condition",
"inputs and 1 output 'out2': tf.Variable(tf.random_normal([50, self.num_output])) } self.biases = { 'bc1': tf.Variable(tf.random_normal([32])),",
"(backprop) sess.run(\"train_op\", feed_dict={graph.get_tensor_by_name(\"Xb:0\"): batch_tr_xb, graph.get_tensor_by_name(\"Xe:0\"): batch_tr_xe, graph.get_tensor_by_name(\"Y:0\"): batch_tr_y, graph.get_tensor_by_name(\"keep_prob:0\"): self.dropout}) # Calculate batch",
"def predict(self, xb, xe, sess): # tf Graph input graph = sess.graph xb",
"self.cnn_num_input]) batch_y = np.reshape(batch_y,[-1,self.num_output]) batch_tr_xe = batch_xe[:self.batch_tr_size] batch_test_xe = batch_xe[self.batch_tr_size:] batch_tr_xb = batch_xb[:self.batch_tr_size]",
"and optimizer loss_op = tf.losses.mean_squared_error(predictions = prediction ,labels = self.Y) optimizer = tf.train.AdamOptimizer(learning_rate",
"saver.restore(sess, \"./model.ckpt\") # self.run_sess(sess,xb,xe,y) def predict(self, xb, xe, sess): # tf Graph input",
"100000 self.steps_back = steps_back self.batch_size = batch_size if batch_size==1: self.test_proportion = 0 else:",
"= MinMaxScaler(feature_range=(0, 1), copy=True).fit(y.reshape(-1,1)) xe= scaler2.transform(xe) y= scaler3.transform(y.reshape(-1,1)) # graph = tf.Graph() neural_net.combined_net()",
"xe = np.reshape(xe, [-1, 1, self.fc_num_input]) p = sess.run(\"prediction:0\", feed_dict={graph.get_tensor_by_name(\"Xb:0\"): xb, graph.get_tensor_by_name(\"Xe:0\"): xe,",
"= tf.nn.conv2d(x, W, strides=[1, strides, strides, 1], padding='SAME') x = tf.nn.bias_add(x, b) return",
"batch_tr_xe, graph.get_tensor_by_name(\"Y:0\"): batch_tr_y, graph.get_tensor_by_name(\"keep_prob:0\"): 1.0}) test_l = sess.run(\"mean_squared_error_1/value:0\", feed_dict={graph.get_tensor_by_name(\"Xb_test:0\"): batch_test_xb, graph.get_tensor_by_name(\"Xe_test:0\"): batch_test_xe, graph.get_tensor_by_name(\"Y_test:0\"):",
"tf.nn.dropout(fc11_relued, self.keep_prob) def fc_net(self,xe): xe = tf.reshape(xe, shape=[-1, self.weights['wd2'].get_shape().as_list()[0]]) fc2 = tf.add(tf.matmul(xe, self.weights['wd2']),",
"training_l <= 0.01 : print(\"condition satisfied\") break if test_l < 0.009 and training_l",
"self.weights['wd1']), self.biases['bd1']) fc1_relued = tf.nn.relu(fc1) fc11 = tf.add(tf.matmul(fc1_relued, self.weights['wd11']), self.biases['bd11']) fc11_relued = tf.nn.relu(fc11)",
"tf.add(tf.matmul(fc3_sigmoided, self.weights['out2']), self.biases['out2'], name=\"prediction\") # Define loss and optimizer loss_op = tf.losses.mean_squared_error(predictions =",
"self.weights = { # 5x5 conv 'wc1': tf.Variable(tf.random_normal([2, 8, 1, 32])), # 5x5",
"saver.save(sess, name) print(\"Model saved in path: %s\" % save_path) def train(self,xb, xe, y,",
"batch_y, saver, name): graph = sess.graph batch_xe = np.reshape(batch_xe,[-1,1,self.fc_num_input]) batch_xb = np.reshape(batch_xb, [-1,",
"'out2': tf.Variable(tf.random_normal([self.num_output])) } # Create some wrappers for simplicity def conv2d(self, x, W,",
"matplotlib.pyplot as plt import pickle class NN(): def __init__(self, batch_size = 300, graph",
"optimizer.minimize(loss_op,name=\"train_op\") if self.test_proportion != 0: # Test graph conv_component_test = self.conv_net(graph.get_tensor_by_name(\"Xb_test:0\")) fc_component_test =",
"fc net with sigmoid fc3_test = tf.add(tf.matmul(fc_test, self.weights['out']), self.biases['out']) fc3_sigmoided_test = tf.nn.sigmoid(fc3_test) #",
"\" + str(step) + \", Minibatch training Loss= \" + str(training_l)) print(\"Step \"",
"# self.validation_loss.append(test_l) print(\"Optimization Finished!\") # Save the variables to disk. save_path = saver.save(sess,",
"self.weights['out']), self.biases['out']) fc3_sigmoided_test = tf.nn.sigmoid(fc3_test) # linear fc prediction_test = tf.add(tf.matmul(fc3_sigmoided_test, self.weights['out2']), self.biases['out2'],",
"connected for cnn 'wd1': tf.Variable(tf.random_normal([self.steps_back*self.cnn_num_input*64//4, 1024])), 'wd11': tf.Variable(tf.random_normal([1024, 20])), # fully connected for",
"concatenate the to components fc_test = tf.concat([conv_component_test, fc_component_test], axis=1) # another fc net",
"= tf.add(tf.matmul(fc1_relued, self.weights['wd11']), self.biases['bd11']) fc11_relued = tf.nn.relu(fc11) ## Apply Dropout return tf.nn.dropout(fc11_relued, self.keep_prob)",
"self.fc_net(graph.get_tensor_by_name(\"Xe_test:0\")) # concatenate the to components fc_test = tf.concat([conv_component_test, fc_component_test], axis=1) # another",
"filename=\"Q_data0.csv\") neural_net = NN(batch_size = 100, steps_back=8) scaler1 = {} for i in",
"# another fc net with sigmoid fc3_test = tf.add(tf.matmul(fc_test, self.weights['out']), self.biases['out']) fc3_sigmoided_test =",
"maxpool2d(self, x, k=2): # MaxPool2D wrapper return tf.nn.max_pool(x, ksize=[1, k, k, 1], strides=[1,",
"fc3_sigmoided_test = tf.nn.sigmoid(fc3_test) # linear fc prediction_test = tf.add(tf.matmul(fc3_sigmoided_test, self.weights['out2']), self.biases['out2'], name=\"prediction_test\") loss_op_test",
"ksize=[1, k, k, 1], strides=[1, k, k, 1], padding='SAME') # Create model def",
"steps_back=8, num_TCL=30): self.num_TCL = num_TCL with graph.as_default(): # Training Parameters self.learning_rate = 0.1",
"b) return tf.nn.relu(x) def maxpool2d(self, x, k=2): # MaxPool2D wrapper return tf.nn.max_pool(x, ksize=[1,",
"10 # Network Parameters self.cnn_num_input = num_TCL # MNIST data input self.fc_num_input =",
"str(test_l)) if test_l - training_l> 0.015: overfitting += 1 else: overfitting = 0",
"MinMaxScaler(feature_range=(0,1), copy=True) xb[:,i,:] = scaler1[i].fit_transform(xb[:,i,:]) scaler2 = MinMaxScaler(feature_range=(0,1), copy=True).fit(xe) scaler3 = MinMaxScaler(feature_range=(0, 1),",
"self.validation_loss.append(test_l) print(\"Optimization Finished!\") # Save the variables to disk. save_path = saver.save(sess, name)",
"conv_component_test = self.conv_net(graph.get_tensor_by_name(\"Xb_test:0\")) fc_component_test = self.fc_net(graph.get_tensor_by_name(\"Xe_test:0\")) # concatenate the to components fc_test =",
"self.num_steps = 100000 self.steps_back = steps_back self.batch_size = batch_size if batch_size==1: self.test_proportion =",
"fc11 = tf.add(tf.matmul(fc1_relued, self.weights['wd11']), self.biases['bd11']) fc11_relued = tf.nn.relu(fc11) ## Apply Dropout return tf.nn.dropout(fc11_relued,",
"= self.fc_net(graph.get_tensor_by_name(\"Xe_test:0\")) # concatenate the to components fc_test = tf.concat([conv_component_test, fc_component_test], axis=1) #",
"Test graph conv_component_test = self.conv_net(graph.get_tensor_by_name(\"Xb_test:0\")) fc_component_test = self.fc_net(graph.get_tensor_by_name(\"Xe_test:0\")) # concatenate the to components",
"feed_dict={graph.get_tensor_by_name(\"Xb_test:0\"): batch_test_xb, graph.get_tensor_by_name(\"Xe_test:0\"): batch_test_xe, graph.get_tensor_by_name(\"Y_test:0\"): batch_test_y, graph.get_tensor_by_name(\"keep_prob:0\"): 1.0}) if step % 10 ==",
"name= name) # plt.plot(range(len(self.training_loss)), self.training_loss, label='Training') # plt.plot(range(len(self.validation_loss)), self.validation_loss, label='Validation') # plt.xlabel('Steps') #",
"def __init__(self, batch_size = 300, graph = tf.get_default_graph(),test_size = 0.1, steps_back=8, num_TCL=30): self.num_TCL",
"= tf.nn.sigmoid(fc3_test) # linear fc prediction_test = tf.add(tf.matmul(fc3_sigmoided_test, self.weights['out2']), self.biases['out2'], name=\"prediction_test\") loss_op_test =",
"# plt.ylabel('Loss') # # plt.title(\"Loss function\") # # plt.legend() # # plt.show() #",
"Parameters self.cnn_num_input = num_TCL # MNIST data input self.fc_num_input = 4 self.num_output =",
"1.0}) if step % 10 == 0 or step == 1: print(\"Step \"",
"activation x = tf.nn.conv2d(x, W, strides=[1, strides, strides, 1], padding='SAME') x = tf.nn.bias_add(x,",
"graph = sess.graph batch_xe = np.reshape(batch_xe,[-1,1,self.fc_num_input]) batch_xb = np.reshape(batch_xb, [-1, self.steps_back, self.cnn_num_input]) batch_y",
"validation Loss= \" + str(test_l)) if test_l - training_l> 0.015: overfitting += 1",
"in range(xb.shape[0]//self.batch_size): # Run the initializer index = i*self.batch_size self.run_sess(sess, xb[index:index+self.batch_size],xe[index:index+self.batch_size],y[index:index+self.batch_size], saver, name=",
"tf.nn.relu(fc1) fc11 = tf.add(tf.matmul(fc1_relued, self.weights['wd11']), self.biases['bd11']) fc11_relued = tf.nn.relu(fc11) ## Apply Dropout return",
"self.num_steps + 1): # Run optimization op (backprop) sess.run(\"train_op\", feed_dict={graph.get_tensor_by_name(\"Xb:0\"): batch_tr_xb, graph.get_tensor_by_name(\"Xe:0\"): batch_tr_xe,",
"self.steps_back, self.cnn_num_input],name='Xb') self.Xe = tf.placeholder(tf.float32, [self.batch_tr_size, 1, 4], name='Xe') self.Y = tf.placeholder(tf.float32, [self.batch_tr_size,",
"Convolution Layer conv2 = self.conv2d(conv1, self.weights['wc2'], self.biases['bc2']) # Max Pooling (down-sampling) # conv2",
"fully connected layer input conv2_reshaped = tf.reshape(conv2, [-1, self.weights['wd1'].get_shape().as_list()[0]]) fc1 = tf.add(tf.matmul(conv2_reshaped, self.weights['wd1']),",
"self.validation_loss, label='Validation') # plt.xlabel('Steps') # # plt.ylabel('Loss') # # plt.title(\"Loss function\") # #",
"training_l = sess.run(\"mean_squared_error/value:0\", feed_dict={graph.get_tensor_by_name(\"Xb:0\"): batch_tr_xb, graph.get_tensor_by_name(\"Xe:0\"): batch_tr_xe, graph.get_tensor_by_name(\"Y:0\"): batch_tr_y, graph.get_tensor_by_name(\"keep_prob:0\"): 1.0}) test_l =",
"return tf.nn.max_pool(x, ksize=[1, k, k, 1], strides=[1, k, k, 1], padding='SAME') # Create",
">= 30 and training_l <= 0.01 : print(\"condition satisfied\") break if test_l <",
"self.cnn_num_input]) xe = np.reshape(xe, [-1, 1, self.fc_num_input]) p = sess.run(\"prediction:0\", feed_dict={graph.get_tensor_by_name(\"Xb:0\"): xb, graph.get_tensor_by_name(\"Xe:0\"):",
"# linear fc prediction_test = tf.add(tf.matmul(fc3_sigmoided_test, self.weights['out2']), self.biases['out2'], name=\"prediction_test\") loss_op_test = tf.losses.mean_squared_error(predictions=prediction_test, labels=self.Y_test)",
"break # self.training_loss.append(training_l) # self.validation_loss.append(test_l) print(\"Optimization Finished!\") # Save the variables to disk.",
"\" + str(training_l)) print(\"Step \" + str(step) + \", Minibatch validation Loss= \"",
"variables to disk. save_path = saver.save(sess, name) print(\"Model saved in path: %s\" %",
"fc2 = tf.add(tf.matmul(xe, self.weights['wd2']), self.biases['bd2']) return tf.nn.relu(fc2) def combined_net(self, graph = tf.get_default_graph()): with",
"as np import tensorflow as tf from read_data import get_X_y from sklearn.preprocessing import",
"if test_l < 0.009 and training_l < 0.009 : print(\"condition satisfied\") break #",
"xb[:,i,:] = scaler1[i].fit_transform(xb[:,i,:]) scaler2 = MinMaxScaler(feature_range=(0,1), copy=True).fit(xe) scaler3 = MinMaxScaler(feature_range=(0, 1), copy=True).fit(y.reshape(-1,1)) xe=",
"sess.run(\"prediction:0\", feed_dict={graph.get_tensor_by_name(\"Xb:0\"): xb, graph.get_tensor_by_name(\"Xe:0\"): xe, graph.get_tensor_by_name(\"keep_prob:0\"): 1.0}) return p if __name__ == '__main__':",
"[-1, self.steps_back, self.cnn_num_input]) xe = np.reshape(xe, [-1, 1, self.fc_num_input]) p = sess.run(\"prediction:0\", feed_dict={graph.get_tensor_by_name(\"Xb:0\"):",
"8, 32, 64])), # fully connected for cnn 'wd1': tf.Variable(tf.random_normal([self.steps_back*self.cnn_num_input*64//4, 1024])), 'wd11': tf.Variable(tf.random_normal([1024,",
"[self.batch_tr_size, 1, 4], name='Xe') self.Y = tf.placeholder(tf.float32, [self.batch_tr_size, self.num_output], name='Y') if self.test_proportion !=",
"training_l < 0.009 : print(\"condition satisfied\") break # self.training_loss.append(training_l) # self.validation_loss.append(test_l) print(\"Optimization Finished!\")",
"function\") # # plt.legend() # # plt.show() # def retrain(self,xb, xe, y,sess): #",
"= tf.concat([conv_component_test, fc_component_test], axis=1) # another fc net with sigmoid fc3_test = tf.add(tf.matmul(fc_test,",
"pickle class NN(): def __init__(self, batch_size = 300, graph = tf.get_default_graph(),test_size = 0.1,",
"sess): # tf Graph input graph = sess.graph xb = np.reshape(xb, [-1, self.steps_back,",
"in range(1, self.num_steps + 1): # Run optimization op (backprop) sess.run(\"train_op\", feed_dict={graph.get_tensor_by_name(\"Xb:0\"): batch_tr_xb,",
"# Network Parameters self.cnn_num_input = num_TCL # MNIST data input self.fc_num_input = 4",
"bias self.weights = { # 5x5 conv 'wc1': tf.Variable(tf.random_normal([2, 8, 1, 32])), #",
"= 1 # MNIST total classes (0-9 digits) self.dropout = 0.85 # Dropout,",
"# fully connected for cnn 'wd1': tf.Variable(tf.random_normal([self.steps_back*self.cnn_num_input*64//4, 1024])), 'wd11': tf.Variable(tf.random_normal([1024, 20])), # fully",
"input conv2_reshaped = tf.reshape(conv2, [-1, self.weights['wd1'].get_shape().as_list()[0]]) fc1 = tf.add(tf.matmul(conv2_reshaped, self.weights['wd1']), self.biases['bd1']) fc1_relued =",
"32, 64])), # fully connected for cnn 'wd1': tf.Variable(tf.random_normal([self.steps_back*self.cnn_num_input*64//4, 1024])), 'wd11': tf.Variable(tf.random_normal([1024, 20])),",
"## Apply Dropout return tf.nn.dropout(fc11_relued, self.keep_prob) def fc_net(self,xe): xe = tf.reshape(xe, shape=[-1, self.weights['wd2'].get_shape().as_list()[0]])",
"def conv2d(self, x, W, b, strides=1): # Conv2D wrapper, with bias and relu",
"relu activation x = tf.nn.conv2d(x, W, strides=[1, strides, strides, 1], padding='SAME') x =",
"= i*self.batch_size self.run_sess(sess, xb[index:index+self.batch_size],xe[index:index+self.batch_size],y[index:index+self.batch_size], saver, name= name) # plt.plot(range(len(self.training_loss)), self.training_loss, label='Training') # plt.plot(range(len(self.validation_loss)),",
"graph.get_tensor_by_name(\"Y:0\"): batch_tr_y, graph.get_tensor_by_name(\"keep_prob:0\"): self.dropout}) # Calculate batch loss training_l = sess.run(\"mean_squared_error/value:0\", feed_dict={graph.get_tensor_by_name(\"Xb:0\"): batch_tr_xb,",
"= \"./model0.ckpt\", graph = tf.get_default_graph() ): self.training_loss = [] self.validation_loss = [] with",
"# Dropout, probability to keep units # Placeholders self.Xb = tf.placeholder(tf.float32, [self.batch_tr_size, self.steps_back,",
"name) except: sess.run(tf.global_variables_initializer()) for i in range(xb.shape[0]//self.batch_size): # Run the initializer index =",
"graph.as_default(): # Training Parameters self.learning_rate = 0.1 self.num_steps = 100000 self.steps_back = steps_back",
"0 else: self.test_proportion = test_size self.batch_tr_size = int(self.batch_size * (1 - self.test_proportion)) self.test_size",
"x = tf.nn.bias_add(x, b) return tf.nn.relu(x) def maxpool2d(self, x, k=2): # MaxPool2D wrapper",
"axis=1) # another fc net with sigmoid fc3 = tf.add(tf.matmul(fc, self.weights['out']), self.biases['out']) fc3_sigmoided",
"< 0.009 : print(\"condition satisfied\") break # self.training_loss.append(training_l) # self.validation_loss.append(test_l) print(\"Optimization Finished!\") #",
"= self.maxpool2d(conv1, k=2) # Convolution Layer conv2 = self.conv2d(conv1, self.weights['wc2'], self.biases['bc2']) # Max",
"self.keep_prob = tf.placeholder(tf.float32, name='keep_prob') # dropout (keep probability) # display_step = 10 #",
"probability) # display_step = 10 # Network Parameters self.cnn_num_input = num_TCL # MNIST",
"optimizer = tf.train.AdamOptimizer(learning_rate = self.learning_rate) train_op = optimizer.minimize(loss_op,name=\"train_op\") if self.test_proportion != 0: #",
"i*self.batch_size self.run_sess(sess, xb[index:index+self.batch_size],xe[index:index+self.batch_size],y[index:index+self.batch_size], saver, name= name) # plt.plot(range(len(self.training_loss)), self.training_loss, label='Training') # plt.plot(range(len(self.validation_loss)), self.validation_loss,",
"self.Y) optimizer = tf.train.AdamOptimizer(learning_rate = self.learning_rate) train_op = optimizer.minimize(loss_op,name=\"train_op\") if self.test_proportion != 0:",
"= np.reshape(batch_xb, [-1, self.steps_back, self.cnn_num_input]) batch_y = np.reshape(batch_y,[-1,self.num_output]) batch_tr_xe = batch_xe[:self.batch_tr_size] batch_test_xe =",
"batch_xe, batch_y, saver, name): graph = sess.graph batch_xe = np.reshape(batch_xe,[-1,1,self.fc_num_input]) batch_xb = np.reshape(batch_xb,",
"read_data import get_X_y from sklearn.preprocessing import MinMaxScaler import matplotlib.pyplot as plt import pickle",
"= 0.1, steps_back=8, num_TCL=30): self.num_TCL = num_TCL with graph.as_default(): # Training Parameters self.learning_rate",
"predict(self, xb, xe, sess): # tf Graph input graph = sess.graph xb =",
"= tf.nn.bias_add(x, b) return tf.nn.relu(x) def maxpool2d(self, x, k=2): # MaxPool2D wrapper return",
"scaler2.transform(xe) y= scaler3.transform(y.reshape(-1,1)) # graph = tf.Graph() neural_net.combined_net() # saver = tf.train.Saver() #",
"Dropout return tf.nn.dropout(fc11_relued, self.keep_prob) def fc_net(self,xe): xe = tf.reshape(xe, shape=[-1, self.weights['wd2'].get_shape().as_list()[0]]) fc2 =",
"# Max Pooling (down-sampling) # conv2 = self.maxpool2d(conv2, k=2) # Fully connected layer",
"'bd11': tf.Variable(tf.random_normal([20])), 'bd2': tf.Variable(tf.random_normal([20])), 'out': tf.Variable(tf.random_normal([50])), 'out2': tf.Variable(tf.random_normal([self.num_output])) } # Create some wrappers",
"'out': tf.Variable(tf.random_normal([50])), 'out2': tf.Variable(tf.random_normal([self.num_output])) } # Create some wrappers for simplicity def conv2d(self,",
"components fc_test = tf.concat([conv_component_test, fc_component_test], axis=1) # another fc net with sigmoid fc3_test",
"Training Parameters self.learning_rate = 0.1 self.num_steps = 100000 self.steps_back = steps_back self.batch_size =",
"and relu activation x = tf.nn.conv2d(x, W, strides=[1, strides, strides, 1], padding='SAME') x",
"= neural_net.keep_prob # init = tf.global_variables_initializer() # graph = tf.get_default_graph() neural_net.train(xb, xe, y)",
"self.batch_size = batch_size if batch_size==1: self.test_proportion = 0 else: self.test_proportion = test_size self.batch_tr_size",
"run_sess(self, sess, batch_xb, batch_xe, batch_y, saver, name): graph = sess.graph batch_xe = np.reshape(batch_xe,[-1,1,self.fc_num_input])",
"# another fc net with sigmoid fc3 = tf.add(tf.matmul(fc, self.weights['out']), self.biases['out']) fc3_sigmoided =",
"sess.run(tf.global_variables_initializer()) for i in range(xb.shape[0]//self.batch_size): # Run the initializer index = i*self.batch_size self.run_sess(sess,",
"name) # plt.plot(range(len(self.training_loss)), self.training_loss, label='Training') # plt.plot(range(len(self.validation_loss)), self.validation_loss, label='Validation') # plt.xlabel('Steps') # #",
"batch_tr_xe, graph.get_tensor_by_name(\"Y:0\"): batch_tr_y, graph.get_tensor_by_name(\"keep_prob:0\"): self.dropout}) # Calculate batch loss training_l = sess.run(\"mean_squared_error/value:0\", feed_dict={graph.get_tensor_by_name(\"Xb:0\"):",
"input graph = sess.graph xb = np.reshape(xb, [-1, self.steps_back, self.cnn_num_input]) xe = np.reshape(xe,",
"= self.Y) optimizer = tf.train.AdamOptimizer(learning_rate = self.learning_rate) train_op = optimizer.minimize(loss_op,name=\"train_op\") if self.test_proportion !=",
"# Test graph conv_component_test = self.conv_net(graph.get_tensor_by_name(\"Xb_test:0\")) fc_component_test = self.fc_net(graph.get_tensor_by_name(\"Xe_test:0\")) # concatenate the to",
"loss and optimizer loss_op = tf.losses.mean_squared_error(predictions = prediction ,labels = self.Y) optimizer =",
"tf.losses.mean_squared_error(predictions=prediction_test, labels=self.Y_test) def run_sess(self, sess, batch_xb, batch_xe, batch_y, saver, name): graph = sess.graph",
"or step == 1: print(\"Step \" + str(step) + \", Minibatch training Loss=",
"# plt.plot(range(len(self.validation_loss)), self.validation_loss, label='Validation') # plt.xlabel('Steps') # # plt.ylabel('Loss') # # plt.title(\"Loss function\")",
"batch_test_xb, graph.get_tensor_by_name(\"Xe_test:0\"): batch_test_xe, graph.get_tensor_by_name(\"Y_test:0\"): batch_test_y, graph.get_tensor_by_name(\"keep_prob:0\"): 1.0}) if step % 10 == 0",
"labels=self.Y_test) def run_sess(self, sess, batch_xb, batch_xe, batch_y, saver, name): graph = sess.graph batch_xe",
"Placeholders self.Xb_test = tf.placeholder(tf.float32, [self.test_size, self.steps_back, self.cnn_num_input],name='Xb_test') self.Xe_test = tf.placeholder(tf.float32, [self.test_size, 1, 4],",
"fc_component = self.fc_net(self.Xe) # concatenate the to components fc = tf.concat([conv_component,fc_component], axis=1) #",
"if self.test_proportion != 0: # Test Placeholders self.Xb_test = tf.placeholder(tf.float32, [self.test_size, self.steps_back, self.cnn_num_input],name='Xb_test')",
"batch_tr_xb, graph.get_tensor_by_name(\"Xe:0\"): batch_tr_xe, graph.get_tensor_by_name(\"Y:0\"): batch_tr_y, graph.get_tensor_by_name(\"keep_prob:0\"): self.dropout}) # Calculate batch loss training_l =",
"import get_X_y from sklearn.preprocessing import MinMaxScaler import matplotlib.pyplot as plt import pickle class",
"net with sigmoid fc3_test = tf.add(tf.matmul(fc_test, self.weights['out']), self.biases['out']) fc3_sigmoided_test = tf.nn.sigmoid(fc3_test) # linear",
"NN(): def __init__(self, batch_size = 300, graph = tf.get_default_graph(),test_size = 0.1, steps_back=8, num_TCL=30):",
"# # plt.ylabel('Loss') # # plt.title(\"Loss function\") # # plt.legend() # # plt.show()",
"self.steps_back = steps_back self.batch_size = batch_size if batch_size==1: self.test_proportion = 0 else: self.test_proportion",
"= tf.train.AdamOptimizer(learning_rate = self.learning_rate) train_op = optimizer.minimize(loss_op,name=\"train_op\") if self.test_proportion != 0: # Test",
"batch_y[self.batch_tr_size:] overfitting=0 for step in range(1, self.num_steps + 1): # Run optimization op",
"fc = tf.concat([conv_component,fc_component], axis=1) # another fc net with sigmoid fc3 = tf.add(tf.matmul(fc,",
"): self.training_loss = [] self.validation_loss = [] with tf.Session(graph=graph) as sess: saver =",
"(1 - self.test_proportion)) self.test_size = int(self.test_proportion*self.batch_size) self.keep_prob = tf.placeholder(tf.float32, name='keep_prob') # dropout (keep",
"self.num_output])) } self.biases = { 'bc1': tf.Variable(tf.random_normal([32])), 'bc2': tf.Variable(tf.random_normal([64])), 'bd1': tf.Variable(tf.random_normal([1024])), 'bd11': tf.Variable(tf.random_normal([20])),",
"x, k=2): # MaxPool2D wrapper return tf.nn.max_pool(x, ksize=[1, k, k, 1], strides=[1, k,",
"= batch_xb[self.batch_tr_size:] batch_tr_y = batch_y[:self.batch_tr_size] batch_test_y = batch_y[self.batch_tr_size:] overfitting=0 for step in range(1,",
"self.biases['out']) fc3_sigmoided = tf.nn.sigmoid(fc3) #linear fc prediction = tf.add(tf.matmul(fc3_sigmoided, self.weights['out2']), self.biases['out2'], name=\"prediction\") #",
"Max Pooling (down-sampling) conv1 = self.maxpool2d(conv1, k=2) # Convolution Layer conv2 = self.conv2d(conv1,",
"self.conv_net(graph.get_tensor_by_name(\"Xb_test:0\")) fc_component_test = self.fc_net(graph.get_tensor_by_name(\"Xe_test:0\")) # concatenate the to components fc_test = tf.concat([conv_component_test, fc_component_test],",
"y= scaler3.transform(y.reshape(-1,1)) # graph = tf.Graph() neural_net.combined_net() # saver = tf.train.Saver() # keep_prob",
"self.conv2d(conv1, self.weights['wc2'], self.biases['bc2']) # Max Pooling (down-sampling) # conv2 = self.maxpool2d(conv2, k=2) #",
"layer # Reshape conv2 output to fit fully connected layer input conv2_reshaped =",
"prediction ,labels = self.Y) optimizer = tf.train.AdamOptimizer(learning_rate = self.learning_rate) train_op = optimizer.minimize(loss_op,name=\"train_op\") if",
"graph.get_tensor_by_name(\"keep_prob:0\"): 1.0}) if step % 10 == 0 or step == 1: print(\"Step",
"# Run optimization op (backprop) sess.run(\"train_op\", feed_dict={graph.get_tensor_by_name(\"Xb:0\"): batch_tr_xb, graph.get_tensor_by_name(\"Xe:0\"): batch_tr_xe, graph.get_tensor_by_name(\"Y:0\"): batch_tr_y, graph.get_tensor_by_name(\"keep_prob:0\"):",
"fc_test = tf.concat([conv_component_test, fc_component_test], axis=1) # another fc net with sigmoid fc3_test =",
"bias and relu activation x = tf.nn.conv2d(x, W, strides=[1, strides, strides, 1], padding='SAME')",
"== 1: print(\"Step \" + str(step) + \", Minibatch training Loss= \" +",
"train_op = optimizer.minimize(loss_op,name=\"train_op\") if self.test_proportion != 0: # Test graph conv_component_test = self.conv_net(graph.get_tensor_by_name(\"Xb_test:0\"))",
"strides=[1, strides, strides, 1], padding='SAME') x = tf.nn.bias_add(x, b) return tf.nn.relu(x) def maxpool2d(self,",
"neural_net = NN(batch_size = 100, steps_back=8) scaler1 = {} for i in range(xb.shape[1]):",
"self.steps_back, self.cnn_num_input]) xe = np.reshape(xe, [-1, 1, self.fc_num_input]) p = sess.run(\"prediction:0\", feed_dict={graph.get_tensor_by_name(\"Xb:0\"): xb,",
"tf.Variable(tf.random_normal([1024, 20])), # fully connected for fl_net, 'wd2': tf.Variable(tf.random_normal([4, 20])), # 1024+10 inputs,",
"Loss= \" + str(training_l)) print(\"Step \" + str(step) + \", Minibatch validation Loss=",
"import MinMaxScaler import matplotlib.pyplot as plt import pickle class NN(): def __init__(self, batch_size",
"self.learning_rate = 0.1 self.num_steps = 100000 self.steps_back = steps_back self.batch_size = batch_size if",
"'bc2': tf.Variable(tf.random_normal([64])), 'bd1': tf.Variable(tf.random_normal([1024])), 'bd11': tf.Variable(tf.random_normal([20])), 'bd2': tf.Variable(tf.random_normal([20])), 'out': tf.Variable(tf.random_normal([50])), 'out2': tf.Variable(tf.random_normal([self.num_output])) }",
"= 0 if overfitting >= 30 and training_l <= 0.01 : print(\"condition satisfied\")",
"tf.Variable(tf.random_normal([20])), 'bd2': tf.Variable(tf.random_normal([20])), 'out': tf.Variable(tf.random_normal([50])), 'out2': tf.Variable(tf.random_normal([self.num_output])) } # Create some wrappers for",
"with sigmoid fc3 = tf.add(tf.matmul(fc, self.weights['out']), self.biases['out']) fc3_sigmoided = tf.nn.sigmoid(fc3) #linear fc prediction",
"conv_component = self.conv_net(self.Xb) fc_component = self.fc_net(self.Xe) # concatenate the to components fc =",
"concatenate the to components fc = tf.concat([conv_component,fc_component], axis=1) # another fc net with",
"[] with tf.Session(graph=graph) as sess: saver = tf.train.Saver() try: saver.restore(sess, name) except: sess.run(tf.global_variables_initializer())",
"k=2) # Fully connected layer # Reshape conv2 output to fit fully connected",
"Apply Dropout return tf.nn.dropout(fc11_relued, self.keep_prob) def fc_net(self,xe): xe = tf.reshape(xe, shape=[-1, self.weights['wd2'].get_shape().as_list()[0]]) fc2",
"keep_prob = neural_net.keep_prob # init = tf.global_variables_initializer() # graph = tf.get_default_graph() neural_net.train(xb, xe,",
"= tf.nn.sigmoid(fc3) #linear fc prediction = tf.add(tf.matmul(fc3_sigmoided, self.weights['out2']), self.biases['out2'], name=\"prediction\") # Define loss",
"print(\"Model saved in path: %s\" % save_path) def train(self,xb, xe, y, name =",
"self.Xb_test = tf.placeholder(tf.float32, [self.test_size, self.steps_back, self.cnn_num_input],name='Xb_test') self.Xe_test = tf.placeholder(tf.float32, [self.test_size, 1, 4], name='Xe_test')",
"output to fit fully connected layer input conv2_reshaped = tf.reshape(conv2, [-1, self.weights['wd1'].get_shape().as_list()[0]]) fc1",
"self.test_proportion = test_size self.batch_tr_size = int(self.batch_size * (1 - self.test_proportion)) self.test_size = int(self.test_proportion*self.batch_size)",
"self.Xe_test = tf.placeholder(tf.float32, [self.test_size, 1, 4], name='Xe_test') self.Y_test = tf.placeholder(tf.float32, [self.test_size, self.num_output], name='Y_test')",
"100, steps_back=8) scaler1 = {} for i in range(xb.shape[1]): scaler1[i] = MinMaxScaler(feature_range=(0,1), copy=True)",
"overfitting >= 30 and training_l <= 0.01 : print(\"condition satisfied\") break if test_l",
"the variables to disk. save_path = saver.save(sess, name) print(\"Model saved in path: %s\"",
"tf.placeholder(tf.float32, [self.batch_tr_size, 1, 4], name='Xe') self.Y = tf.placeholder(tf.float32, [self.batch_tr_size, self.num_output], name='Y') if self.test_proportion",
"tf.placeholder(tf.float32, name='keep_prob') # dropout (keep probability) # display_step = 10 # Network Parameters",
"layers weight & bias self.weights = { # 5x5 conv 'wc1': tf.Variable(tf.random_normal([2, 8,",
"Test Placeholders self.Xb_test = tf.placeholder(tf.float32, [self.test_size, self.steps_back, self.cnn_num_input],name='Xb_test') self.Xe_test = tf.placeholder(tf.float32, [self.test_size, 1,",
"fc_component_test], axis=1) # another fc net with sigmoid fc3_test = tf.add(tf.matmul(fc_test, self.weights['out']), self.biases['out'])",
"'bd1': tf.Variable(tf.random_normal([1024])), 'bd11': tf.Variable(tf.random_normal([20])), 'bd2': tf.Variable(tf.random_normal([20])), 'out': tf.Variable(tf.random_normal([50])), 'out2': tf.Variable(tf.random_normal([self.num_output])) } # Create",
"self.learning_rate) train_op = optimizer.minimize(loss_op,name=\"train_op\") if self.test_proportion != 0: # Test graph conv_component_test =",
"save_path = saver.save(sess, name) print(\"Model saved in path: %s\" % save_path) def train(self,xb,",
"tf.losses.mean_squared_error(predictions = prediction ,labels = self.Y) optimizer = tf.train.AdamOptimizer(learning_rate = self.learning_rate) train_op =",
"batch_xb, batch_xe, batch_y, saver, name): graph = sess.graph batch_xe = np.reshape(batch_xe,[-1,1,self.fc_num_input]) batch_xb =",
"strides, 1], padding='SAME') x = tf.nn.bias_add(x, b) return tf.nn.relu(x) def maxpool2d(self, x, k=2):",
"batch_tr_xb, graph.get_tensor_by_name(\"Xe:0\"): batch_tr_xe, graph.get_tensor_by_name(\"Y:0\"): batch_tr_y, graph.get_tensor_by_name(\"keep_prob:0\"): 1.0}) test_l = sess.run(\"mean_squared_error_1/value:0\", feed_dict={graph.get_tensor_by_name(\"Xb_test:0\"): batch_test_xb, graph.get_tensor_by_name(\"Xe_test:0\"):",
"combined_net(self, graph = tf.get_default_graph()): with graph.as_default(): conv_component = self.conv_net(self.Xb) fc_component = self.fc_net(self.Xe) #",
"scaler3 = MinMaxScaler(feature_range=(0, 1), copy=True).fit(y.reshape(-1,1)) xe= scaler2.transform(xe) y= scaler3.transform(y.reshape(-1,1)) # graph = tf.Graph()",
"num_TCL with graph.as_default(): # Training Parameters self.learning_rate = 0.1 self.num_steps = 100000 self.steps_back",
"x, W, b, strides=1): # Conv2D wrapper, with bias and relu activation x",
"self.run_sess(sess,xb,xe,y) def predict(self, xb, xe, sess): # tf Graph input graph = sess.graph",
"copy=True).fit(y.reshape(-1,1)) xe= scaler2.transform(xe) y= scaler3.transform(y.reshape(-1,1)) # graph = tf.Graph() neural_net.combined_net() # saver =",
"self.test_proportion)) self.test_size = int(self.test_proportion*self.batch_size) self.keep_prob = tf.placeholder(tf.float32, name='keep_prob') # dropout (keep probability) #",
"tf.Variable(tf.random_normal([self.num_output])) } # Create some wrappers for simplicity def conv2d(self, x, W, b,",
"1, 4], name='Xe_test') self.Y_test = tf.placeholder(tf.float32, [self.test_size, self.num_output], name='Y_test') # Store layers weight",
"5x5 conv, 32 inputs, 64 outputs 'wc2': tf.Variable(tf.random_normal([2, 8, 32, 64])), # fully",
"0 or step == 1: print(\"Step \" + str(step) + \", Minibatch training",
"saver = tf.train.Saver() # keep_prob = neural_net.keep_prob # init = tf.global_variables_initializer() # graph",
"= scaler1[i].fit_transform(xb[:,i,:]) scaler2 = MinMaxScaler(feature_range=(0,1), copy=True).fit(xe) scaler3 = MinMaxScaler(feature_range=(0, 1), copy=True).fit(y.reshape(-1,1)) xe= scaler2.transform(xe)",
"class NN(): def __init__(self, batch_size = 300, graph = tf.get_default_graph(),test_size = 0.1, steps_back=8,",
"= tf.placeholder(tf.float32, [self.test_size, self.num_output], name='Y_test') # Store layers weight & bias self.weights =",
"break if test_l < 0.009 and training_l < 0.009 : print(\"condition satisfied\") break",
"fc1 = tf.add(tf.matmul(conv2_reshaped, self.weights['wd1']), self.biases['bd1']) fc1_relued = tf.nn.relu(fc1) fc11 = tf.add(tf.matmul(fc1_relued, self.weights['wd11']), self.biases['bd11'])",
"0.01 : print(\"condition satisfied\") break if test_l < 0.009 and training_l < 0.009",
"to disk. save_path = saver.save(sess, name) print(\"Model saved in path: %s\" % save_path)",
"= self.conv_net(graph.get_tensor_by_name(\"Xb_test:0\")) fc_component_test = self.fc_net(graph.get_tensor_by_name(\"Xe_test:0\")) # concatenate the to components fc_test = tf.concat([conv_component_test,",
"fully connected for cnn 'wd1': tf.Variable(tf.random_normal([self.steps_back*self.cnn_num_input*64//4, 1024])), 'wd11': tf.Variable(tf.random_normal([1024, 20])), # fully connected",
"numpy as np import tensorflow as tf from read_data import get_X_y from sklearn.preprocessing",
"1.0}) test_l = sess.run(\"mean_squared_error_1/value:0\", feed_dict={graph.get_tensor_by_name(\"Xb_test:0\"): batch_test_xb, graph.get_tensor_by_name(\"Xe_test:0\"): batch_test_xe, graph.get_tensor_by_name(\"Y_test:0\"): batch_test_y, graph.get_tensor_by_name(\"keep_prob:0\"): 1.0}) if",
"100 inputs and 1 output 'out2': tf.Variable(tf.random_normal([50, self.num_output])) } self.biases = { 'bc1':",
"= 0 else: self.test_proportion = test_size self.batch_tr_size = int(self.batch_size * (1 - self.test_proportion))",
"self.Xe = tf.placeholder(tf.float32, [self.batch_tr_size, 1, 4], name='Xe') self.Y = tf.placeholder(tf.float32, [self.batch_tr_size, self.num_output], name='Y')",
"self.Y = tf.placeholder(tf.float32, [self.batch_tr_size, self.num_output], name='Y') if self.test_proportion != 0: # Test Placeholders",
"with graph.as_default(): # Training Parameters self.learning_rate = 0.1 self.num_steps = 100000 self.steps_back =",
"MaxPool2D wrapper return tf.nn.max_pool(x, ksize=[1, k, k, 1], strides=[1, k, k, 1], padding='SAME')",
"and training_l <= 0.01 : print(\"condition satisfied\") break if test_l < 0.009 and",
"= NN(batch_size = 100, steps_back=8) scaler1 = {} for i in range(xb.shape[1]): scaler1[i]",
"self.maxpool2d(conv2, k=2) # Fully connected layer # Reshape conv2 output to fit fully",
"self.Xb = tf.placeholder(tf.float32, [self.batch_tr_size, self.steps_back, self.cnn_num_input],name='Xb') self.Xe = tf.placeholder(tf.float32, [self.batch_tr_size, 1, 4], name='Xe')",
"k, 1], padding='SAME') # Create model def conv_net(self,xb): xb = tf.reshape(xb, shape=[-1, self.steps_back,",
"to components fc = tf.concat([conv_component,fc_component], axis=1) # another fc net with sigmoid fc3",
"= tf.train.Saver() # keep_prob = neural_net.keep_prob # init = tf.global_variables_initializer() # graph =",
"i in range(xb.shape[0]//self.batch_size): # Run the initializer index = i*self.batch_size self.run_sess(sess, xb[index:index+self.batch_size],xe[index:index+self.batch_size],y[index:index+self.batch_size], saver,",
"# # plt.show() # def retrain(self,xb, xe, y,sess): # saver.restore(sess, \"./model.ckpt\") # self.run_sess(sess,xb,xe,y)",
"test_l - training_l> 0.015: overfitting += 1 else: overfitting = 0 if overfitting",
"'wd11': tf.Variable(tf.random_normal([1024, 20])), # fully connected for fl_net, 'wd2': tf.Variable(tf.random_normal([4, 20])), # 1024+10",
"self.biases['bc2']) # Max Pooling (down-sampling) # conv2 = self.maxpool2d(conv2, k=2) # Fully connected",
"if test_l - training_l> 0.015: overfitting += 1 else: overfitting = 0 if",
"= {} for i in range(xb.shape[1]): scaler1[i] = MinMaxScaler(feature_range=(0,1), copy=True) xb[:,i,:] = scaler1[i].fit_transform(xb[:,i,:])",
"'bd2': tf.Variable(tf.random_normal([20])), 'out': tf.Variable(tf.random_normal([50])), 'out2': tf.Variable(tf.random_normal([self.num_output])) } # Create some wrappers for simplicity",
"xe, y, name = \"./model0.ckpt\", graph = tf.get_default_graph() ): self.training_loss = [] self.validation_loss",
"!= 0: # Test graph conv_component_test = self.conv_net(graph.get_tensor_by_name(\"Xb_test:0\")) fc_component_test = self.fc_net(graph.get_tensor_by_name(\"Xe_test:0\")) # concatenate",
"to components fc_test = tf.concat([conv_component_test, fc_component_test], axis=1) # another fc net with sigmoid",
"tf.reshape(xb, shape=[-1, self.steps_back, self.num_TCL, 1]) # Convolution Layer conv1 = self.conv2d(xb, self.weights['wc1'],self.biases['bc1']) #",
"conv2d(self, x, W, b, strides=1): # Conv2D wrapper, with bias and relu activation",
"with sigmoid fc3_test = tf.add(tf.matmul(fc_test, self.weights['out']), self.biases['out']) fc3_sigmoided_test = tf.nn.sigmoid(fc3_test) # linear fc",
"self.fc_num_input = 4 self.num_output = 1 # MNIST total classes (0-9 digits) self.dropout",
"1, 4], name='Xe') self.Y = tf.placeholder(tf.float32, [self.batch_tr_size, self.num_output], name='Y') if self.test_proportion != 0:",
"= get_X_y(steps_back=7, filename=\"Q_data0.csv\") neural_net = NN(batch_size = 100, steps_back=8) scaler1 = {} for",
"Pooling (down-sampling) conv1 = self.maxpool2d(conv1, k=2) # Convolution Layer conv2 = self.conv2d(conv1, self.weights['wc2'],",
"= batch_xe[:self.batch_tr_size] batch_test_xe = batch_xe[self.batch_tr_size:] batch_tr_xb = batch_xb[:self.batch_tr_size] batch_test_xb = batch_xb[self.batch_tr_size:] batch_tr_y =",
"the initializer index = i*self.batch_size self.run_sess(sess, xb[index:index+self.batch_size],xe[index:index+self.batch_size],y[index:index+self.batch_size], saver, name= name) # plt.plot(range(len(self.training_loss)), self.training_loss,",
"strides=[1, k, k, 1], padding='SAME') # Create model def conv_net(self,xb): xb = tf.reshape(xb,",
"30 and training_l <= 0.01 : print(\"condition satisfied\") break if test_l < 0.009",
"tf.concat([conv_component,fc_component], axis=1) # another fc net with sigmoid fc3 = tf.add(tf.matmul(fc, self.weights['out']), self.biases['out'])",
"self.dropout = 0.85 # Dropout, probability to keep units # Placeholders self.Xb =",
"# Training Parameters self.learning_rate = 0.1 self.num_steps = 100000 self.steps_back = steps_back self.batch_size",
"= tf.reshape(conv2, [-1, self.weights['wd1'].get_shape().as_list()[0]]) fc1 = tf.add(tf.matmul(conv2_reshaped, self.weights['wd1']), self.biases['bd1']) fc1_relued = tf.nn.relu(fc1) fc11",
"0 if overfitting >= 30 and training_l <= 0.01 : print(\"condition satisfied\") break",
"[self.batch_tr_size, self.num_output], name='Y') if self.test_proportion != 0: # Test Placeholders self.Xb_test = tf.placeholder(tf.float32,",
"tf.Variable(tf.random_normal([2, 8, 1, 32])), # 5x5 conv, 32 inputs, 64 outputs 'wc2': tf.Variable(tf.random_normal([2,",
"# dropout (keep probability) # display_step = 10 # Network Parameters self.cnn_num_input =",
"conv2 = self.conv2d(conv1, self.weights['wc2'], self.biases['bc2']) # Max Pooling (down-sampling) # conv2 = self.maxpool2d(conv2,",
"conv_net(self,xb): xb = tf.reshape(xb, shape=[-1, self.steps_back, self.num_TCL, 1]) # Convolution Layer conv1 =",
"self.weights['out']), self.biases['out']) fc3_sigmoided = tf.nn.sigmoid(fc3) #linear fc prediction = tf.add(tf.matmul(fc3_sigmoided, self.weights['out2']), self.biases['out2'], name=\"prediction\")",
"print(\"Optimization Finished!\") # Save the variables to disk. save_path = saver.save(sess, name) print(\"Model",
"= 300, graph = tf.get_default_graph(),test_size = 0.1, steps_back=8, num_TCL=30): self.num_TCL = num_TCL with",
"xb[index:index+self.batch_size],xe[index:index+self.batch_size],y[index:index+self.batch_size], saver, name= name) # plt.plot(range(len(self.training_loss)), self.training_loss, label='Training') # plt.plot(range(len(self.validation_loss)), self.validation_loss, label='Validation') #",
"scaler3.transform(y.reshape(-1,1)) # graph = tf.Graph() neural_net.combined_net() # saver = tf.train.Saver() # keep_prob =",
"# plt.title(\"Loss function\") # # plt.legend() # # plt.show() # def retrain(self,xb, xe,",
"Graph input graph = sess.graph xb = np.reshape(xb, [-1, self.steps_back, self.cnn_num_input]) xe =",
"tf.add(tf.matmul(fc_test, self.weights['out']), self.biases['out']) fc3_sigmoided_test = tf.nn.sigmoid(fc3_test) # linear fc prediction_test = tf.add(tf.matmul(fc3_sigmoided_test, self.weights['out2']),",
"Dropout, probability to keep units # Placeholders self.Xb = tf.placeholder(tf.float32, [self.batch_tr_size, self.steps_back, self.cnn_num_input],name='Xb')",
"# second fuly connected layer 100 inputs and 1 output 'out2': tf.Variable(tf.random_normal([50, self.num_output]))",
"satisfied\") break # self.training_loss.append(training_l) # self.validation_loss.append(test_l) print(\"Optimization Finished!\") # Save the variables to",
"to fit fully connected layer input conv2_reshaped = tf.reshape(conv2, [-1, self.weights['wd1'].get_shape().as_list()[0]]) fc1 =",
"batch_xe = np.reshape(batch_xe,[-1,1,self.fc_num_input]) batch_xb = np.reshape(batch_xb, [-1, self.steps_back, self.cnn_num_input]) batch_y = np.reshape(batch_y,[-1,self.num_output]) batch_tr_xe",
"with graph.as_default(): conv_component = self.conv_net(self.Xb) fc_component = self.fc_net(self.Xe) # concatenate the to components",
"self.biases['out']) fc3_sigmoided_test = tf.nn.sigmoid(fc3_test) # linear fc prediction_test = tf.add(tf.matmul(fc3_sigmoided_test, self.weights['out2']), self.biases['out2'], name=\"prediction_test\")",
"self.biases['bd1']) fc1_relued = tf.nn.relu(fc1) fc11 = tf.add(tf.matmul(fc1_relued, self.weights['wd11']), self.biases['bd11']) fc11_relued = tf.nn.relu(fc11) ##",
"training_l> 0.015: overfitting += 1 else: overfitting = 0 if overfitting >= 30",
"input self.fc_num_input = 4 self.num_output = 1 # MNIST total classes (0-9 digits)",
"# Conv2D wrapper, with bias and relu activation x = tf.nn.conv2d(x, W, strides=[1,",
"outputs 'wc2': tf.Variable(tf.random_normal([2, 8, 32, 64])), # fully connected for cnn 'wd1': tf.Variable(tf.random_normal([self.steps_back*self.cnn_num_input*64//4,",
"= batch_size if batch_size==1: self.test_proportion = 0 else: self.test_proportion = test_size self.batch_tr_size =",
"name=\"prediction\") # Define loss and optimizer loss_op = tf.losses.mean_squared_error(predictions = prediction ,labels =",
"= MinMaxScaler(feature_range=(0,1), copy=True) xb[:,i,:] = scaler1[i].fit_transform(xb[:,i,:]) scaler2 = MinMaxScaler(feature_range=(0,1), copy=True).fit(xe) scaler3 = MinMaxScaler(feature_range=(0,",
"# conv2 = self.maxpool2d(conv2, k=2) # Fully connected layer # Reshape conv2 output",
"Fully connected layer # Reshape conv2 output to fit fully connected layer input",
"batch_size = 300, graph = tf.get_default_graph(),test_size = 0.1, steps_back=8, num_TCL=30): self.num_TCL = num_TCL",
"'out': tf.Variable(tf.random_normal([20+20, 50])), # second fuly connected layer 100 inputs and 1 output",
"self.weights['wc2'], self.biases['bc2']) # Max Pooling (down-sampling) # conv2 = self.maxpool2d(conv2, k=2) # Fully",
"self.batch_tr_size = int(self.batch_size * (1 - self.test_proportion)) self.test_size = int(self.test_proportion*self.batch_size) self.keep_prob = tf.placeholder(tf.float32,",
"sigmoid fc3 = tf.add(tf.matmul(fc, self.weights['out']), self.biases['out']) fc3_sigmoided = tf.nn.sigmoid(fc3) #linear fc prediction =",
"\" + str(step) + \", Minibatch validation Loss= \" + str(test_l)) if test_l",
"1 else: overfitting = 0 if overfitting >= 30 and training_l <= 0.01",
"= [] with tf.Session(graph=graph) as sess: saver = tf.train.Saver() try: saver.restore(sess, name) except:",
"{} for i in range(xb.shape[1]): scaler1[i] = MinMaxScaler(feature_range=(0,1), copy=True) xb[:,i,:] = scaler1[i].fit_transform(xb[:,i,:]) scaler2",
"self.weights['wd1'].get_shape().as_list()[0]]) fc1 = tf.add(tf.matmul(conv2_reshaped, self.weights['wd1']), self.biases['bd1']) fc1_relued = tf.nn.relu(fc1) fc11 = tf.add(tf.matmul(fc1_relued, self.weights['wd11']),",
"Run the initializer index = i*self.batch_size self.run_sess(sess, xb[index:index+self.batch_size],xe[index:index+self.batch_size],y[index:index+self.batch_size], saver, name= name) # plt.plot(range(len(self.training_loss)),",
"= MinMaxScaler(feature_range=(0,1), copy=True).fit(xe) scaler3 = MinMaxScaler(feature_range=(0, 1), copy=True).fit(y.reshape(-1,1)) xe= scaler2.transform(xe) y= scaler3.transform(y.reshape(-1,1)) #",
"as plt import pickle class NN(): def __init__(self, batch_size = 300, graph =",
"batch_xb[:self.batch_tr_size] batch_test_xb = batch_xb[self.batch_tr_size:] batch_tr_y = batch_y[:self.batch_tr_size] batch_test_y = batch_y[self.batch_tr_size:] overfitting=0 for step",
"tf.nn.relu(fc11) ## Apply Dropout return tf.nn.dropout(fc11_relued, self.keep_prob) def fc_net(self,xe): xe = tf.reshape(xe, shape=[-1,",
"== 0 or step == 1: print(\"Step \" + str(step) + \", Minibatch",
"shape=[-1, self.steps_back, self.num_TCL, 1]) # Convolution Layer conv1 = self.conv2d(xb, self.weights['wc1'],self.biases['bc1']) # Max",
"} # Create some wrappers for simplicity def conv2d(self, x, W, b, strides=1):",
"= tf.get_default_graph()): with graph.as_default(): conv_component = self.conv_net(self.Xb) fc_component = self.fc_net(self.Xe) # concatenate the",
"\", Minibatch training Loss= \" + str(training_l)) print(\"Step \" + str(step) + \",",
"(down-sampling) conv1 = self.maxpool2d(conv1, k=2) # Convolution Layer conv2 = self.conv2d(conv1, self.weights['wc2'], self.biases['bc2'])",
"W, strides=[1, strides, strides, 1], padding='SAME') x = tf.nn.bias_add(x, b) return tf.nn.relu(x) def",
"# concatenate the to components fc_test = tf.concat([conv_component_test, fc_component_test], axis=1) # another fc",
"batch_test_y, graph.get_tensor_by_name(\"keep_prob:0\"): 1.0}) if step % 10 == 0 or step == 1:",
"tf.Variable(tf.random_normal([20])), 'out': tf.Variable(tf.random_normal([50])), 'out2': tf.Variable(tf.random_normal([self.num_output])) } # Create some wrappers for simplicity def",
"if batch_size==1: self.test_proportion = 0 else: self.test_proportion = test_size self.batch_tr_size = int(self.batch_size *",
"i in range(xb.shape[1]): scaler1[i] = MinMaxScaler(feature_range=(0,1), copy=True) xb[:,i,:] = scaler1[i].fit_transform(xb[:,i,:]) scaler2 = MinMaxScaler(feature_range=(0,1),",
"saved in path: %s\" % save_path) def train(self,xb, xe, y, name = \"./model0.ckpt\",",
"batch_test_xb = batch_xb[self.batch_tr_size:] batch_tr_y = batch_y[:self.batch_tr_size] batch_test_y = batch_y[self.batch_tr_size:] overfitting=0 for step in",
"batch_y[:self.batch_tr_size] batch_test_y = batch_y[self.batch_tr_size:] overfitting=0 for step in range(1, self.num_steps + 1): #",
"b, strides=1): # Conv2D wrapper, with bias and relu activation x = tf.nn.conv2d(x,",
"# Fully connected layer # Reshape conv2 output to fit fully connected layer",
"tf.Variable(tf.random_normal([32])), 'bc2': tf.Variable(tf.random_normal([64])), 'bd1': tf.Variable(tf.random_normal([1024])), 'bd11': tf.Variable(tf.random_normal([20])), 'bd2': tf.Variable(tf.random_normal([20])), 'out': tf.Variable(tf.random_normal([50])), 'out2': tf.Variable(tf.random_normal([self.num_output]))",
"another fc net with sigmoid fc3 = tf.add(tf.matmul(fc, self.weights['out']), self.biases['out']) fc3_sigmoided = tf.nn.sigmoid(fc3)",
"else: overfitting = 0 if overfitting >= 30 and training_l <= 0.01 :",
"self.dropout}) # Calculate batch loss training_l = sess.run(\"mean_squared_error/value:0\", feed_dict={graph.get_tensor_by_name(\"Xb:0\"): batch_tr_xb, graph.get_tensor_by_name(\"Xe:0\"): batch_tr_xe, graph.get_tensor_by_name(\"Y:0\"):",
"# plt.plot(range(len(self.training_loss)), self.training_loss, label='Training') # plt.plot(range(len(self.validation_loss)), self.validation_loss, label='Validation') # plt.xlabel('Steps') # # plt.ylabel('Loss')",
"wrapper return tf.nn.max_pool(x, ksize=[1, k, k, 1], strides=[1, k, k, 1], padding='SAME') #",
"strides=1): # Conv2D wrapper, with bias and relu activation x = tf.nn.conv2d(x, W,",
"for i in range(xb.shape[0]//self.batch_size): # Run the initializer index = i*self.batch_size self.run_sess(sess, xb[index:index+self.batch_size],xe[index:index+self.batch_size],y[index:index+self.batch_size],",
"fc3_test = tf.add(tf.matmul(fc_test, self.weights['out']), self.biases['out']) fc3_sigmoided_test = tf.nn.sigmoid(fc3_test) # linear fc prediction_test =",
"== '__main__': xb, xe, y = get_X_y(steps_back=7, filename=\"Q_data0.csv\") neural_net = NN(batch_size = 100,",
"tf.nn.conv2d(x, W, strides=[1, strides, strides, 1], padding='SAME') x = tf.nn.bias_add(x, b) return tf.nn.relu(x)",
"print(\"Step \" + str(step) + \", Minibatch validation Loss= \" + str(test_l)) if",
"batch_tr_y, graph.get_tensor_by_name(\"keep_prob:0\"): 1.0}) test_l = sess.run(\"mean_squared_error_1/value:0\", feed_dict={graph.get_tensor_by_name(\"Xb_test:0\"): batch_test_xb, graph.get_tensor_by_name(\"Xe_test:0\"): batch_test_xe, graph.get_tensor_by_name(\"Y_test:0\"): batch_test_y, graph.get_tensor_by_name(\"keep_prob:0\"):",
"except: sess.run(tf.global_variables_initializer()) for i in range(xb.shape[0]//self.batch_size): # Run the initializer index = i*self.batch_size",
"self.run_sess(sess, xb[index:index+self.batch_size],xe[index:index+self.batch_size],y[index:index+self.batch_size], saver, name= name) # plt.plot(range(len(self.training_loss)), self.training_loss, label='Training') # plt.plot(range(len(self.validation_loss)), self.validation_loss, label='Validation')",
"[self.test_size, self.num_output], name='Y_test') # Store layers weight & bias self.weights = { #",
"= 100000 self.steps_back = steps_back self.batch_size = batch_size if batch_size==1: self.test_proportion = 0",
"graph = tf.get_default_graph() ): self.training_loss = [] self.validation_loss = [] with tf.Session(graph=graph) as",
"np.reshape(xe, [-1, 1, self.fc_num_input]) p = sess.run(\"prediction:0\", feed_dict={graph.get_tensor_by_name(\"Xb:0\"): xb, graph.get_tensor_by_name(\"Xe:0\"): xe, graph.get_tensor_by_name(\"keep_prob:0\"): 1.0})",
"# 5x5 conv, 32 inputs, 64 outputs 'wc2': tf.Variable(tf.random_normal([2, 8, 32, 64])), #",
"Reshape conv2 output to fit fully connected layer input conv2_reshaped = tf.reshape(conv2, [-1,",
"0: # Test graph conv_component_test = self.conv_net(graph.get_tensor_by_name(\"Xb_test:0\")) fc_component_test = self.fc_net(graph.get_tensor_by_name(\"Xe_test:0\")) # concatenate the",
"connected for fl_net, 'wd2': tf.Variable(tf.random_normal([4, 20])), # 1024+10 inputs, 1 output (class prediction)",
"padding='SAME') # Create model def conv_net(self,xb): xb = tf.reshape(xb, shape=[-1, self.steps_back, self.num_TCL, 1])",
"= self.maxpool2d(conv2, k=2) # Fully connected layer # Reshape conv2 output to fit",
"sess, batch_xb, batch_xe, batch_y, saver, name): graph = sess.graph batch_xe = np.reshape(batch_xe,[-1,1,self.fc_num_input]) batch_xb",
"keep units # Placeholders self.Xb = tf.placeholder(tf.float32, [self.batch_tr_size, self.steps_back, self.cnn_num_input],name='Xb') self.Xe = tf.placeholder(tf.float32,",
"[self.test_size, 1, 4], name='Xe_test') self.Y_test = tf.placeholder(tf.float32, [self.test_size, self.num_output], name='Y_test') # Store layers",
"# tf Graph input graph = sess.graph xb = np.reshape(xb, [-1, self.steps_back, self.cnn_num_input])",
"Run optimization op (backprop) sess.run(\"train_op\", feed_dict={graph.get_tensor_by_name(\"Xb:0\"): batch_tr_xb, graph.get_tensor_by_name(\"Xe:0\"): batch_tr_xe, graph.get_tensor_by_name(\"Y:0\"): batch_tr_y, graph.get_tensor_by_name(\"keep_prob:0\"): self.dropout})",
"# display_step = 10 # Network Parameters self.cnn_num_input = num_TCL # MNIST data",
"= tf.add(tf.matmul(fc_test, self.weights['out']), self.biases['out']) fc3_sigmoided_test = tf.nn.sigmoid(fc3_test) # linear fc prediction_test = tf.add(tf.matmul(fc3_sigmoided_test,",
"graph.get_tensor_by_name(\"Y:0\"): batch_tr_y, graph.get_tensor_by_name(\"keep_prob:0\"): 1.0}) test_l = sess.run(\"mean_squared_error_1/value:0\", feed_dict={graph.get_tensor_by_name(\"Xb_test:0\"): batch_test_xb, graph.get_tensor_by_name(\"Xe_test:0\"): batch_test_xe, graph.get_tensor_by_name(\"Y_test:0\"): batch_test_y,",
"saver, name= name) # plt.plot(range(len(self.training_loss)), self.training_loss, label='Training') # plt.plot(range(len(self.validation_loss)), self.validation_loss, label='Validation') # plt.xlabel('Steps')",
"label='Training') # plt.plot(range(len(self.validation_loss)), self.validation_loss, label='Validation') # plt.xlabel('Steps') # # plt.ylabel('Loss') # # plt.title(\"Loss",
"__name__ == '__main__': xb, xe, y = get_X_y(steps_back=7, filename=\"Q_data0.csv\") neural_net = NN(batch_size =",
"with bias and relu activation x = tf.nn.conv2d(x, W, strides=[1, strides, strides, 1],",
"step in range(1, self.num_steps + 1): # Run optimization op (backprop) sess.run(\"train_op\", feed_dict={graph.get_tensor_by_name(\"Xb:0\"):",
"return tf.nn.relu(x) def maxpool2d(self, x, k=2): # MaxPool2D wrapper return tf.nn.max_pool(x, ksize=[1, k,",
"(down-sampling) # conv2 = self.maxpool2d(conv2, k=2) # Fully connected layer # Reshape conv2",
"shape=[-1, self.weights['wd2'].get_shape().as_list()[0]]) fc2 = tf.add(tf.matmul(xe, self.weights['wd2']), self.biases['bd2']) return tf.nn.relu(fc2) def combined_net(self, graph =",
"# Run the initializer index = i*self.batch_size self.run_sess(sess, xb[index:index+self.batch_size],xe[index:index+self.batch_size],y[index:index+self.batch_size], saver, name= name) #",
"graph.get_tensor_by_name(\"Xe:0\"): batch_tr_xe, graph.get_tensor_by_name(\"Y:0\"): batch_tr_y, graph.get_tensor_by_name(\"keep_prob:0\"): self.dropout}) # Calculate batch loss training_l = sess.run(\"mean_squared_error/value:0\",",
"fully connected for fl_net, 'wd2': tf.Variable(tf.random_normal([4, 20])), # 1024+10 inputs, 1 output (class",
"1 output (class prediction) 'out': tf.Variable(tf.random_normal([20+20, 50])), # second fuly connected layer 100",
"index = i*self.batch_size self.run_sess(sess, xb[index:index+self.batch_size],xe[index:index+self.batch_size],y[index:index+self.batch_size], saver, name= name) # plt.plot(range(len(self.training_loss)), self.training_loss, label='Training') #",
"1 # MNIST total classes (0-9 digits) self.dropout = 0.85 # Dropout, probability",
"self.weights['wc1'],self.biases['bc1']) # Max Pooling (down-sampling) conv1 = self.maxpool2d(conv1, k=2) # Convolution Layer conv2",
"'out2': tf.Variable(tf.random_normal([50, self.num_output])) } self.biases = { 'bc1': tf.Variable(tf.random_normal([32])), 'bc2': tf.Variable(tf.random_normal([64])), 'bd1': tf.Variable(tf.random_normal([1024])),",
"# Save the variables to disk. save_path = saver.save(sess, name) print(\"Model saved in",
"save_path) def train(self,xb, xe, y, name = \"./model0.ckpt\", graph = tf.get_default_graph() ): self.training_loss",
"graph.get_tensor_by_name(\"Y_test:0\"): batch_test_y, graph.get_tensor_by_name(\"keep_prob:0\"): 1.0}) if step % 10 == 0 or step ==",
"path: %s\" % save_path) def train(self,xb, xe, y, name = \"./model0.ckpt\", graph =",
"k, k, 1], padding='SAME') # Create model def conv_net(self,xb): xb = tf.reshape(xb, shape=[-1,",
"tf.Variable(tf.random_normal([1024])), 'bd11': tf.Variable(tf.random_normal([20])), 'bd2': tf.Variable(tf.random_normal([20])), 'out': tf.Variable(tf.random_normal([50])), 'out2': tf.Variable(tf.random_normal([self.num_output])) } # Create some",
"4 self.num_output = 1 # MNIST total classes (0-9 digits) self.dropout = 0.85",
"self.biases['bd11']) fc11_relued = tf.nn.relu(fc11) ## Apply Dropout return tf.nn.dropout(fc11_relued, self.keep_prob) def fc_net(self,xe): xe",
"1], strides=[1, k, k, 1], padding='SAME') # Create model def conv_net(self,xb): xb =",
"%s\" % save_path) def train(self,xb, xe, y, name = \"./model0.ckpt\", graph = tf.get_default_graph()",
"< 0.009 and training_l < 0.009 : print(\"condition satisfied\") break # self.training_loss.append(training_l) #",
"np import tensorflow as tf from read_data import get_X_y from sklearn.preprocessing import MinMaxScaler",
"loss_op = tf.losses.mean_squared_error(predictions = prediction ,labels = self.Y) optimizer = tf.train.AdamOptimizer(learning_rate = self.learning_rate)",
"self.biases = { 'bc1': tf.Variable(tf.random_normal([32])), 'bc2': tf.Variable(tf.random_normal([64])), 'bd1': tf.Variable(tf.random_normal([1024])), 'bd11': tf.Variable(tf.random_normal([20])), 'bd2': tf.Variable(tf.random_normal([20])),",
"# MNIST data input self.fc_num_input = 4 self.num_output = 1 # MNIST total",
"Layer conv2 = self.conv2d(conv1, self.weights['wc2'], self.biases['bc2']) # Max Pooling (down-sampling) # conv2 =",
"= test_size self.batch_tr_size = int(self.batch_size * (1 - self.test_proportion)) self.test_size = int(self.test_proportion*self.batch_size) self.keep_prob",
"name='Xe_test') self.Y_test = tf.placeholder(tf.float32, [self.test_size, self.num_output], name='Y_test') # Store layers weight & bias",
"# Placeholders self.Xb = tf.placeholder(tf.float32, [self.batch_tr_size, self.steps_back, self.cnn_num_input],name='Xb') self.Xe = tf.placeholder(tf.float32, [self.batch_tr_size, 1,",
"% save_path) def train(self,xb, xe, y, name = \"./model0.ckpt\", graph = tf.get_default_graph() ):",
"simplicity def conv2d(self, x, W, b, strides=1): # Conv2D wrapper, with bias and",
"Pooling (down-sampling) # conv2 = self.maxpool2d(conv2, k=2) # Fully connected layer # Reshape",
"4], name='Xe_test') self.Y_test = tf.placeholder(tf.float32, [self.test_size, self.num_output], name='Y_test') # Store layers weight &",
"name=\"prediction_test\") loss_op_test = tf.losses.mean_squared_error(predictions=prediction_test, labels=self.Y_test) def run_sess(self, sess, batch_xb, batch_xe, batch_y, saver, name):",
"self.test_size = int(self.test_proportion*self.batch_size) self.keep_prob = tf.placeholder(tf.float32, name='keep_prob') # dropout (keep probability) # display_step",
"optimization op (backprop) sess.run(\"train_op\", feed_dict={graph.get_tensor_by_name(\"Xb:0\"): batch_tr_xb, graph.get_tensor_by_name(\"Xe:0\"): batch_tr_xe, graph.get_tensor_by_name(\"Y:0\"): batch_tr_y, graph.get_tensor_by_name(\"keep_prob:0\"): self.dropout}) #",
"self.biases['out2'], name=\"prediction_test\") loss_op_test = tf.losses.mean_squared_error(predictions=prediction_test, labels=self.Y_test) def run_sess(self, sess, batch_xb, batch_xe, batch_y, saver,",
"strides, strides, 1], padding='SAME') x = tf.nn.bias_add(x, b) return tf.nn.relu(x) def maxpool2d(self, x,",
"tf.add(tf.matmul(conv2_reshaped, self.weights['wd1']), self.biases['bd1']) fc1_relued = tf.nn.relu(fc1) fc11 = tf.add(tf.matmul(fc1_relued, self.weights['wd11']), self.biases['bd11']) fc11_relued =",
"net with sigmoid fc3 = tf.add(tf.matmul(fc, self.weights['out']), self.biases['out']) fc3_sigmoided = tf.nn.sigmoid(fc3) #linear fc",
"self.training_loss, label='Training') # plt.plot(range(len(self.validation_loss)), self.validation_loss, label='Validation') # plt.xlabel('Steps') # # plt.ylabel('Loss') # #",
"= 10 # Network Parameters self.cnn_num_input = num_TCL # MNIST data input self.fc_num_input",
"batch_xe[:self.batch_tr_size] batch_test_xe = batch_xe[self.batch_tr_size:] batch_tr_xb = batch_xb[:self.batch_tr_size] batch_test_xb = batch_xb[self.batch_tr_size:] batch_tr_y = batch_y[:self.batch_tr_size]",
"for i in range(xb.shape[1]): scaler1[i] = MinMaxScaler(feature_range=(0,1), copy=True) xb[:,i,:] = scaler1[i].fit_transform(xb[:,i,:]) scaler2 =",
"Create model def conv_net(self,xb): xb = tf.reshape(xb, shape=[-1, self.steps_back, self.num_TCL, 1]) # Convolution",
"1.0}) return p if __name__ == '__main__': xb, xe, y = get_X_y(steps_back=7, filename=\"Q_data0.csv\")",
"range(xb.shape[1]): scaler1[i] = MinMaxScaler(feature_range=(0,1), copy=True) xb[:,i,:] = scaler1[i].fit_transform(xb[:,i,:]) scaler2 = MinMaxScaler(feature_range=(0,1), copy=True).fit(xe) scaler3",
"= tf.get_default_graph(),test_size = 0.1, steps_back=8, num_TCL=30): self.num_TCL = num_TCL with graph.as_default(): # Training",
"name='Xe') self.Y = tf.placeholder(tf.float32, [self.batch_tr_size, self.num_output], name='Y') if self.test_proportion != 0: # Test",
"= tf.nn.relu(fc1) fc11 = tf.add(tf.matmul(fc1_relued, self.weights['wd11']), self.biases['bd11']) fc11_relued = tf.nn.relu(fc11) ## Apply Dropout",
"Store layers weight & bias self.weights = { # 5x5 conv 'wc1': tf.Variable(tf.random_normal([2,",
"plt.xlabel('Steps') # # plt.ylabel('Loss') # # plt.title(\"Loss function\") # # plt.legend() # #",
"1], padding='SAME') x = tf.nn.bias_add(x, b) return tf.nn.relu(x) def maxpool2d(self, x, k=2): #",
"+ str(test_l)) if test_l - training_l> 0.015: overfitting += 1 else: overfitting =",
"label='Validation') # plt.xlabel('Steps') # # plt.ylabel('Loss') # # plt.title(\"Loss function\") # # plt.legend()",
"np.reshape(batch_xe,[-1,1,self.fc_num_input]) batch_xb = np.reshape(batch_xb, [-1, self.steps_back, self.cnn_num_input]) batch_y = np.reshape(batch_y,[-1,self.num_output]) batch_tr_xe = batch_xe[:self.batch_tr_size]",
"= np.reshape(batch_y,[-1,self.num_output]) batch_tr_xe = batch_xe[:self.batch_tr_size] batch_test_xe = batch_xe[self.batch_tr_size:] batch_tr_xb = batch_xb[:self.batch_tr_size] batch_test_xb =",
"loss training_l = sess.run(\"mean_squared_error/value:0\", feed_dict={graph.get_tensor_by_name(\"Xb:0\"): batch_tr_xb, graph.get_tensor_by_name(\"Xe:0\"): batch_tr_xe, graph.get_tensor_by_name(\"Y:0\"): batch_tr_y, graph.get_tensor_by_name(\"keep_prob:0\"): 1.0}) test_l",
"str(step) + \", Minibatch validation Loss= \" + str(test_l)) if test_l - training_l>",
"[] self.validation_loss = [] with tf.Session(graph=graph) as sess: saver = tf.train.Saver() try: saver.restore(sess,",
"tf.add(tf.matmul(xe, self.weights['wd2']), self.biases['bd2']) return tf.nn.relu(fc2) def combined_net(self, graph = tf.get_default_graph()): with graph.as_default(): conv_component",
"self.maxpool2d(conv1, k=2) # Convolution Layer conv2 = self.conv2d(conv1, self.weights['wc2'], self.biases['bc2']) # Max Pooling",
"conv2_reshaped = tf.reshape(conv2, [-1, self.weights['wd1'].get_shape().as_list()[0]]) fc1 = tf.add(tf.matmul(conv2_reshaped, self.weights['wd1']), self.biases['bd1']) fc1_relued = tf.nn.relu(fc1)",
"wrappers for simplicity def conv2d(self, x, W, b, strides=1): # Conv2D wrapper, with",
"= tf.placeholder(tf.float32, [self.batch_tr_size, 1, 4], name='Xe') self.Y = tf.placeholder(tf.float32, [self.batch_tr_size, self.num_output], name='Y') if",
"xb, xe, y = get_X_y(steps_back=7, filename=\"Q_data0.csv\") neural_net = NN(batch_size = 100, steps_back=8) scaler1",
"copy=True).fit(xe) scaler3 = MinMaxScaler(feature_range=(0, 1), copy=True).fit(y.reshape(-1,1)) xe= scaler2.transform(xe) y= scaler3.transform(y.reshape(-1,1)) # graph =",
"[self.test_size, self.steps_back, self.cnn_num_input],name='Xb_test') self.Xe_test = tf.placeholder(tf.float32, [self.test_size, 1, 4], name='Xe_test') self.Y_test = tf.placeholder(tf.float32,",
"1 output 'out2': tf.Variable(tf.random_normal([50, self.num_output])) } self.biases = { 'bc1': tf.Variable(tf.random_normal([32])), 'bc2': tf.Variable(tf.random_normal([64])),",
"# concatenate the to components fc = tf.concat([conv_component,fc_component], axis=1) # another fc net",
"display_step = 10 # Network Parameters self.cnn_num_input = num_TCL # MNIST data input",
"try: saver.restore(sess, name) except: sess.run(tf.global_variables_initializer()) for i in range(xb.shape[0]//self.batch_size): # Run the initializer",
"retrain(self,xb, xe, y,sess): # saver.restore(sess, \"./model.ckpt\") # self.run_sess(sess,xb,xe,y) def predict(self, xb, xe, sess):",
"(class prediction) 'out': tf.Variable(tf.random_normal([20+20, 50])), # second fuly connected layer 100 inputs and",
"Save the variables to disk. save_path = saver.save(sess, name) print(\"Model saved in path:",
"classes (0-9 digits) self.dropout = 0.85 # Dropout, probability to keep units #",
"layer 100 inputs and 1 output 'out2': tf.Variable(tf.random_normal([50, self.num_output])) } self.biases = {",
"0.009 and training_l < 0.009 : print(\"condition satisfied\") break # self.training_loss.append(training_l) # self.validation_loss.append(test_l)",
"= tf.losses.mean_squared_error(predictions=prediction_test, labels=self.Y_test) def run_sess(self, sess, batch_xb, batch_xe, batch_y, saver, name): graph =",
"self.validation_loss = [] with tf.Session(graph=graph) as sess: saver = tf.train.Saver() try: saver.restore(sess, name)",
"sklearn.preprocessing import MinMaxScaler import matplotlib.pyplot as plt import pickle class NN(): def __init__(self,",
"self.keep_prob) def fc_net(self,xe): xe = tf.reshape(xe, shape=[-1, self.weights['wd2'].get_shape().as_list()[0]]) fc2 = tf.add(tf.matmul(xe, self.weights['wd2']), self.biases['bd2'])",
"overfitting += 1 else: overfitting = 0 if overfitting >= 30 and training_l",
"conv2 output to fit fully connected layer input conv2_reshaped = tf.reshape(conv2, [-1, self.weights['wd1'].get_shape().as_list()[0]])",
"fc3_sigmoided = tf.nn.sigmoid(fc3) #linear fc prediction = tf.add(tf.matmul(fc3_sigmoided, self.weights['out2']), self.biases['out2'], name=\"prediction\") # Define",
"self.biases['out2'], name=\"prediction\") # Define loss and optimizer loss_op = tf.losses.mean_squared_error(predictions = prediction ,labels",
"y, name = \"./model0.ckpt\", graph = tf.get_default_graph() ): self.training_loss = [] self.validation_loss =",
"batch_test_y = batch_y[self.batch_tr_size:] overfitting=0 for step in range(1, self.num_steps + 1): # Run",
"def conv_net(self,xb): xb = tf.reshape(xb, shape=[-1, self.steps_back, self.num_TCL, 1]) # Convolution Layer conv1",
"dropout (keep probability) # display_step = 10 # Network Parameters self.cnn_num_input = num_TCL",
"inputs, 64 outputs 'wc2': tf.Variable(tf.random_normal([2, 8, 32, 64])), # fully connected for cnn",
"fc_net(self,xe): xe = tf.reshape(xe, shape=[-1, self.weights['wd2'].get_shape().as_list()[0]]) fc2 = tf.add(tf.matmul(xe, self.weights['wd2']), self.biases['bd2']) return tf.nn.relu(fc2)",
"sess.graph xb = np.reshape(xb, [-1, self.steps_back, self.cnn_num_input]) xe = np.reshape(xe, [-1, 1, self.fc_num_input])",
"padding='SAME') x = tf.nn.bias_add(x, b) return tf.nn.relu(x) def maxpool2d(self, x, k=2): # MaxPool2D",
"# Create some wrappers for simplicity def conv2d(self, x, W, b, strides=1): #",
"batch_tr_xb = batch_xb[:self.batch_tr_size] batch_test_xb = batch_xb[self.batch_tr_size:] batch_tr_y = batch_y[:self.batch_tr_size] batch_test_y = batch_y[self.batch_tr_size:] overfitting=0",
"# 5x5 conv 'wc1': tf.Variable(tf.random_normal([2, 8, 1, 32])), # 5x5 conv, 32 inputs,",
"step % 10 == 0 or step == 1: print(\"Step \" + str(step)",
"name='Y_test') # Store layers weight & bias self.weights = { # 5x5 conv",
"% 10 == 0 or step == 1: print(\"Step \" + str(step) +",
"disk. save_path = saver.save(sess, name) print(\"Model saved in path: %s\" % save_path) def",
"= tf.train.Saver() try: saver.restore(sess, name) except: sess.run(tf.global_variables_initializer()) for i in range(xb.shape[0]//self.batch_size): # Run",
"graph.get_tensor_by_name(\"keep_prob:0\"): self.dropout}) # Calculate batch loss training_l = sess.run(\"mean_squared_error/value:0\", feed_dict={graph.get_tensor_by_name(\"Xb:0\"): batch_tr_xb, graph.get_tensor_by_name(\"Xe:0\"): batch_tr_xe,",
"plt import pickle class NN(): def __init__(self, batch_size = 300, graph = tf.get_default_graph(),test_size",
"x = tf.nn.conv2d(x, W, strides=[1, strides, strides, 1], padding='SAME') x = tf.nn.bias_add(x, b)",
"batch_xb[self.batch_tr_size:] batch_tr_y = batch_y[:self.batch_tr_size] batch_test_y = batch_y[self.batch_tr_size:] overfitting=0 for step in range(1, self.num_steps",
"tf.get_default_graph() ): self.training_loss = [] self.validation_loss = [] with tf.Session(graph=graph) as sess: saver",
"= { # 5x5 conv 'wc1': tf.Variable(tf.random_normal([2, 8, 1, 32])), # 5x5 conv,",
"[-1, self.weights['wd1'].get_shape().as_list()[0]]) fc1 = tf.add(tf.matmul(conv2_reshaped, self.weights['wd1']), self.biases['bd1']) fc1_relued = tf.nn.relu(fc1) fc11 = tf.add(tf.matmul(fc1_relued,",
"saver = tf.train.Saver() try: saver.restore(sess, name) except: sess.run(tf.global_variables_initializer()) for i in range(xb.shape[0]//self.batch_size): #",
"for step in range(1, self.num_steps + 1): # Run optimization op (backprop) sess.run(\"train_op\",",
"prediction = tf.add(tf.matmul(fc3_sigmoided, self.weights['out2']), self.biases['out2'], name=\"prediction\") # Define loss and optimizer loss_op =",
"10 == 0 or step == 1: print(\"Step \" + str(step) + \",",
": print(\"condition satisfied\") break if test_l < 0.009 and training_l < 0.009 :",
"# plt.xlabel('Steps') # # plt.ylabel('Loss') # # plt.title(\"Loss function\") # # plt.legend() #",
"1024])), 'wd11': tf.Variable(tf.random_normal([1024, 20])), # fully connected for fl_net, 'wd2': tf.Variable(tf.random_normal([4, 20])), #",
"= self.conv2d(conv1, self.weights['wc2'], self.biases['bc2']) # Max Pooling (down-sampling) # conv2 = self.maxpool2d(conv2, k=2)",
"50])), # second fuly connected layer 100 inputs and 1 output 'out2': tf.Variable(tf.random_normal([50,",
"1]) # Convolution Layer conv1 = self.conv2d(xb, self.weights['wc1'],self.biases['bc1']) # Max Pooling (down-sampling) conv1",
"self.num_TCL = num_TCL with graph.as_default(): # Training Parameters self.learning_rate = 0.1 self.num_steps =",
"= num_TCL with graph.as_default(): # Training Parameters self.learning_rate = 0.1 self.num_steps = 100000",
"= tf.add(tf.matmul(fc, self.weights['out']), self.biases['out']) fc3_sigmoided = tf.nn.sigmoid(fc3) #linear fc prediction = tf.add(tf.matmul(fc3_sigmoided, self.weights['out2']),",
"# plt.legend() # # plt.show() # def retrain(self,xb, xe, y,sess): # saver.restore(sess, \"./model.ckpt\")",
"# def retrain(self,xb, xe, y,sess): # saver.restore(sess, \"./model.ckpt\") # self.run_sess(sess,xb,xe,y) def predict(self, xb,",
"# saver.restore(sess, \"./model.ckpt\") # self.run_sess(sess,xb,xe,y) def predict(self, xb, xe, sess): # tf Graph",
"'__main__': xb, xe, y = get_X_y(steps_back=7, filename=\"Q_data0.csv\") neural_net = NN(batch_size = 100, steps_back=8)",
"tf.get_default_graph()): with graph.as_default(): conv_component = self.conv_net(self.Xb) fc_component = self.fc_net(self.Xe) # concatenate the to",
"fc net with sigmoid fc3 = tf.add(tf.matmul(fc, self.weights['out']), self.biases['out']) fc3_sigmoided = tf.nn.sigmoid(fc3) #linear",
"[-1, self.steps_back, self.cnn_num_input]) batch_y = np.reshape(batch_y,[-1,self.num_output]) batch_tr_xe = batch_xe[:self.batch_tr_size] batch_test_xe = batch_xe[self.batch_tr_size:] batch_tr_xb",
"name) print(\"Model saved in path: %s\" % save_path) def train(self,xb, xe, y, name",
"0.1, steps_back=8, num_TCL=30): self.num_TCL = num_TCL with graph.as_default(): # Training Parameters self.learning_rate =",
"wrapper, with bias and relu activation x = tf.nn.conv2d(x, W, strides=[1, strides, strides,",
"range(xb.shape[0]//self.batch_size): # Run the initializer index = i*self.batch_size self.run_sess(sess, xb[index:index+self.batch_size],xe[index:index+self.batch_size],y[index:index+self.batch_size], saver, name= name)",
"model def conv_net(self,xb): xb = tf.reshape(xb, shape=[-1, self.steps_back, self.num_TCL, 1]) # Convolution Layer",
"self.biases['bd2']) return tf.nn.relu(fc2) def combined_net(self, graph = tf.get_default_graph()): with graph.as_default(): conv_component = self.conv_net(self.Xb)",
"self.weights['wd2'].get_shape().as_list()[0]]) fc2 = tf.add(tf.matmul(xe, self.weights['wd2']), self.biases['bd2']) return tf.nn.relu(fc2) def combined_net(self, graph = tf.get_default_graph()):",
"8, 1, 32])), # 5x5 conv, 32 inputs, 64 outputs 'wc2': tf.Variable(tf.random_normal([2, 8,"
] |
[
"from sklearn.metrics import log_loss ###################################################### # list ids and labels trainids=[] labels=[] with",
"TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE",
"for trainidx, testidx in kf: clf.fit(x[trainidx],y[trainidx]) pred[testidx] = clf.predict_proba(x[testidx]) return pred \"\"\" function",
"n_estimators=400,max_features=None, min_samples_leaf=2,min_samples_split=3, n_jobs=7) for filename in [ '45c.csv', ]: print filename runcv(filename,gbm,xtr) writesubm(filename,gbm,xtr)",
"BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED",
"p1=docv(c1,kf,x,y,nrow) p2=docv(c2,kf,x,y,nrow) pcombi=0.667*p1+0.333*p2 print '%.4f %.4f %.4f'%(log_loss(y,p1),log_loss(y,p2),log_loss(y,pcombi)) with open('pred_%s'%filename,'w') as f: w=csv.writer(f) for",
"AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT",
"def runcv(filename,c1,c2): y=np.array(labels) nrow=len(y) x,_=readdata('train_%s'%filename) x=np.array(x) kf = KFold(nrow,10,shuffle=True) p1=docv(c1,kf,x,y,nrow) p2=docv(c2,kf,x,y,nrow) pcombi=0.667*p1+0.333*p2 print",
"as f: w=csv.writer(f) if header: w.writerow(header) for row in data: w.writerow(row) ###################################################### #",
"of train/ test file, classifier 1 and 2 to be used output: writes",
"OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE",
"to file * train classifiers using all traindata, create testset predictions, combine and",
"holdout-set-predictions for all rows * run cross validation \"\"\" def docv(clf,kf,x,y,nrow,nlab=9): pred =",
"same directory ###################################################### # import dependencies import csv import numpy as np from",
"following conditions are met: 1. Redistributions of source code must retain the above",
"using all traindata, create testset predictions, combine and save results \"\"\" def writesubm(filename,c1,c2):",
"SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY",
"for row in r: testids.append(row[0]) ###################################################### # general functions def readdata(fname,header=True,selectedcols=None): with open(fname,'r')",
"IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. \"\"\" #first run feature_extraction.py #then",
"# _untuned_modeling.py # author: <NAME>, <EMAIL> # licence: FreeBSD \"\"\" Copyright (c) 2015,",
"in [ '45c.csv', ]: print filename runcv(filename,gbm,xtr) writesubm(filename,gbm,xtr) print '' \"\"\" 45c.csv 0.0117",
"all traindata, create testset predictions, combine and save results \"\"\" def writesubm(filename,c1,c2): xtrain,names=readdata('train_%s'%filename)",
"%.4f'%(log_loss(y,p1),log_loss(y,p2),log_loss(y,pcombi)) with open('pred_%s'%filename,'w') as f: w=csv.writer(f) for row in pcombi: w.writerow(row) ###################################################### #",
"if selectedcols: assert header==True data = [[float(e) for i,e in enumerate(row) if names[i]",
"train/ test file, classifier 1 and 2 to be used output: writes holdout-set-predictions",
"for filename in [ '45c.csv', ]: print filename runcv(filename,gbm,xtr) writesubm(filename,gbm,xtr) print '' \"\"\"",
"copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in",
"COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,",
"i,e in enumerate(row) if names[i] in selectedcols] for row in r] names =",
"r=csv.reader(f) r.next() for row in r: testids.append(row[0]) ###################################################### # general functions def readdata(fname,header=True,selectedcols=None):",
"to file * run cross validation by calling docv for both classifiers, combine",
"w.writerow(['Id']+['Prediction%d'%num for num in xrange(1,10)]) for inum,i in enumerate(testids): w.writerow([i]+list(p[inum])) ###################################################### # go",
"All rights reserved. Redistribution and use in source and binary forms, with or",
"SUCH DAMAGE. \"\"\" #first run feature_extraction.py #then run this file from the same",
"input: name of train/ test file, classifier 1 and 2 to be used",
"for row in r] return data,names def writedata(data,fname,header=None): with open(fname,'w') as f: w=csv.writer(f)",
"if __name__ == '__main__': gbm=GradientBoostingClassifier( n_estimators=400, max_features=5) xtr=ExtraTreesClassifier( n_estimators=400,max_features=None, min_samples_leaf=2,min_samples_split=3, n_jobs=7) for filename",
"w.writerow(row) ###################################################### # cross validation \"\"\" function docv input: classifier, kfolds object, features,",
"by calling docv for both classifiers, combine and save results \"\"\" def runcv(filename,c1,c2):",
"r] names = [name for name in names if name in selectedcols] else:",
"<reponame>mcvenkat/Python-Programs<filename>_untuned_modeling.py ###################################################### # _untuned_modeling.py # author: <NAME>, <EMAIL> # licence: FreeBSD \"\"\" Copyright",
"if header else None if selectedcols: assert header==True data = [[float(e) for i,e",
"LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON",
"conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the",
"input: classifier, kfolds object, features, labels, number of data rows output: holdout-set-predictions for",
"train classifiers using all traindata, create testset predictions, combine and save results \"\"\"",
"LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR",
"_untuned_modeling.py # author: <NAME>, <EMAIL> # licence: FreeBSD \"\"\" Copyright (c) 2015, <NAME>",
"assert header==True data = [[float(e) for i,e in enumerate(row) if names[i] in selectedcols]",
"p2=docv(c2,kf,x,y,nrow) pcombi=0.667*p1+0.333*p2 print '%.4f %.4f %.4f'%(log_loss(y,p1),log_loss(y,p2),log_loss(y,pcombi)) with open('pred_%s'%filename,'w') as f: w=csv.writer(f) for row",
"data rows output: holdout-set-predictions for all rows * run cross validation \"\"\" def",
"combine and save results \"\"\" def runcv(filename,c1,c2): y=np.array(labels) nrow=len(y) x,_=readdata('train_%s'%filename) x=np.array(x) kf =",
"met: 1. Redistributions of source code must retain the above copyright notice, this",
"CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;",
"EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. \"\"\" #first run feature_extraction.py",
"must reproduce the above copyright notice, this list of conditions and the following",
"PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER",
"predictions to file * train classifiers using all traindata, create testset predictions, combine",
"feature_extraction.py #then run this file from the same directory ###################################################### # import dependencies",
"THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES,",
"modification, are permitted provided that the following conditions are met: 1. Redistributions of",
"with open(fname,'r') as f: r=csv.reader(f) names = r.next() if header else None if",
"SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. \"\"\" #first run",
"csv import numpy as np from sklearn.cross_validation import KFold from sklearn.ensemble import GradientBoostingClassifier,ExtraTreesClassifier",
"f: w=csv.writer(f) if header: w.writerow(header) for row in data: w.writerow(row) ###################################################### # cross",
"this file from the same directory ###################################################### # import dependencies import csv import",
"open(fname,'r') as f: r=csv.reader(f) names = r.next() if header else None if selectedcols:",
"importance \"\"\" function writesubm input: name of train/ test file, classifier 1 and",
"permitted provided that the following conditions are met: 1. Redistributions of source code",
"PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR",
"docv(clf,kf,x,y,nrow,nlab=9): pred = np.zeros((nrow,nlab)) for trainidx, testidx in kf: clf.fit(x[trainidx],y[trainidx]) pred[testidx] = clf.predict_proba(x[testidx])",
"run cross validation by calling docv for both classifiers, combine and save results",
"distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"",
"###################################################### # _untuned_modeling.py # author: <NAME>, <EMAIL> # licence: FreeBSD \"\"\" Copyright (c)",
"for inum,i in enumerate(testids): w.writerow([i]+list(p[inum])) ###################################################### # go if __name__ == '__main__': gbm=GradientBoostingClassifier(",
"GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER",
"\"\"\" def writesubm(filename,c1,c2): xtrain,names=readdata('train_%s'%filename) xtest,_=readdata('test_%s'%filename) c1.fit(xtrain,labels) c2.fit(xtrain,labels) p1=c1.predict_proba(xtest) p2=c2.predict_proba(xtest) p=0.667*p1+0.333*p2 with open('subm_%s'%filename,'w') as",
"materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS",
"in source and binary forms, with or without modification, are permitted provided that",
"cross validation \"\"\" function docv input: classifier, kfolds object, features, labels, number of",
"THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,",
"np from sklearn.cross_validation import KFold from sklearn.ensemble import GradientBoostingClassifier,ExtraTreesClassifier from sklearn.metrics import log_loss",
"#then run this file from the same directory ###################################################### # import dependencies import",
"labels.append(float(row[1])) testids=[] with open('sampleSubmission.csv','r') as f: r=csv.reader(f) r.next() for row in r: testids.append(row[0])",
"or without modification, are permitted provided that the following conditions are met: 1.",
"results \"\"\" def runcv(filename,c1,c2): y=np.array(labels) nrow=len(y) x,_=readdata('train_%s'%filename) x=np.array(x) kf = KFold(nrow,10,shuffle=True) p1=docv(c1,kf,x,y,nrow) p2=docv(c2,kf,x,y,nrow)",
"the above copyright notice, this list of conditions and the following disclaimer in",
"CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED",
"ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED",
"as f: r=csv.reader(f) r.next() # skip header for row in r: trainids.append(row[0]) labels.append(float(row[1]))",
"KFold(nrow,10,shuffle=True) p1=docv(c1,kf,x,y,nrow) p2=docv(c2,kf,x,y,nrow) pcombi=0.667*p1+0.333*p2 print '%.4f %.4f %.4f'%(log_loss(y,p1),log_loss(y,p2),log_loss(y,pcombi)) with open('pred_%s'%filename,'w') as f: w=csv.writer(f)",
"docv for both classifiers, combine and save results \"\"\" def runcv(filename,c1,c2): y=np.array(labels) nrow=len(y)",
"list of conditions and the following disclaimer. 2. Redistributions in binary form must",
"all rows to file * run cross validation by calling docv for both",
"w=csv.writer(f) if header: w.writerow(header) for row in data: w.writerow(row) ###################################################### # cross validation",
"this list of conditions and the following disclaimer. 2. Redistributions in binary form",
"# licence: FreeBSD \"\"\" Copyright (c) 2015, <NAME> All rights reserved. Redistribution and",
"author: <NAME>, <EMAIL> # licence: FreeBSD \"\"\" Copyright (c) 2015, <NAME> All rights",
"HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,",
"and the following disclaimer in the documentation and/or other materials provided with the",
"Copyright (c) 2015, <NAME> All rights reserved. Redistribution and use in source and",
"run cross validation \"\"\" def docv(clf,kf,x,y,nrow,nlab=9): pred = np.zeros((nrow,nlab)) for trainidx, testidx in",
"[name for name in names if name in selectedcols] else: data = [[float(e)",
"inum,i in enumerate(testids): w.writerow([i]+list(p[inum])) ###################################################### # go if __name__ == '__main__': gbm=GradientBoostingClassifier( n_estimators=400,",
"GradientBoostingClassifier,ExtraTreesClassifier from sklearn.metrics import log_loss ###################################################### # list ids and labels trainids=[] labels=[]",
"the following disclaimer in the documentation and/or other materials provided with the distribution.",
"notice, this list of conditions and the following disclaimer in the documentation and/or",
"COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,",
"used output: writes testset predictions to file * train classifiers using all traindata,",
"w.writerow([i]+list(p[inum])) ###################################################### # go if __name__ == '__main__': gbm=GradientBoostingClassifier( n_estimators=400, max_features=5) xtr=ExtraTreesClassifier( n_estimators=400,max_features=None,",
"Redistributions of source code must retain the above copyright notice, this list of",
"with or without modification, are permitted provided that the following conditions are met:",
"labels trainids=[] labels=[] with open('trainLabels.csv','r') as f: r=csv.reader(f) r.next() # skip header for",
"###################################################### # general functions def readdata(fname,header=True,selectedcols=None): with open(fname,'r') as f: r=csv.reader(f) names =",
"testset predictions, combine and save results \"\"\" def writesubm(filename,c1,c2): xtrain,names=readdata('train_%s'%filename) xtest,_=readdata('test_%s'%filename) c1.fit(xtrain,labels) c2.fit(xtrain,labels)",
"(c) 2015, <NAME> All rights reserved. Redistribution and use in source and binary",
"row in r: testids.append(row[0]) ###################################################### # general functions def readdata(fname,header=True,selectedcols=None): with open(fname,'r') as",
"\"\"\" def runcv(filename,c1,c2): y=np.array(labels) nrow=len(y) x,_=readdata('train_%s'%filename) x=np.array(x) kf = KFold(nrow,10,shuffle=True) p1=docv(c1,kf,x,y,nrow) p2=docv(c2,kf,x,y,nrow) pcombi=0.667*p1+0.333*p2",
"following disclaimer in the documentation and/or other materials provided with the distribution. THIS",
"r: trainids.append(row[0]) labels.append(float(row[1])) testids=[] with open('sampleSubmission.csv','r') as f: r=csv.reader(f) r.next() for row in",
"import dependencies import csv import numpy as np from sklearn.cross_validation import KFold from",
"reproduce the above copyright notice, this list of conditions and the following disclaimer",
"2 to be used output: writes testset predictions to file * train classifiers",
"of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce",
"#first run feature_extraction.py #then run this file from the same directory ###################################################### #",
"if name in selectedcols] else: data = [[float(e) for e in row] for",
"BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,",
"list ids and labels trainids=[] labels=[] with open('trainLabels.csv','r') as f: r=csv.reader(f) r.next() #",
"Redistribution and use in source and binary forms, with or without modification, are",
"object, features, labels, number of data rows output: holdout-set-predictions for all rows *",
"DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR",
"PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR",
"USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY",
"classifiers, combine and save results \"\"\" def runcv(filename,c1,c2): y=np.array(labels) nrow=len(y) x,_=readdata('train_%s'%filename) x=np.array(x) kf",
"FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT",
"def writedata(data,fname,header=None): with open(fname,'w') as f: w=csv.writer(f) if header: w.writerow(header) for row in",
"binary forms, with or without modification, are permitted provided that the following conditions",
"for row in r: trainids.append(row[0]) labels.append(float(row[1])) testids=[] with open('sampleSubmission.csv','r') as f: r=csv.reader(f) r.next()",
"TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;",
"OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS",
"classifier 1 and 2 to be used output: writes holdout-set-predictions for all rows",
"THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. \"\"\" #first",
"to be used output: writes testset predictions to file * train classifiers using",
"LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING",
"clf.fit(x[trainidx],y[trainidx]) pred[testidx] = clf.predict_proba(x[testidx]) return pred \"\"\" function runcv input: name of train/",
"as f: r=csv.reader(f) names = r.next() if header else None if selectedcols: assert",
"KFold from sklearn.ensemble import GradientBoostingClassifier,ExtraTreesClassifier from sklearn.metrics import log_loss ###################################################### # list ids",
"trainids=[] labels=[] with open('trainLabels.csv','r') as f: r=csv.reader(f) r.next() # skip header for row",
"(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF",
"name in selectedcols] else: data = [[float(e) for e in row] for row",
"None if selectedcols: assert header==True data = [[float(e) for i,e in enumerate(row) if",
"else None if selectedcols: assert header==True data = [[float(e) for i,e in enumerate(row)",
"enumerate(testids): w.writerow([i]+list(p[inum])) ###################################################### # go if __name__ == '__main__': gbm=GradientBoostingClassifier( n_estimators=400, max_features=5) xtr=ExtraTreesClassifier(",
"IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND",
"general functions def readdata(fname,header=True,selectedcols=None): with open(fname,'r') as f: r=csv.reader(f) names = r.next() if",
"DAMAGE. \"\"\" #first run feature_extraction.py #then run this file from the same directory",
"run feature_extraction.py #then run this file from the same directory ###################################################### # import",
"dependencies import csv import numpy as np from sklearn.cross_validation import KFold from sklearn.ensemble",
"header: w.writerow(header) for row in data: w.writerow(row) ###################################################### # cross validation \"\"\" function",
"p2=c2.predict_proba(xtest) p=0.667*p1+0.333*p2 with open('subm_%s'%filename,'w') as f: w=csv.writer(f) w.writerow(['Id']+['Prediction%d'%num for num in xrange(1,10)]) for",
"ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES",
"header else None if selectedcols: assert header==True data = [[float(e) for i,e in",
"for row in r] names = [name for name in names if name",
"and print feature importance \"\"\" function writesubm input: name of train/ test file,",
"trainidx, testidx in kf: clf.fit(x[trainidx],y[trainidx]) pred[testidx] = clf.predict_proba(x[testidx]) return pred \"\"\" function runcv",
"conditions and the following disclaimer in the documentation and/or other materials provided with",
"w.writerow(row) ###################################################### # submit and print feature importance \"\"\" function writesubm input: name",
"print '%.4f %.4f %.4f'%(log_loss(y,p1),log_loss(y,p2),log_loss(y,pcombi)) with open('pred_%s'%filename,'w') as f: w=csv.writer(f) for row in pcombi:",
"pred = np.zeros((nrow,nlab)) for trainidx, testidx in kf: clf.fit(x[trainidx],y[trainidx]) pred[testidx] = clf.predict_proba(x[testidx]) return",
"data = [[float(e) for e in row] for row in r] return data,names",
"* run cross validation by calling docv for both classifiers, combine and save",
"= r.next() if header else None if selectedcols: assert header==True data = [[float(e)",
"# go if __name__ == '__main__': gbm=GradientBoostingClassifier( n_estimators=400, max_features=5) xtr=ExtraTreesClassifier( n_estimators=400,max_features=None, min_samples_leaf=2,min_samples_split=3, n_jobs=7)",
"'45c.csv', ]: print filename runcv(filename,gbm,xtr) writesubm(filename,gbm,xtr) print '' \"\"\" 45c.csv 0.0117 0.0168 0.0101",
"LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT",
"return data,names def writedata(data,fname,header=None): with open(fname,'w') as f: w=csv.writer(f) if header: w.writerow(header) for",
"list of conditions and the following disclaimer in the documentation and/or other materials",
"docv input: classifier, kfolds object, features, labels, number of data rows output: holdout-set-predictions",
"above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions",
"in kf: clf.fit(x[trainidx],y[trainidx]) pred[testidx] = clf.predict_proba(x[testidx]) return pred \"\"\" function runcv input: name",
"y=np.array(labels) nrow=len(y) x,_=readdata('train_%s'%filename) x=np.array(x) kf = KFold(nrow,10,shuffle=True) p1=docv(c1,kf,x,y,nrow) p2=docv(c2,kf,x,y,nrow) pcombi=0.667*p1+0.333*p2 print '%.4f %.4f",
"OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN",
"c2.fit(xtrain,labels) p1=c1.predict_proba(xtest) p2=c2.predict_proba(xtest) p=0.667*p1+0.333*p2 with open('subm_%s'%filename,'w') as f: w=csv.writer(f) w.writerow(['Id']+['Prediction%d'%num for num in",
"= np.zeros((nrow,nlab)) for trainidx, testidx in kf: clf.fit(x[trainidx],y[trainidx]) pred[testidx] = clf.predict_proba(x[testidx]) return pred",
"= clf.predict_proba(x[testidx]) return pred \"\"\" function runcv input: name of train/ test file,",
"file * train classifiers using all traindata, create testset predictions, combine and save",
"r.next() for row in r: testids.append(row[0]) ###################################################### # general functions def readdata(fname,header=True,selectedcols=None): with",
"NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,",
"OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,",
"to be used output: writes holdout-set-predictions for all rows to file * run",
"readdata(fname,header=True,selectedcols=None): with open(fname,'r') as f: r=csv.reader(f) names = r.next() if header else None",
"def docv(clf,kf,x,y,nrow,nlab=9): pred = np.zeros((nrow,nlab)) for trainidx, testidx in kf: clf.fit(x[trainidx],y[trainidx]) pred[testidx] =",
"'%.4f %.4f %.4f'%(log_loss(y,p1),log_loss(y,p2),log_loss(y,pcombi)) with open('pred_%s'%filename,'w') as f: w=csv.writer(f) for row in pcombi: w.writerow(row)",
"\"\"\" function writesubm input: name of train/ test file, classifier 1 and 2",
"output: writes testset predictions to file * train classifiers using all traindata, create",
"e in row] for row in r] return data,names def writedata(data,fname,header=None): with open(fname,'w')",
"the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS",
"###################################################### # submit and print feature importance \"\"\" function writesubm input: name of",
"2015, <NAME> All rights reserved. Redistribution and use in source and binary forms,",
"for row in pcombi: w.writerow(row) ###################################################### # submit and print feature importance \"\"\"",
"EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF",
"in pcombi: w.writerow(row) ###################################################### # submit and print feature importance \"\"\" function writesubm",
"for all rows to file * run cross validation by calling docv for",
"r.next() # skip header for row in r: trainids.append(row[0]) labels.append(float(row[1])) testids=[] with open('sampleSubmission.csv','r')",
"in xrange(1,10)]) for inum,i in enumerate(testids): w.writerow([i]+list(p[inum])) ###################################################### # go if __name__ ==",
"OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY",
"THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH",
"function runcv input: name of train/ test file, classifier 1 and 2 to",
"2. Redistributions in binary form must reproduce the above copyright notice, this list",
"OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY",
"INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT",
"SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE",
"pred \"\"\" function runcv input: name of train/ test file, classifier 1 and",
"following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice,",
"save results \"\"\" def runcv(filename,c1,c2): y=np.array(labels) nrow=len(y) x,_=readdata('train_%s'%filename) x=np.array(x) kf = KFold(nrow,10,shuffle=True) p1=docv(c1,kf,x,y,nrow)",
"the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED",
"validation \"\"\" def docv(clf,kf,x,y,nrow,nlab=9): pred = np.zeros((nrow,nlab)) for trainidx, testidx in kf: clf.fit(x[trainidx],y[trainidx])",
"documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY",
"combine and save results \"\"\" def writesubm(filename,c1,c2): xtrain,names=readdata('train_%s'%filename) xtest,_=readdata('test_%s'%filename) c1.fit(xtrain,labels) c2.fit(xtrain,labels) p1=c1.predict_proba(xtest) p2=c2.predict_proba(xtest)",
"rows to file * run cross validation by calling docv for both classifiers,",
"NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR",
"cross validation \"\"\" def docv(clf,kf,x,y,nrow,nlab=9): pred = np.zeros((nrow,nlab)) for trainidx, testidx in kf:",
"must retain the above copyright notice, this list of conditions and the following",
"STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT",
"open('trainLabels.csv','r') as f: r=csv.reader(f) r.next() # skip header for row in r: trainids.append(row[0])",
"HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR",
"notice, this list of conditions and the following disclaimer. 2. Redistributions in binary",
"1 and 2 to be used output: writes holdout-set-predictions for all rows to",
"the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright",
"ids and labels trainids=[] labels=[] with open('trainLabels.csv','r') as f: r=csv.reader(f) r.next() # skip",
"PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS",
"= KFold(nrow,10,shuffle=True) p1=docv(c1,kf,x,y,nrow) p2=docv(c2,kf,x,y,nrow) pcombi=0.667*p1+0.333*p2 print '%.4f %.4f %.4f'%(log_loss(y,p1),log_loss(y,p2),log_loss(y,pcombi)) with open('pred_%s'%filename,'w') as f:",
"[ '45c.csv', ]: print filename runcv(filename,gbm,xtr) writesubm(filename,gbm,xtr) print '' \"\"\" 45c.csv 0.0117 0.0168",
"in r: trainids.append(row[0]) labels.append(float(row[1])) testids=[] with open('sampleSubmission.csv','r') as f: r=csv.reader(f) r.next() for row",
"# general functions def readdata(fname,header=True,selectedcols=None): with open(fname,'r') as f: r=csv.reader(f) names = r.next()",
"row in r] names = [name for name in names if name in",
"from sklearn.cross_validation import KFold from sklearn.ensemble import GradientBoostingClassifier,ExtraTreesClassifier from sklearn.metrics import log_loss ######################################################",
"forms, with or without modification, are permitted provided that the following conditions are",
"in selectedcols] else: data = [[float(e) for e in row] for row in",
"as f: w=csv.writer(f) w.writerow(['Id']+['Prediction%d'%num for num in xrange(1,10)]) for inum,i in enumerate(testids): w.writerow([i]+list(p[inum]))",
"writesubm(filename,gbm,xtr) print '' \"\"\" 45c.csv 0.0117 0.0168 0.0101 public LB: 0.008071379 private LB:",
"writes testset predictions to file * train classifiers using all traindata, create testset",
"and save results \"\"\" def writesubm(filename,c1,c2): xtrain,names=readdata('train_%s'%filename) xtest,_=readdata('test_%s'%filename) c1.fit(xtrain,labels) c2.fit(xtrain,labels) p1=c1.predict_proba(xtest) p2=c2.predict_proba(xtest) p=0.667*p1+0.333*p2",
"IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE",
"train/ test file, classifier 1 and 2 to be used output: writes testset",
"<NAME>, <EMAIL> # licence: FreeBSD \"\"\" Copyright (c) 2015, <NAME> All rights reserved.",
"and 2 to be used output: writes testset predictions to file * train",
"kfolds object, features, labels, number of data rows output: holdout-set-predictions for all rows",
"name of train/ test file, classifier 1 and 2 to be used output:",
"that the following conditions are met: 1. Redistributions of source code must retain",
"import numpy as np from sklearn.cross_validation import KFold from sklearn.ensemble import GradientBoostingClassifier,ExtraTreesClassifier from",
"n_estimators=400, max_features=5) xtr=ExtraTreesClassifier( n_estimators=400,max_features=None, min_samples_leaf=2,min_samples_split=3, n_jobs=7) for filename in [ '45c.csv', ]: print",
"as f: w=csv.writer(f) for row in pcombi: w.writerow(row) ###################################################### # submit and print",
"writesubm input: name of train/ test file, classifier 1 and 2 to be",
"* train classifiers using all traindata, create testset predictions, combine and save results",
"selectedcols: assert header==True data = [[float(e) for i,e in enumerate(row) if names[i] in",
"be used output: writes holdout-set-predictions for all rows to file * run cross",
"THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.",
"pcombi=0.667*p1+0.333*p2 print '%.4f %.4f %.4f'%(log_loss(y,p1),log_loss(y,p2),log_loss(y,pcombi)) with open('pred_%s'%filename,'w') as f: w=csv.writer(f) for row in",
"MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL",
"# skip header for row in r: trainids.append(row[0]) labels.append(float(row[1])) testids=[] with open('sampleSubmission.csv','r') as",
"and 2 to be used output: writes holdout-set-predictions for all rows to file",
"p1=c1.predict_proba(xtest) p2=c2.predict_proba(xtest) p=0.667*p1+0.333*p2 with open('subm_%s'%filename,'w') as f: w=csv.writer(f) w.writerow(['Id']+['Prediction%d'%num for num in xrange(1,10)])",
"p=0.667*p1+0.333*p2 with open('subm_%s'%filename,'w') as f: w=csv.writer(f) w.writerow(['Id']+['Prediction%d'%num for num in xrange(1,10)]) for inum,i",
"of source code must retain the above copyright notice, this list of conditions",
"INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF",
"name in names if name in selectedcols] else: data = [[float(e) for e",
"writedata(data,fname,header=None): with open(fname,'w') as f: w=csv.writer(f) if header: w.writerow(header) for row in data:",
"2 to be used output: writes holdout-set-predictions for all rows to file *",
"file, classifier 1 and 2 to be used output: writes holdout-set-predictions for all",
"for row in data: w.writerow(row) ###################################################### # cross validation \"\"\" function docv input:",
"%.4f %.4f'%(log_loss(y,p1),log_loss(y,p2),log_loss(y,pcombi)) with open('pred_%s'%filename,'w') as f: w=csv.writer(f) for row in pcombi: w.writerow(row) ######################################################",
"OF THE POSSIBILITY OF SUCH DAMAGE. \"\"\" #first run feature_extraction.py #then run this",
"OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL",
"disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this",
"for e in row] for row in r] return data,names def writedata(data,fname,header=None): with",
"# author: <NAME>, <EMAIL> # licence: FreeBSD \"\"\" Copyright (c) 2015, <NAME> All",
"f: r=csv.reader(f) r.next() for row in r: testids.append(row[0]) ###################################################### # general functions def",
"gbm=GradientBoostingClassifier( n_estimators=400, max_features=5) xtr=ExtraTreesClassifier( n_estimators=400,max_features=None, min_samples_leaf=2,min_samples_split=3, n_jobs=7) for filename in [ '45c.csv', ]:",
"ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF",
"print '' \"\"\" 45c.csv 0.0117 0.0168 0.0101 public LB: 0.008071379 private LB: 0.007615772",
"THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND",
"[[float(e) for i,e in enumerate(row) if names[i] in selectedcols] for row in r]",
"TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE",
"FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER",
"WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS",
"for name in names if name in selectedcols] else: data = [[float(e) for",
"names if name in selectedcols] else: data = [[float(e) for e in row]",
"for num in xrange(1,10)]) for inum,i in enumerate(testids): w.writerow([i]+list(p[inum])) ###################################################### # go if",
"rows * run cross validation \"\"\" def docv(clf,kf,x,y,nrow,nlab=9): pred = np.zeros((nrow,nlab)) for trainidx,",
"# cross validation \"\"\" function docv input: classifier, kfolds object, features, labels, number",
"BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,",
"trainids.append(row[0]) labels.append(float(row[1])) testids=[] with open('sampleSubmission.csv','r') as f: r=csv.reader(f) r.next() for row in r:",
"open('subm_%s'%filename,'w') as f: w=csv.writer(f) w.writerow(['Id']+['Prediction%d'%num for num in xrange(1,10)]) for inum,i in enumerate(testids):",
"\"\"\" #first run feature_extraction.py #then run this file from the same directory ######################################################",
"OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR",
"names = r.next() if header else None if selectedcols: assert header==True data =",
"output: writes holdout-set-predictions for all rows to file * run cross validation by",
"sklearn.ensemble import GradientBoostingClassifier,ExtraTreesClassifier from sklearn.metrics import log_loss ###################################################### # list ids and labels",
"names = [name for name in names if name in selectedcols] else: data",
"classifier 1 and 2 to be used output: writes testset predictions to file",
"in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS",
"file * run cross validation by calling docv for both classifiers, combine and",
"data,names def writedata(data,fname,header=None): with open(fname,'w') as f: w=csv.writer(f) if header: w.writerow(header) for row",
"and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE",
"from sklearn.ensemble import GradientBoostingClassifier,ExtraTreesClassifier from sklearn.metrics import log_loss ###################################################### # list ids and",
"writesubm(filename,c1,c2): xtrain,names=readdata('train_%s'%filename) xtest,_=readdata('test_%s'%filename) c1.fit(xtrain,labels) c2.fit(xtrain,labels) p1=c1.predict_proba(xtest) p2=c2.predict_proba(xtest) p=0.667*p1+0.333*p2 with open('subm_%s'%filename,'w') as f: w=csv.writer(f)",
"in r] names = [name for name in names if name in selectedcols]",
"ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE",
"OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY",
"else: data = [[float(e) for e in row] for row in r] return",
"INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR",
"INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT",
"testids.append(row[0]) ###################################################### # general functions def readdata(fname,header=True,selectedcols=None): with open(fname,'r') as f: r=csv.reader(f) names",
"def readdata(fname,header=True,selectedcols=None): with open(fname,'r') as f: r=csv.reader(f) names = r.next() if header else",
"functions def readdata(fname,header=True,selectedcols=None): with open(fname,'r') as f: r=csv.reader(f) names = r.next() if header",
"###################################################### # import dependencies import csv import numpy as np from sklearn.cross_validation import",
"\"\"\" function docv input: classifier, kfolds object, features, labels, number of data rows",
"np.zeros((nrow,nlab)) for trainidx, testidx in kf: clf.fit(x[trainidx],y[trainidx]) pred[testidx] = clf.predict_proba(x[testidx]) return pred \"\"\"",
"and labels trainids=[] labels=[] with open('trainLabels.csv','r') as f: r=csv.reader(f) r.next() # skip header",
"CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES",
"disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE",
"directory ###################################################### # import dependencies import csv import numpy as np from sklearn.cross_validation",
"w=csv.writer(f) w.writerow(['Id']+['Prediction%d'%num for num in xrange(1,10)]) for inum,i in enumerate(testids): w.writerow([i]+list(p[inum])) ###################################################### #",
"of data rows output: holdout-set-predictions for all rows * run cross validation \"\"\"",
"this list of conditions and the following disclaimer in the documentation and/or other",
"EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,",
"w.writerow(header) for row in data: w.writerow(row) ###################################################### # cross validation \"\"\" function docv",
"(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF",
"numpy as np from sklearn.cross_validation import KFold from sklearn.ensemble import GradientBoostingClassifier,ExtraTreesClassifier from sklearn.metrics",
"<NAME> All rights reserved. Redistribution and use in source and binary forms, with",
"Redistributions in binary form must reproduce the above copyright notice, this list of",
"all rows * run cross validation \"\"\" def docv(clf,kf,x,y,nrow,nlab=9): pred = np.zeros((nrow,nlab)) for",
"LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE",
"DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,",
"function docv input: classifier, kfolds object, features, labels, number of data rows output:",
"classifier, kfolds object, features, labels, number of data rows output: holdout-set-predictions for all",
"\"\"\" function runcv input: name of train/ test file, classifier 1 and 2",
"log_loss ###################################################### # list ids and labels trainids=[] labels=[] with open('trainLabels.csv','r') as f:",
"HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT",
"rights reserved. Redistribution and use in source and binary forms, with or without",
"the above copyright notice, this list of conditions and the following disclaimer. 2.",
"IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED",
"runcv(filename,c1,c2): y=np.array(labels) nrow=len(y) x,_=readdata('train_%s'%filename) x=np.array(x) kf = KFold(nrow,10,shuffle=True) p1=docv(c1,kf,x,y,nrow) p2=docv(c2,kf,x,y,nrow) pcombi=0.667*p1+0.333*p2 print '%.4f",
"and the following disclaimer. 2. Redistributions in binary form must reproduce the above",
"num in xrange(1,10)]) for inum,i in enumerate(testids): w.writerow([i]+list(p[inum])) ###################################################### # go if __name__",
"row in data: w.writerow(row) ###################################################### # cross validation \"\"\" function docv input: classifier,",
"binary form must reproduce the above copyright notice, this list of conditions and",
"licence: FreeBSD \"\"\" Copyright (c) 2015, <NAME> All rights reserved. Redistribution and use",
"number of data rows output: holdout-set-predictions for all rows * run cross validation",
"and save results \"\"\" def runcv(filename,c1,c2): y=np.array(labels) nrow=len(y) x,_=readdata('train_%s'%filename) x=np.array(x) kf = KFold(nrow,10,shuffle=True)",
"DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF",
"file from the same directory ###################################################### # import dependencies import csv import numpy",
"nrow=len(y) x,_=readdata('train_%s'%filename) x=np.array(x) kf = KFold(nrow,10,shuffle=True) p1=docv(c1,kf,x,y,nrow) p2=docv(c2,kf,x,y,nrow) pcombi=0.667*p1+0.333*p2 print '%.4f %.4f %.4f'%(log_loss(y,p1),log_loss(y,p2),log_loss(y,pcombi))",
"filename in [ '45c.csv', ]: print filename runcv(filename,gbm,xtr) writesubm(filename,gbm,xtr) print '' \"\"\" 45c.csv",
"IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY",
"'__main__': gbm=GradientBoostingClassifier( n_estimators=400, max_features=5) xtr=ExtraTreesClassifier( n_estimators=400,max_features=None, min_samples_leaf=2,min_samples_split=3, n_jobs=7) for filename in [ '45c.csv',",
"__name__ == '__main__': gbm=GradientBoostingClassifier( n_estimators=400, max_features=5) xtr=ExtraTreesClassifier( n_estimators=400,max_features=None, min_samples_leaf=2,min_samples_split=3, n_jobs=7) for filename in",
"EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS",
"]: print filename runcv(filename,gbm,xtr) writesubm(filename,gbm,xtr) print '' \"\"\" 45c.csv 0.0117 0.0168 0.0101 public",
"holdout-set-predictions for all rows to file * run cross validation by calling docv",
"sklearn.metrics import log_loss ###################################################### # list ids and labels trainids=[] labels=[] with open('trainLabels.csv','r')",
"for i,e in enumerate(row) if names[i] in selectedcols] for row in r] names",
"IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN",
"file, classifier 1 and 2 to be used output: writes testset predictions to",
"runcv(filename,gbm,xtr) writesubm(filename,gbm,xtr) print '' \"\"\" 45c.csv 0.0117 0.0168 0.0101 public LB: 0.008071379 private",
"x,_=readdata('train_%s'%filename) x=np.array(x) kf = KFold(nrow,10,shuffle=True) p1=docv(c1,kf,x,y,nrow) p2=docv(c2,kf,x,y,nrow) pcombi=0.667*p1+0.333*p2 print '%.4f %.4f %.4f'%(log_loss(y,p1),log_loss(y,p2),log_loss(y,pcombi)) with",
"retain the above copyright notice, this list of conditions and the following disclaimer.",
"results \"\"\" def writesubm(filename,c1,c2): xtrain,names=readdata('train_%s'%filename) xtest,_=readdata('test_%s'%filename) c1.fit(xtrain,labels) c2.fit(xtrain,labels) p1=c1.predict_proba(xtest) p2=c2.predict_proba(xtest) p=0.667*p1+0.333*p2 with open('subm_%s'%filename,'w')",
"ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF",
"BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A",
"r=csv.reader(f) r.next() # skip header for row in r: trainids.append(row[0]) labels.append(float(row[1])) testids=[] with",
"for both classifiers, combine and save results \"\"\" def runcv(filename,c1,c2): y=np.array(labels) nrow=len(y) x,_=readdata('train_%s'%filename)",
"traindata, create testset predictions, combine and save results \"\"\" def writesubm(filename,c1,c2): xtrain,names=readdata('train_%s'%filename) xtest,_=readdata('test_%s'%filename)",
"testids=[] with open('sampleSubmission.csv','r') as f: r=csv.reader(f) r.next() for row in r: testids.append(row[0]) ######################################################",
"OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT",
"THE POSSIBILITY OF SUCH DAMAGE. \"\"\" #first run feature_extraction.py #then run this file",
"enumerate(row) if names[i] in selectedcols] for row in r] names = [name for",
"cross validation by calling docv for both classifiers, combine and save results \"\"\"",
"in enumerate(row) if names[i] in selectedcols] for row in r] names = [name",
"labels, number of data rows output: holdout-set-predictions for all rows * run cross",
"LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF",
"reserved. Redistribution and use in source and binary forms, with or without modification,",
"be used output: writes testset predictions to file * train classifiers using all",
"= [[float(e) for i,e in enumerate(row) if names[i] in selectedcols] for row in",
"[[float(e) for e in row] for row in r] return data,names def writedata(data,fname,header=None):",
"in binary form must reproduce the above copyright notice, this list of conditions",
"of conditions and the following disclaimer in the documentation and/or other materials provided",
"<EMAIL> # licence: FreeBSD \"\"\" Copyright (c) 2015, <NAME> All rights reserved. Redistribution",
"output: holdout-set-predictions for all rows * run cross validation \"\"\" def docv(clf,kf,x,y,nrow,nlab=9): pred",
"in r] return data,names def writedata(data,fname,header=None): with open(fname,'w') as f: w=csv.writer(f) if header:",
"SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,",
"if header: w.writerow(header) for row in data: w.writerow(row) ###################################################### # cross validation \"\"\"",
"in r: testids.append(row[0]) ###################################################### # general functions def readdata(fname,header=True,selectedcols=None): with open(fname,'r') as f:",
"OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,",
"\"\"\" def docv(clf,kf,x,y,nrow,nlab=9): pred = np.zeros((nrow,nlab)) for trainidx, testidx in kf: clf.fit(x[trainidx],y[trainidx]) pred[testidx]",
"print filename runcv(filename,gbm,xtr) writesubm(filename,gbm,xtr) print '' \"\"\" 45c.csv 0.0117 0.0168 0.0101 public LB:",
"submit and print feature importance \"\"\" function writesubm input: name of train/ test",
"skip header for row in r: trainids.append(row[0]) labels.append(float(row[1])) testids=[] with open('sampleSubmission.csv','r') as f:",
"code must retain the above copyright notice, this list of conditions and the",
"= [name for name in names if name in selectedcols] else: data =",
"features, labels, number of data rows output: holdout-set-predictions for all rows * run",
"and binary forms, with or without modification, are permitted provided that the following",
"r=csv.reader(f) names = r.next() if header else None if selectedcols: assert header==True data",
"source code must retain the above copyright notice, this list of conditions and",
"print feature importance \"\"\" function writesubm input: name of train/ test file, classifier",
"\"\"\" Copyright (c) 2015, <NAME> All rights reserved. Redistribution and use in source",
"ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE",
"with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS",
"with open('sampleSubmission.csv','r') as f: r=csv.reader(f) r.next() for row in r: testids.append(row[0]) ###################################################### #",
"xtr=ExtraTreesClassifier( n_estimators=400,max_features=None, min_samples_leaf=2,min_samples_split=3, n_jobs=7) for filename in [ '45c.csv', ]: print filename runcv(filename,gbm,xtr)",
"run this file from the same directory ###################################################### # import dependencies import csv",
"OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED",
"filename runcv(filename,gbm,xtr) writesubm(filename,gbm,xtr) print '' \"\"\" 45c.csv 0.0117 0.0168 0.0101 public LB: 0.008071379",
"xrange(1,10)]) for inum,i in enumerate(testids): w.writerow([i]+list(p[inum])) ###################################################### # go if __name__ == '__main__':",
"OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF",
"used output: writes holdout-set-predictions for all rows to file * run cross validation",
"# submit and print feature importance \"\"\" function writesubm input: name of train/",
"* run cross validation \"\"\" def docv(clf,kf,x,y,nrow,nlab=9): pred = np.zeros((nrow,nlab)) for trainidx, testidx",
"FreeBSD \"\"\" Copyright (c) 2015, <NAME> All rights reserved. Redistribution and use in",
"calling docv for both classifiers, combine and save results \"\"\" def runcv(filename,c1,c2): y=np.array(labels)",
"test file, classifier 1 and 2 to be used output: writes holdout-set-predictions for",
"IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY",
"open('sampleSubmission.csv','r') as f: r=csv.reader(f) r.next() for row in r: testids.append(row[0]) ###################################################### # general",
"as f: r=csv.reader(f) r.next() for row in r: testids.append(row[0]) ###################################################### # general functions",
"are permitted provided that the following conditions are met: 1. Redistributions of source",
"both classifiers, combine and save results \"\"\" def runcv(filename,c1,c2): y=np.array(labels) nrow=len(y) x,_=readdata('train_%s'%filename) x=np.array(x)",
"without modification, are permitted provided that the following conditions are met: 1. Redistributions",
"conditions are met: 1. Redistributions of source code must retain the above copyright",
"testidx in kf: clf.fit(x[trainidx],y[trainidx]) pred[testidx] = clf.predict_proba(x[testidx]) return pred \"\"\" function runcv input:",
"CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY",
"FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT",
"feature importance \"\"\" function writesubm input: name of train/ test file, classifier 1",
"f: w=csv.writer(f) for row in pcombi: w.writerow(row) ###################################################### # submit and print feature",
"BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,",
"\"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,",
"AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT",
"as np from sklearn.cross_validation import KFold from sklearn.ensemble import GradientBoostingClassifier,ExtraTreesClassifier from sklearn.metrics import",
"validation \"\"\" function docv input: classifier, kfolds object, features, labels, number of data",
"header==True data = [[float(e) for i,e in enumerate(row) if names[i] in selectedcols] for",
"sklearn.cross_validation import KFold from sklearn.ensemble import GradientBoostingClassifier,ExtraTreesClassifier from sklearn.metrics import log_loss ###################################################### #",
"r] return data,names def writedata(data,fname,header=None): with open(fname,'w') as f: w=csv.writer(f) if header: w.writerow(header)",
"provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND",
"form must reproduce the above copyright notice, this list of conditions and the",
"the same directory ###################################################### # import dependencies import csv import numpy as np",
"###################################################### # cross validation \"\"\" function docv input: classifier, kfolds object, features, labels,",
"n_jobs=7) for filename in [ '45c.csv', ]: print filename runcv(filename,gbm,xtr) writesubm(filename,gbm,xtr) print ''",
"above copyright notice, this list of conditions and the following disclaimer in the",
"'' \"\"\" 45c.csv 0.0117 0.0168 0.0101 public LB: 0.008071379 private LB: 0.007615772 \"\"\"",
"1. Redistributions of source code must retain the above copyright notice, this list",
"OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. \"\"\"",
"and use in source and binary forms, with or without modification, are permitted",
"use in source and binary forms, with or without modification, are permitted provided",
"in enumerate(testids): w.writerow([i]+list(p[inum])) ###################################################### # go if __name__ == '__main__': gbm=GradientBoostingClassifier( n_estimators=400, max_features=5)",
"import csv import numpy as np from sklearn.cross_validation import KFold from sklearn.ensemble import",
"copyright notice, this list of conditions and the following disclaimer in the documentation",
"for all rows * run cross validation \"\"\" def docv(clf,kf,x,y,nrow,nlab=9): pred = np.zeros((nrow,nlab))",
"labels=[] with open('trainLabels.csv','r') as f: r=csv.reader(f) r.next() # skip header for row in",
"= [[float(e) for e in row] for row in r] return data,names def",
"save results \"\"\" def writesubm(filename,c1,c2): xtrain,names=readdata('train_%s'%filename) xtest,_=readdata('test_%s'%filename) c1.fit(xtrain,labels) c2.fit(xtrain,labels) p1=c1.predict_proba(xtest) p2=c2.predict_proba(xtest) p=0.667*p1+0.333*p2 with",
"kf: clf.fit(x[trainidx],y[trainidx]) pred[testidx] = clf.predict_proba(x[testidx]) return pred \"\"\" function runcv input: name of",
"selectedcols] else: data = [[float(e) for e in row] for row in r]",
"w=csv.writer(f) for row in pcombi: w.writerow(row) ###################################################### # submit and print feature importance",
"IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS",
"THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR",
"with open(fname,'w') as f: w=csv.writer(f) if header: w.writerow(header) for row in data: w.writerow(row)",
"predictions, combine and save results \"\"\" def writesubm(filename,c1,c2): xtrain,names=readdata('train_%s'%filename) xtest,_=readdata('test_%s'%filename) c1.fit(xtrain,labels) c2.fit(xtrain,labels) p1=c1.predict_proba(xtest)",
"runcv input: name of train/ test file, classifier 1 and 2 to be",
"provided that the following conditions are met: 1. Redistributions of source code must",
"in selectedcols] for row in r] names = [name for name in names",
"names[i] in selectedcols] for row in r] names = [name for name in",
"r: testids.append(row[0]) ###################################################### # general functions def readdata(fname,header=True,selectedcols=None): with open(fname,'r') as f: r=csv.reader(f)",
"xtest,_=readdata('test_%s'%filename) c1.fit(xtrain,labels) c2.fit(xtrain,labels) p1=c1.predict_proba(xtest) p2=c2.predict_proba(xtest) p=0.667*p1+0.333*p2 with open('subm_%s'%filename,'w') as f: w=csv.writer(f) w.writerow(['Id']+['Prediction%d'%num for",
"CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR",
"OF SUCH DAMAGE. \"\"\" #first run feature_extraction.py #then run this file from the",
"NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,",
"def writesubm(filename,c1,c2): xtrain,names=readdata('train_%s'%filename) xtest,_=readdata('test_%s'%filename) c1.fit(xtrain,labels) c2.fit(xtrain,labels) p1=c1.predict_proba(xtest) p2=c2.predict_proba(xtest) p=0.667*p1+0.333*p2 with open('subm_%s'%filename,'w') as f:",
"import KFold from sklearn.ensemble import GradientBoostingClassifier,ExtraTreesClassifier from sklearn.metrics import log_loss ###################################################### # list",
"function writesubm input: name of train/ test file, classifier 1 and 2 to",
"###################################################### # go if __name__ == '__main__': gbm=GradientBoostingClassifier( n_estimators=400, max_features=5) xtr=ExtraTreesClassifier( n_estimators=400,max_features=None, min_samples_leaf=2,min_samples_split=3,",
"return pred \"\"\" function runcv input: name of train/ test file, classifier 1",
"go if __name__ == '__main__': gbm=GradientBoostingClassifier( n_estimators=400, max_features=5) xtr=ExtraTreesClassifier( n_estimators=400,max_features=None, min_samples_leaf=2,min_samples_split=3, n_jobs=7) for",
"DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS",
"ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING",
"other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT",
"A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR",
"are met: 1. Redistributions of source code must retain the above copyright notice,",
"WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO",
"PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE",
"f: r=csv.reader(f) r.next() # skip header for row in r: trainids.append(row[0]) labels.append(float(row[1])) testids=[]",
"source and binary forms, with or without modification, are permitted provided that the",
"SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)",
"SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND",
"OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)",
"from the same directory ###################################################### # import dependencies import csv import numpy as",
"row in pcombi: w.writerow(row) ###################################################### # submit and print feature importance \"\"\" function",
"row in r] return data,names def writedata(data,fname,header=None): with open(fname,'w') as f: w=csv.writer(f) if",
"WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE",
"NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS",
"xtrain,names=readdata('train_%s'%filename) xtest,_=readdata('test_%s'%filename) c1.fit(xtrain,labels) c2.fit(xtrain,labels) p1=c1.predict_proba(xtest) p2=c2.predict_proba(xtest) p=0.667*p1+0.333*p2 with open('subm_%s'%filename,'w') as f: w=csv.writer(f) w.writerow(['Id']+['Prediction%d'%num",
"writes holdout-set-predictions for all rows to file * run cross validation by calling",
"row in r: trainids.append(row[0]) labels.append(float(row[1])) testids=[] with open('sampleSubmission.csv','r') as f: r=csv.reader(f) r.next() for",
"clf.predict_proba(x[testidx]) return pred \"\"\" function runcv input: name of train/ test file, classifier",
"create testset predictions, combine and save results \"\"\" def writesubm(filename,c1,c2): xtrain,names=readdata('train_%s'%filename) xtest,_=readdata('test_%s'%filename) c1.fit(xtrain,labels)",
"max_features=5) xtr=ExtraTreesClassifier( n_estimators=400,max_features=None, min_samples_leaf=2,min_samples_split=3, n_jobs=7) for filename in [ '45c.csv', ]: print filename",
"c1.fit(xtrain,labels) c2.fit(xtrain,labels) p1=c1.predict_proba(xtest) p2=c2.predict_proba(xtest) p=0.667*p1+0.333*p2 with open('subm_%s'%filename,'w') as f: w=csv.writer(f) w.writerow(['Id']+['Prediction%d'%num for num",
"import log_loss ###################################################### # list ids and labels trainids=[] labels=[] with open('trainLabels.csv','r') as",
"in names if name in selectedcols] else: data = [[float(e) for e in",
"USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.",
"AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED",
"if names[i] in selectedcols] for row in r] names = [name for name",
"header for row in r: trainids.append(row[0]) labels.append(float(row[1])) testids=[] with open('sampleSubmission.csv','r') as f: r=csv.reader(f)",
"with open('trainLabels.csv','r') as f: r=csv.reader(f) r.next() # skip header for row in r:",
"WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN",
"# import dependencies import csv import numpy as np from sklearn.cross_validation import KFold",
"open(fname,'w') as f: w=csv.writer(f) if header: w.writerow(header) for row in data: w.writerow(row) ######################################################",
"test file, classifier 1 and 2 to be used output: writes testset predictions",
"###################################################### # list ids and labels trainids=[] labels=[] with open('trainLabels.csv','r') as f: r=csv.reader(f)",
"ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. \"\"\" #first run feature_extraction.py #then run",
"pcombi: w.writerow(row) ###################################################### # submit and print feature importance \"\"\" function writesubm input:",
"open('pred_%s'%filename,'w') as f: w=csv.writer(f) for row in pcombi: w.writerow(row) ###################################################### # submit and",
"in row] for row in r] return data,names def writedata(data,fname,header=None): with open(fname,'w') as",
"import GradientBoostingClassifier,ExtraTreesClassifier from sklearn.metrics import log_loss ###################################################### # list ids and labels trainids=[]",
"OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN",
"== '__main__': gbm=GradientBoostingClassifier( n_estimators=400, max_features=5) xtr=ExtraTreesClassifier( n_estimators=400,max_features=None, min_samples_leaf=2,min_samples_split=3, n_jobs=7) for filename in [",
"min_samples_leaf=2,min_samples_split=3, n_jobs=7) for filename in [ '45c.csv', ]: print filename runcv(filename,gbm,xtr) writesubm(filename,gbm,xtr) print",
"rows output: holdout-set-predictions for all rows * run cross validation \"\"\" def docv(clf,kf,x,y,nrow,nlab=9):",
"classifiers using all traindata, create testset predictions, combine and save results \"\"\" def",
"in data: w.writerow(row) ###################################################### # cross validation \"\"\" function docv input: classifier, kfolds",
"AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE",
"validation by calling docv for both classifiers, combine and save results \"\"\" def",
"POSSIBILITY OF SUCH DAMAGE. \"\"\" #first run feature_extraction.py #then run this file from",
"with open('subm_%s'%filename,'w') as f: w=csv.writer(f) w.writerow(['Id']+['Prediction%d'%num for num in xrange(1,10)]) for inum,i in",
"data = [[float(e) for i,e in enumerate(row) if names[i] in selectedcols] for row",
"kf = KFold(nrow,10,shuffle=True) p1=docv(c1,kf,x,y,nrow) p2=docv(c2,kf,x,y,nrow) pcombi=0.667*p1+0.333*p2 print '%.4f %.4f %.4f'%(log_loss(y,p1),log_loss(y,p2),log_loss(y,pcombi)) with open('pred_%s'%filename,'w') as",
"data: w.writerow(row) ###################################################### # cross validation \"\"\" function docv input: classifier, kfolds object,",
"selectedcols] for row in r] names = [name for name in names if",
"with open('pred_%s'%filename,'w') as f: w=csv.writer(f) for row in pcombi: w.writerow(row) ###################################################### # submit",
"testset predictions to file * train classifiers using all traindata, create testset predictions,",
"# list ids and labels trainids=[] labels=[] with open('trainLabels.csv','r') as f: r=csv.reader(f) r.next()",
"pred[testidx] = clf.predict_proba(x[testidx]) return pred \"\"\" function runcv input: name of train/ test",
"x=np.array(x) kf = KFold(nrow,10,shuffle=True) p1=docv(c1,kf,x,y,nrow) p2=docv(c2,kf,x,y,nrow) pcombi=0.667*p1+0.333*p2 print '%.4f %.4f %.4f'%(log_loss(y,p1),log_loss(y,p2),log_loss(y,pcombi)) with open('pred_%s'%filename,'w')",
"1 and 2 to be used output: writes testset predictions to file *",
"r.next() if header else None if selectedcols: assert header==True data = [[float(e) for",
"f: r=csv.reader(f) names = r.next() if header else None if selectedcols: assert header==True",
"f: w=csv.writer(f) w.writerow(['Id']+['Prediction%d'%num for num in xrange(1,10)]) for inum,i in enumerate(testids): w.writerow([i]+list(p[inum])) ######################################################",
"the following conditions are met: 1. Redistributions of source code must retain the",
"row] for row in r] return data,names def writedata(data,fname,header=None): with open(fname,'w') as f:"
] |
[
"fail.\") assert msg in str(err.value) @pytest.mark.parametrize( \"version, purpose, key\", [ (1, \"public\", load_key(\"keys/public_key_rsa.pem\")),",
"@pytest.mark.parametrize( \"version, purpose, key, msg\", [ (\"v*\", \"local\", token_bytes(32), \"Invalid version: v*.\"), (\"v0\",",
"Key.from_paserk(paserk) pytest.fail(\"Key.from_paserk should fail.\") assert msg in str(err.value) @pytest.mark.parametrize( \"version\", [ 1, 2,",
"\"public\", load_key(\"keys/public_key_rsa.pem\")), (2, \"public\", load_key(\"keys/public_key_ed25519.pem\")), (3, \"public\", load_key(\"keys/public_key_ecdsa_p384.pem\")), (4, \"public\", load_key(\"keys/public_key_ed25519.pem\")), ], )",
"key) wk = token_bytes(32) with pytest.raises(ValueError) as err: k.to_paserk(password=wk) pytest.fail(\"to_paserk() should fail.\") assert",
"\"A key for public does not have decrypt().\" in str(err.value) @pytest.mark.parametrize( \"version, key,",
"( 4, {\"x\": b\"xxx\", \"y\": b\"\", \"d\": b\"ddd\"}, \"Only one of x or",
"as err: Key.from_paserk(paserk, password=\"<PASSWORD>\") pytest.fail(\"Key.from_paserk should fail.\") assert msg in str(err.value) @pytest.mark.parametrize( \"paserk,",
"key cannot be wrapped.\" in str(err.value) @pytest.mark.parametrize( \"version, key, msg\", [ ( 1,",
"should be set for v2.public.\", ), ( 3, {\"x\": b\"xxx\", \"y\": b\"\", \"d\":",
"(2, \"local\", token_bytes(32)), (3, \"local\", token_bytes(32)), (4, \"local\", token_bytes(32)), ], ) def test_key_new_local(self,",
"test_key_new_with_invalid_arg(self, version, purpose, key, msg): with pytest.raises(ValueError) as err: Key.new(version, purpose, key) pytest.fail(\"Key.new",
"\"The key is not Ed25519 key.\"), ( 2, load_key(\"keys/private_key_ecdsa_p384.pem\"), \"The key is not",
"def test_key_from_paserk_with_password_for_wrong_paserk(self, paserk, msg): with pytest.raises(ValueError) as err: Key.from_paserk(paserk, password=\"<PASSWORD>\") pytest.fail(\"Key.from_paserk should fail.\")",
"be set for v2.public.\", ), ( 3, {\"x\": b\"xxx\", \"y\": b\"\", \"d\": b\"ddd\"},",
"k = Key.new(version, \"public\", key) wk1 = token_bytes(32) wk2 = token_bytes(32) wpk =",
"(4, load_key(\"keys/public_key_ed25519.pem\")), ], ) def test_key_from_paserk_for_public_key_with_password(self, version, key): k = Key.new(version, \"public\", key)",
"\"public\", load_key(\"keys/public_key_ed25519.pem\")), (3, \"public\", load_key(\"keys/public_key_ecdsa_p384.pem\")), (4, \"public\", load_key(\"keys/public_key_ed25519.pem\")), ], ) def test_key_to_paserk_public(self, version,",
"for public does not have decrypt().\" in str(err.value) @pytest.mark.parametrize( \"version, key, msg\", [",
"), ( 1, load_key(\"keys/public_key_ecdsa_p384.pem\"), \"The key is not RSA key.\", ), (2, load_key(\"keys/private_key_rsa.pem\"),",
"PASERK key type: xxx.\"), ], ) def test_key_from_paserk_with_invalid_args(self, paserk, msg): with pytest.raises(ValueError) as",
"(4, \"local\", token_bytes(32)), (1, \"public\", load_key(\"keys/private_key_rsa.pem\")), (2, \"public\", load_key(\"keys/private_key_ed25519.pem\")), (3, \"public\", load_key(\"keys/private_key_ecdsa_p384.pem\")), (4,",
"( 3, { \"x\": base64url_decode(\"_XyN9woHaS0mPimSW-etwJMEDSzxIMjp4PjezavU8SHJoClz1bQrcmPb1ZJxHxhI\"), \"y\": base64url_decode(\"<KEY>\"), \"d\": b\"ddd\", }, \"Failed to load",
"purpose with pytest.raises(NotSupportedError) as err: k.sign(b\"Hello world!\") pytest.fail(\"Key.sign() should fail.\") assert \"A key",
"k.encrypt(b\"Hello world!\") pytest.fail(\"Key.sign() should fail.\") assert \"A key for public does not have",
"], ) def test_key_from_asymmetric_params(self, version, key): k = Key.from_asymmetric_key_params(version, x=key[\"x\"], y=key[\"y\"], d=key[\"d\"]) assert",
"pytest.raises(DecryptError) as err: Key.from_paserk(wpk, wrapping_key=wk2) pytest.fail(\"Key.from_paserk() should fail.\") assert \"Failed to unwrap a",
"@pytest.mark.parametrize( \"version, key, msg\", [ ( 1, load_jwk(\"keys/private_key_rsa.json\"), \"v1.public is not supported on",
"( 3, {\"x\": b\"xxx\", \"y\": b\"\", \"d\": b\"ddd\"}, \"x and y (and d)",
"key) pytest.fail(\"Key.new should fail.\") assert msg in str(err.value) @pytest.mark.parametrize( \"version, key\", [ #",
"load key.\"), ( 2, {\"x\": b\"\", \"y\": b\"\", \"d\": b\"\"}, \"x or d",
"should be set for v2.public.\", ), (2, {\"x\": b\"xxx\", \"y\": b\"\", \"d\": b\"\"},",
"load_jwk(\"keys/private_key_ed25519.json\"), \"Invalid version: 999.\"), (0, load_jwk(\"keys/private_key_ed25519.json\"), \"Invalid version: 0.\"), ( 2, {\"x\": b\"xxx\",",
"class TestKey: \"\"\" Tests for Key. \"\"\" @pytest.mark.parametrize( \"version, purpose, key\", [ (1,",
"public does not have decrypt().\" in str(err.value) @pytest.mark.parametrize( \"version, key, msg\", [ (1,",
"to unwrap a key.\" in str(err.value) @pytest.mark.parametrize( \"version, key\", [ (1, load_key(\"keys/public_key_rsa.pem\")), (2,",
"as err: Key.from_paserk(paserk, wrapping_key=\"xxx\", password=\"<PASSWORD>\") pytest.fail(\"Key.from_paserk should fail.\") assert \"Only one of wrapping_key",
"from secrets import token_bytes import pytest from pyseto import DecryptError, Key, NotSupportedError from",
"k.purpose == purpose with pytest.raises(NotSupportedError) as err: k.encrypt(b\"Hello world!\") pytest.fail(\"Key.sign() should fail.\") assert",
"PASERK type: public.\"), (\"k3.local.AAAAAAAAAAAAAAAA\", \"Invalid PASERK type: local.\"), (\"k3.public.AAAAAAAAAAAAAAAA\", \"Invalid PASERK type: public.\"),",
"in str(err.value) @pytest.mark.parametrize( \"version, key, msg\", [ (1, load_key(\"keys/private_key_ed25519.pem\"), \"The key is not",
"key.\"), (2, load_key(\"keys/public_key_rsa.pem\"), \"The key is not Ed25519 key.\"), ( 2, load_key(\"keys/private_key_ecdsa_p384.pem\"), \"The",
"should fail.\") assert \"Failed to unwrap a key.\" in str(err.value) @pytest.mark.parametrize( \"version, key\",",
"\"x and y (and d) should be set for v3.public.\", ), (3, {\"x\":",
"\"public\", load_key(\"keys/private_key_ecdsa_p384.pem\")), (4, \"public\", load_key(\"keys/private_key_ed25519.pem\")), ], ) def test_key_to_paserk_secret_with_wrapping_key_and_password(self, version, purpose, key): k",
"from pyseto.utils import base64url_decode from .utils import load_jwk, load_key class TestKey: \"\"\" Tests",
"key): k = Key.new(version, purpose, key) assert k.to_paserk().startswith(f\"k{k.version}.secret.\") @pytest.mark.parametrize( \"version, purpose, key\", [",
"\"Public key cannot be wrapped.\" in str(err.value) @pytest.mark.parametrize( \"version, key, msg\", [ (",
"key is not Ed25519 key.\"), ( 4, load_key(\"keys/private_key_ecdsa_p384.pem\"), \"The key is not Ed25519",
"k.decrypt(b\"xxxxxx\") pytest.fail(\"Key.verify() should fail.\") assert \"A key for public does not have decrypt().\"",
"\"Invalid PASERK type: local.\"), (\"k2.public.AAAAAAAAAAAAAAAA\", \"Invalid PASERK type: public.\"), (\"k3.local.AAAAAAAAAAAAAAAA\", \"Invalid PASERK type:",
"[ (1, load_key(\"keys/private_key_rsa.pem\")), (2, load_key(\"keys/private_key_ed25519.pem\")), (3, load_key(\"keys/private_key_ecdsa_p384.pem\")), (4, load_key(\"keys/private_key_ed25519.pem\")), ], ) def test_key_from_paserk_for_private_key_with_wrong_wrapping_key(self,",
"should fail.\") assert \"A key for local does not have verify().\" in str(err.value)",
"key\", [ (1, \"public\", load_key(\"keys/private_key_rsa.pem\")), (1, \"public\", load_key(\"keys/public_key_rsa.pem\")), (2, \"public\", load_key(\"keys/private_key_ed25519.pem\")), (2, \"public\",",
"\"Failed to load key.\"), (2, {\"x\": b\"\", \"y\": b\"\", \"d\": b\"ddd\"}, \"Failed to",
"to load key.\"), ( 2, {\"x\": b\"\", \"y\": b\"\", \"d\": b\"\"}, \"x or",
"load_jwk(\"keys/private_key_rsa.json\")), # (1, load_jwk(\"keys/public_key_rsa.json\")), (2, load_jwk(\"keys/private_key_ed25519.json\")), (2, load_jwk(\"keys/public_key_ed25519.json\")), (3, load_jwk(\"keys/private_key_ecdsa_p384.json\")), (3, load_jwk(\"keys/public_key_ecdsa_p384.json\")), (4,",
"BAD\", \"Invalid or unsupported PEM format.\"), ], ) def test_key_new_with_invalid_arg(self, version, purpose, key,",
"assert \"Only one of wrapping_key or password should be specified.\" in str(err.value) @pytest.mark.parametrize(",
"or d should be set for v2.public.\", ), (2, {\"x\": b\"xxx\", \"y\": b\"\",",
"wrapping_key=wk2) pytest.fail(\"Key.from_paserk() should fail.\") assert \"Failed to unwrap a key.\" in str(err.value) @pytest.mark.parametrize(",
"as err: Key.from_paserk(wpk, wrapping_key=wk2) pytest.fail(\"Key.from_paserk() should fail.\") assert \"Failed to unwrap a key.\"",
"\"The key is not RSA key.\"), (1, load_key(\"keys/public_key_ed25519.pem\"), \"The key is not RSA",
"PASERK type: local.\"), (\"k2.public.AAAAAAAAAAAAAAAA\", \"Invalid PASERK type: public.\"), (\"k3.local.AAAAAAAAAAAAAAAA\", \"Invalid PASERK type: local.\"),",
"def test_key_to_paserk_secret(self, version, purpose, key): k = Key.new(version, purpose, key) assert k.to_paserk().startswith(f\"k{k.version}.secret.\") @pytest.mark.parametrize(",
"token_bytes(32)), (3, \"local\", token_bytes(32)), (4, \"local\", token_bytes(32)), ], ) def test_key_new_local(self, version, purpose,",
"\"The key is not RSA key.\", ), ( 1, load_key(\"keys/public_key_ecdsa_p384.pem\"), \"The key is",
"load_key(\"keys/public_key_ed25519.pem\")), (3, \"public\", load_key(\"keys/private_key_ecdsa_p384.pem\")), (3, \"public\", load_key(\"keys/public_key_ecdsa_p384.pem\")), (4, \"public\", load_key(\"keys/private_key_ed25519.pem\")), (4, \"public\", load_key(\"keys/public_key_ed25519.pem\")),",
"version, purpose, key): k = Key.new(version, purpose, key) assert isinstance(k, KeyInterface) assert k.version",
"pytest.fail(\"Key.from_paserk should fail.\") assert \"Only one of wrapping_key or password should be specified.\"",
"(\"k1.public.AAAAAAAAAAAAAAAA\", \"Invalid PASERK type: public.\"), (\"k2.local.AAAAAAAAAAAAAAAA\", \"Invalid PASERK type: local.\"), (\"k2.public.AAAAAAAAAAAAAAAA\", \"Invalid PASERK",
"load_key(\"keys/private_key_ed25519.pem\")), (3, \"public\", load_key(\"keys/private_key_ecdsa_p384.pem\")), (4, \"public\", load_key(\"keys/private_key_ed25519.pem\")), ], ) def test_key_to_paserk_secret_with_wrapping_key_and_password(self, version, purpose,",
"v0.\", ), ( 0, \"public\", load_key(\"keys/private_key_rsa.pem\"), \"Invalid version: 0.\", ), (1, \"xxx\", token_bytes(32),",
"key) wk1 = token_bytes(32) wk2 = token_bytes(32) wpk = k.to_paserk(wrapping_key=wk1) with pytest.raises(DecryptError) as",
"y=key[\"y\"], d=key[\"d\"]) pytest.fail(\"Key.from_asymmetric_key_params() should fail.\") assert msg in str(err.value) @pytest.mark.parametrize( \"version, purpose, key\",",
"b\"\", \"d\": b\"ddd\"}, \"Failed to load key.\"), ( 2, {\"x\": b\"\", \"y\": b\"\",",
"\"local\", token_bytes(32)), (4, \"local\", token_bytes(32)), ], ) def test_key_new_local(self, version, purpose, key): k",
"Ed25519 key.\"), ( 2, load_key(\"keys/private_key_ecdsa_p384.pem\"), \"The key is not Ed25519 key.\", ), (",
"\"Only one of x or d should be set for v4.public.\", ), (4,",
"import DecryptError, Key, NotSupportedError from pyseto.key_interface import KeyInterface from pyseto.utils import base64url_decode from",
"== purpose with pytest.raises(NotSupportedError) as err: k.encrypt(b\"Hello world!\") pytest.fail(\"Key.sign() should fail.\") assert \"A",
"load_key(\"keys/public_key_ecdsa_p384.pem\"), \"The key is not RSA key.\", ), (2, load_key(\"keys/private_key_rsa.pem\"), \"The key is",
"\"d\": b\"\"}, \"Failed to load key.\"), (4, {\"x\": b\"\", \"y\": b\"\", \"d\": b\"ddd\"},",
"v*.\"), (\"v0\", \"local\", token_bytes(32), \"Invalid version: v0.\"), (0, \"local\", token_bytes(32), \"Invalid version: 0.\"),",
"\"Failed to load key.\", ), ( 4, {\"x\": b\"xxx\", \"y\": b\"\", \"d\": b\"ddd\"},",
"key) wk = token_bytes(32) with pytest.raises(ValueError) as err: k.to_paserk(wrapping_key=wk) pytest.fail(\"to_paserk() should fail.\") assert",
"y (and d) should be set for v3.public.\", ), (3, {\"x\": b\"xxx\", \"y\":",
"unsupported PEM format.\"), ], ) def test_key_new_with_invalid_arg(self, version, purpose, key, msg): with pytest.raises(ValueError)",
"( 3, {\"x\": b\"\", \"y\": b\"yyy\", \"d\": b\"ddd\"}, \"x and y (and d)",
"err: Key.from_paserk(paserk, wrapping_key=\"xxx\", password=\"<PASSWORD>\") pytest.fail(\"Key.from_paserk should fail.\") assert \"Only one of wrapping_key or",
") def test_key_to_paserk_secret_with_wrapping_key_and_password(self, version, purpose, key): k = Key.new(version, purpose, key) with pytest.raises(ValueError)",
"purpose, key) with pytest.raises(ValueError) as err: k.to_paserk(wrapping_key=\"xxx\", password=\"<PASSWORD>\") pytest.fail(\"to_paserk() should fail.\") assert \"Only",
"key is not ECDSA key.\"), (4, load_key(\"keys/private_key_rsa.pem\"), \"The key is not Ed25519 key.\"),",
"token_bytes(32), \"Invalid version: v0.\"), (0, \"local\", token_bytes(32), \"Invalid version: 0.\"), ( \"v*\", \"public\",",
") def test_key_new_with_invalid_arg(self, version, purpose, key, msg): with pytest.raises(ValueError) as err: Key.new(version, purpose,",
"err: Key.from_paserk(wpk, password=<PASSWORD>) pytest.fail(\"Key.from_paserk() should fail.\") assert \"Failed to unwrap a key.\" in",
"k.to_paserk().startswith(f\"k{k.version}.secret.\") @pytest.mark.parametrize( \"version, purpose, key\", [ (1, \"local\", token_bytes(32)), (2, \"local\", token_bytes(32)), (3,",
"== version assert k.purpose == \"public\" @pytest.mark.parametrize( \"paserk\", [ \"k1.local.AAAAAAAAAAAAAAAA\", \"k1.public.AAAAAAAAAAAAAAAA\", \"k2.local.AAAAAAAAAAAAAAAA\", \"k2.public.AAAAAAAAAAAAAAAA\",",
"key.\"), (3, load_key(\"keys/public_key_rsa.pem\"), \"The key is not ECDSA key.\"), (4, load_key(\"keys/private_key_rsa.pem\"), \"The key",
"], ) def test_key_to_paserk_public(self, version, purpose, key): k = Key.new(version, purpose, key) assert",
"to load key.\", ), ( 4, {\"x\": b\"xxx\", \"y\": b\"\", \"d\": b\"ddd\"}, \"Only",
"type: local.\"), (\"k4.public.AAAAAAAAAAAAAAAA\", \"Invalid PASERK type: public.\"), ], ) def test_key_from_paserk_with_password_for_wrong_paserk(self, paserk, msg):",
"load_key(\"keys/private_key_ed25519.pem\")), (4, \"public\", load_key(\"keys/public_key_ed25519.pem\")), ], ) def test_key_new_public(self, version, purpose, key): k =",
"== \"public\" @pytest.mark.parametrize( \"paserk\", [ \"k1.local.AAAAAAAAAAAAAAAA\", \"k1.public.AAAAAAAAAAAAAAAA\", \"k2.local.AAAAAAAAAAAAAAAA\", \"k2.public.AAAAAAAAAAAAAAAA\", \"k3.local.AAAAAAAAAAAAAAAA\", \"k3.public.AAAAAAAAAAAAAAAA\", \"k4.local.AAAAAAAAAAAAAAAA\", \"k4.public.AAAAAAAAAAAAAAAA\",",
"\"x and y (and d) should be set for v3.public.\", ), ( 3,",
"\"public\", \"-----BEGIN BAD\", \"Invalid or unsupported PEM format.\"), ], ) def test_key_new_with_invalid_arg(self, version,",
"import base64url_decode from .utils import load_jwk, load_key class TestKey: \"\"\" Tests for Key.",
"@pytest.mark.parametrize( \"version, purpose, key\", [ (1, \"public\", load_key(\"keys/public_key_rsa.pem\")), (2, \"public\", load_key(\"keys/public_key_ed25519.pem\")), (3, \"public\",",
"should fail.\") assert msg in str(err.value) @pytest.mark.parametrize( \"paserk, msg\", [ (\"v1.local.AAAAAAAAAAAAAAAA\", \"Invalid PASERK",
"b\"ddd\"}, \"Failed to load key.\"), ( 2, {\"x\": b\"\", \"y\": b\"\", \"d\": b\"\"},",
"load_key(\"keys/private_key_rsa.pem\")), (2, load_key(\"keys/private_key_ed25519.pem\")), (3, load_key(\"keys/private_key_ecdsa_p384.pem\")), (4, load_key(\"keys/private_key_ed25519.pem\")), ], ) def test_key_from_paserk_for_private_key_with_wrong_wrapping_key(self, version, key):",
"(and d) should be set for v3.public.\", ), (3, {\"x\": b\"xxx\", \"y\": b\"yyy\",",
"== version assert k.purpose == purpose with pytest.raises(NotSupportedError) as err: k.encrypt(b\"Hello world!\") pytest.fail(\"Key.sign()",
"(4, \"local\", token_bytes(32)), ], ) def test_key_new_local(self, version, purpose, key): k = Key.new(version,",
"\"The key is not Ed25519 key.\"), ( 4, load_key(\"keys/private_key_ecdsa_p384.pem\"), \"The key is not",
"2, load_key(\"keys/public_key_ecdsa_p384.pem\"), \"The key is not Ed25519 key.\", ), ( 3, load_key(\"keys/private_key_ed25519.pem\"), \"The",
"have decrypt().\" in str(err.value) @pytest.mark.parametrize( \"version, key, msg\", [ (1, load_key(\"keys/private_key_ed25519.pem\"), \"The key",
"public.\"), (\"k2.local.AAAAAAAAAAAAAAAA\", \"Invalid PASERK type: local.\"), (\"k2.public.AAAAAAAAAAAAAAAA\", \"Invalid PASERK type: public.\"), (\"k3.local.AAAAAAAAAAAAAAAA\", \"Invalid",
"should fail.\") assert msg in str(err.value) @pytest.mark.parametrize( \"version, purpose, key, msg\", [ (\"v*\",",
"test_key_from_asymmetric_params(self, version, key): k = Key.from_asymmetric_key_params(version, x=key[\"x\"], y=key[\"y\"], d=key[\"d\"]) assert isinstance(k, KeyInterface) assert",
"str(err.value) @pytest.mark.parametrize( \"version, key, msg\", [ ( 1, load_jwk(\"keys/private_key_rsa.json\"), \"v1.public is not supported",
"pytest.fail(\"Key.new should fail.\") assert msg in str(err.value) @pytest.mark.parametrize( \"version, key\", [ # (1,",
"assert \"A key for local does not have verify().\" in str(err.value) @pytest.mark.parametrize( \"version,",
") def test_key_from_asymmetric_params_with_invalid_arg(self, version, key, msg): with pytest.raises(ValueError) as err: Key.from_asymmetric_key_params(version, x=key[\"x\"], y=key[\"y\"],",
") def test_key_to_paserk_public(self, version, purpose, key): k = Key.new(version, purpose, key) assert k.to_paserk().startswith(f\"k{k.version}.public.\")",
"key, msg): with pytest.raises(ValueError) as err: Key.new(version, purpose, key) pytest.fail(\"Key.new should fail.\") assert",
"(2, {\"x\": b\"\", \"y\": b\"\", \"d\": b\"ddd\"}, \"Failed to load key.\"), ( 2,",
"Key.from_paserk(wpk, wrapping_key=wk2) pytest.fail(\"Key.from_paserk() should fail.\") assert \"Failed to unwrap a key.\" in str(err.value)",
"(1, load_key(\"keys/public_key_ed25519.pem\"), \"The key is not RSA key.\"), ( 1, load_key(\"keys/private_key_ecdsa_p384.pem\"), \"The key",
"set for v4.public.\", ), (4, {\"x\": b\"xxx\", \"y\": b\"\", \"d\": b\"\"}, \"Failed to",
"d=key[\"d\"]) pytest.fail(\"Key.from_asymmetric_key_params() should fail.\") assert msg in str(err.value) @pytest.mark.parametrize( \"version, purpose, key\", [",
"[ ( 1, load_jwk(\"keys/private_key_rsa.json\"), \"v1.public is not supported on from_key_parameters.\", ), (999, load_jwk(\"keys/private_key_ed25519.json\"),",
"\"Invalid version: 999.\"), (0, load_jwk(\"keys/private_key_ed25519.json\"), \"Invalid version: 0.\"), ( 2, {\"x\": b\"xxx\", \"y\":",
"4, load_key(\"keys/private_key_ecdsa_p384.pem\"), \"The key is not Ed25519 key.\", ), ( 4, load_key(\"keys/public_key_ecdsa_p384.pem\"), \"The",
"str(err.value) @pytest.mark.parametrize( \"version, key\", [ # (1, load_jwk(\"keys/private_key_rsa.json\")), # (1, load_jwk(\"keys/public_key_rsa.json\")), (2, load_jwk(\"keys/private_key_ed25519.json\")),",
"from .utils import load_jwk, load_key class TestKey: \"\"\" Tests for Key. \"\"\" @pytest.mark.parametrize(",
"\"y\": b\"\", \"d\": b\"\"}, \"Failed to load key.\"), (2, {\"x\": b\"\", \"y\": b\"\",",
"\"d\": b\"\"}, \"x or d should be set for v4.public.\", ), ], )",
"does not have decrypt().\" in str(err.value) @pytest.mark.parametrize( \"version, key, msg\", [ (1, load_key(\"keys/private_key_ed25519.pem\"),",
"key\", [ (1, load_key(\"keys/public_key_rsa.pem\")), (2, load_key(\"keys/public_key_ed25519.pem\")), (3, load_key(\"keys/public_key_ecdsa_p384.pem\")), (4, load_key(\"keys/public_key_ed25519.pem\")), ], ) def",
"\"The key is not ECDSA key.\", ), (3, load_key(\"keys/private_key_rsa.pem\"), \"The key is not",
"(\"k1.local.AAAAAAAAAAAAAAAA\", \"Invalid PASERK type: local.\"), (\"k1.public.AAAAAAAAAAAAAAAA\", \"Invalid PASERK type: public.\"), (\"k2.local.AAAAAAAAAAAAAAAA\", \"Invalid PASERK",
"token_bytes(32)), (2, \"local\", token_bytes(32)), (3, \"local\", token_bytes(32)), (4, \"local\", token_bytes(32)), ], ) def",
"(4, load_key(\"keys/public_key_rsa.pem\"), \"The key is not Ed25519 key.\"), ( 4, load_key(\"keys/private_key_ecdsa_p384.pem\"), \"The key",
"str(err.value) @pytest.mark.parametrize( \"version, purpose, key, msg\", [ (\"v*\", \"local\", token_bytes(32), \"Invalid version: v*.\"),",
"Key.new(version, \"public\", key) wk = token_bytes(32) with pytest.raises(ValueError) as err: k.to_paserk(password=wk) pytest.fail(\"to_paserk() should",
"\"public\", load_key(\"keys/private_key_rsa.pem\")), (2, \"public\", load_key(\"keys/private_key_ed25519.pem\")), (3, \"public\", load_key(\"keys/private_key_ecdsa_p384.pem\")), (4, \"public\", load_key(\"keys/private_key_ed25519.pem\")), ], )",
"for v2.public.\", ), ( 3, {\"x\": b\"xxx\", \"y\": b\"\", \"d\": b\"ddd\"}, \"x and",
"\"y\": b\"yyy\", \"d\": b\"\"}, \"Failed to load key.\"), ( 3, { \"x\": base64url_decode(\"_XyN9woHaS0mPimSW-etwJMEDSzxIMjp4PjezavU8SHJoClz1bQrcmPb1ZJxHxhI\"),",
"(3, \"local\", token_bytes(32)), (4, \"local\", token_bytes(32)), (1, \"public\", load_key(\"keys/private_key_rsa.pem\")), (2, \"public\", load_key(\"keys/private_key_ed25519.pem\")), (3,",
"paserk, msg): with pytest.raises(ValueError) as err: Key.from_paserk(paserk) pytest.fail(\"Key.from_paserk should fail.\") assert msg in",
"version): k = Key.new(version, \"local\", token_bytes(32)) wk1 = token_bytes(32) wk2 = token_bytes(32) wpk",
"load key.\"), (2, {\"x\": b\"\", \"y\": b\"\", \"d\": b\"ddd\"}, \"Failed to load key.\"),",
"str(err.value) @pytest.mark.parametrize( \"paserk, msg\", [ (\"v1.local.AAAAAAAAAAAAAAAA\", \"Invalid PASERK version: v1.\"), (\"*.local.AAAAAAAAAAAAAAAA\", \"Invalid PASERK",
"purpose, key) assert isinstance(k, KeyInterface) assert k.version == version assert k.purpose == purpose",
"k.to_paserk(wrapping_key=\"xxx\", password=\"<PASSWORD>\") pytest.fail(\"to_paserk() should fail.\") assert \"Only one of wrapping_key or password should",
"def test_key_from_asymmetric_params_with_invalid_arg(self, version, key, msg): with pytest.raises(ValueError) as err: Key.from_asymmetric_key_params(version, x=key[\"x\"], y=key[\"y\"], d=key[\"d\"])",
"should fail.\") assert \"A key for local does not have sign().\" in str(err.value)",
"token_bytes(32) wk2 = token_bytes(32) wpk = k.to_paserk(password=wk1) with pytest.raises(DecryptError) as err: Key.from_paserk(wpk, password=<PASSWORD>)",
"key.\" in str(err.value) @pytest.mark.parametrize( \"version, key\", [ (1, load_key(\"keys/private_key_rsa.pem\")), (2, load_key(\"keys/private_key_ed25519.pem\")), (3, load_key(\"keys/private_key_ecdsa_p384.pem\")),",
"and y (and d) should be set for v3.public.\", ), ( 3, {\"x\":",
"), (3, load_key(\"keys/private_key_rsa.pem\"), \"The key is not ECDSA key.\"), (3, load_key(\"keys/public_key_rsa.pem\"), \"The key",
"], ) def test_key_from_asymmetric_params_with_invalid_arg(self, version, key, msg): with pytest.raises(ValueError) as err: Key.from_asymmetric_key_params(version, x=key[\"x\"],",
"for v4.public.\", ), ], ) def test_key_from_asymmetric_params_with_invalid_arg(self, version, key, msg): with pytest.raises(ValueError) as",
"pytest.raises(ValueError) as err: Key.from_paserk(paserk, wrapping_key=\"xxx\", password=\"<PASSWORD>\") pytest.fail(\"Key.from_paserk should fail.\") assert \"Only one of",
"should fail.\") assert \"Failed to unwrap a key.\" in str(err.value) @pytest.mark.parametrize( \"version\", [",
"version assert k.purpose == purpose with pytest.raises(NotSupportedError) as err: k.encrypt(b\"Hello world!\") pytest.fail(\"Key.sign() should",
"is not Ed25519 key.\"), (2, load_key(\"keys/public_key_rsa.pem\"), \"The key is not Ed25519 key.\"), (",
"load_key(\"keys/private_key_rsa.pem\")), (2, \"public\", load_key(\"keys/private_key_ed25519.pem\")), (3, \"public\", load_key(\"keys/private_key_ecdsa_p384.pem\")), (4, \"public\", load_key(\"keys/private_key_ed25519.pem\")), ], ) def",
"type: public.\"), ], ) def test_key_from_paserk_with_password_for_wrong_paserk(self, paserk, msg): with pytest.raises(ValueError) as err: Key.from_paserk(paserk,",
"], ) def test_key_from_paserk_for_private_key_with_wrong_wrapping_key(self, version, key): k = Key.new(version, \"public\", key) wk1 =",
"k.to_paserk(password=wk) pytest.fail(\"to_paserk() should fail.\") assert \"Public key cannot be wrapped.\" in str(err.value) @pytest.mark.parametrize(",
"PASERK version: v1.\"), (\"*.local.AAAAAAAAAAAAAAAA\", \"Invalid PASERK version: *.\"), (\"k1.xxx.AAAAAAAAAAAAAAAA\", \"Invalid PASERK key type:",
"purpose, key): k = Key.new(version, purpose, key) assert isinstance(k, KeyInterface) assert k.version ==",
"msg\", [ (\"v*\", \"local\", token_bytes(32), \"Invalid version: v*.\"), (\"v0\", \"local\", token_bytes(32), \"Invalid version:",
"key is not Ed25519 key.\"), (2, load_key(\"keys/public_key_rsa.pem\"), \"The key is not Ed25519 key.\"),",
"def test_key_new_public_with_wrong_key(self, version, key, msg): with pytest.raises(ValueError) as err: Key.new(version, \"public\", key) pytest.fail(\"Key.new",
"import token_bytes import pytest from pyseto import DecryptError, Key, NotSupportedError from pyseto.key_interface import",
"], ) def test_key_from_paserk_with_invalid_args(self, paserk, msg): with pytest.raises(ValueError) as err: Key.from_paserk(paserk) pytest.fail(\"Key.from_paserk should",
"\"Invalid PASERK type: public.\"), (\"k2.local.AAAAAAAAAAAAAAAA\", \"Invalid PASERK type: local.\"), (\"k2.public.AAAAAAAAAAAAAAAA\", \"Invalid PASERK type:",
"local.\"), (\"k3.public.AAAAAAAAAAAAAAAA\", \"Invalid PASERK type: public.\"), (\"k4.local.AAAAAAAAAAAAAAAA\", \"Invalid PASERK type: local.\"), (\"k4.public.AAAAAAAAAAAAAAAA\", \"Invalid",
"@pytest.mark.parametrize( \"version\", [ 1, 2, 3, 4, ], ) def test_key_from_paserk_for_local_with_wrong_wrapping_key(self, version): k",
"def test_key_from_paserk_for_local_with_wrong_wrapping_key(self, version): k = Key.new(version, \"local\", token_bytes(32)) wk1 = token_bytes(32) wk2 =",
"Key.new(version, \"public\", key) wk = token_bytes(32) with pytest.raises(ValueError) as err: k.to_paserk(wrapping_key=wk) pytest.fail(\"to_paserk() should",
"v4.public.\", ), ], ) def test_key_from_asymmetric_params_with_invalid_arg(self, version, key, msg): with pytest.raises(ValueError) as err:",
"\"public\", load_key(\"keys/private_key_ed25519.pem\")), ], ) def test_key_to_paserk_secret_with_wrapping_key_and_password(self, version, purpose, key): k = Key.new(version, purpose,",
"str(err.value) @pytest.mark.parametrize( \"version\", [ 1, 2, 3, 4, ], ) def test_key_from_paserk_for_local_with_wrong_password(self, version):",
"is not RSA key.\"), ( 1, load_key(\"keys/private_key_ecdsa_p384.pem\"), \"The key is not RSA key.\",",
"key): k = Key.from_asymmetric_key_params(version, x=key[\"x\"], y=key[\"y\"], d=key[\"d\"]) assert isinstance(k, KeyInterface) assert k.version ==",
"assert \"Failed to unwrap a key.\" in str(err.value) @pytest.mark.parametrize( \"version\", [ 1, 2,",
"\"local\", token_bytes(32)) wk1 = token_bytes(32) wk2 = token_bytes(32) wpk = k.to_paserk(password=wk1) with pytest.raises(DecryptError)",
"\"y\": base64url_decode(\"<KEY>\"), \"d\": b\"ddd\", }, \"Failed to load key.\", ), ( 4, {\"x\":",
"@pytest.mark.parametrize( \"version, key\", [ (1, load_key(\"keys/public_key_rsa.pem\")), (2, load_key(\"keys/public_key_ed25519.pem\")), (3, load_key(\"keys/public_key_ecdsa_p384.pem\")), (4, load_key(\"keys/public_key_ed25519.pem\")), ],",
"<filename>tests/test_key.py from secrets import token_bytes import pytest from pyseto import DecryptError, Key, NotSupportedError",
"with pytest.raises(ValueError) as err: Key.new(version, \"public\", key) pytest.fail(\"Key.new should fail.\") assert msg in",
"key type: xxx.\"), ], ) def test_key_from_paserk_with_invalid_args(self, paserk, msg): with pytest.raises(ValueError) as err:",
"type: local.\"), (\"k3.public.AAAAAAAAAAAAAAAA\", \"Invalid PASERK type: public.\"), (\"k4.local.AAAAAAAAAAAAAAAA\", \"Invalid PASERK type: local.\"), (\"k4.public.AAAAAAAAAAAAAAAA\",",
"base64url_decode from .utils import load_jwk, load_key class TestKey: \"\"\" Tests for Key. \"\"\"",
"\"Invalid version: v*.\", ), ( \"v0\", \"public\", load_key(\"keys/private_key_rsa.pem\"), \"Invalid version: v0.\", ), (",
"load_key(\"keys/public_key_rsa.pem\")), (2, load_key(\"keys/public_key_ed25519.pem\")), (3, load_key(\"keys/public_key_ecdsa_p384.pem\")), (4, load_key(\"keys/public_key_ed25519.pem\")), ], ) def test_key_from_paserk_for_public_key_with_password(self, version, key):",
"= Key.new(version, purpose, key) assert k.to_paserk().startswith(f\"k{k.version}.secret.\") @pytest.mark.parametrize( \"version, purpose, key\", [ (1, \"local\",",
"key is not RSA key.\", ), (2, load_key(\"keys/private_key_rsa.pem\"), \"The key is not Ed25519",
"load_jwk(\"keys/private_key_rsa.json\"), \"v1.public is not supported on from_key_parameters.\", ), (999, load_jwk(\"keys/private_key_ed25519.json\"), \"Invalid version: 999.\"),",
"key.\"), ( 4, {\"x\": b\"\", \"y\": b\"\", \"d\": b\"\"}, \"x or d should",
"with pytest.raises(ValueError) as err: Key.from_paserk(paserk) pytest.fail(\"Key.from_paserk should fail.\") assert msg in str(err.value) @pytest.mark.parametrize(",
"( 4, {\"x\": b\"\", \"y\": b\"\", \"d\": b\"\"}, \"x or d should be",
"\"The key is not RSA key.\", ), (2, load_key(\"keys/private_key_rsa.pem\"), \"The key is not",
"not have encrypt().\" in str(err.value) with pytest.raises(NotSupportedError) as err: k.decrypt(b\"xxxxxx\") pytest.fail(\"Key.verify() should fail.\")",
"test_key_from_paserk_with_wrapping_key_and_password(self, paserk): with pytest.raises(ValueError) as err: Key.from_paserk(paserk, wrapping_key=\"xxx\", password=\"<PASSWORD>\") pytest.fail(\"Key.from_paserk should fail.\") assert",
"= token_bytes(32) wpk = k.to_paserk(wrapping_key=wk1) with pytest.raises(DecryptError) as err: Key.from_paserk(wpk, wrapping_key=wk2) pytest.fail(\"Key.from_paserk() should",
"with pytest.raises(NotSupportedError) as err: k.decrypt(b\"xxxxxx\") pytest.fail(\"Key.verify() should fail.\") assert \"A key for public",
"\"d\": b\"ddd\"}, \"x and y (and d) should be set for v3.public.\", ),",
"one of x or d should be set for v4.public.\", ), (4, {\"x\":",
"specified.\" in str(err.value) @pytest.mark.parametrize( \"paserk, msg\", [ (\"k1.local.AAAAAAAAAAAAAAAA\", \"Invalid PASERK type: local.\"), (\"k1.public.AAAAAAAAAAAAAAAA\",",
"key, msg): with pytest.raises(ValueError) as err: Key.new(version, \"public\", key) pytest.fail(\"Key.new should fail.\") assert",
"token_bytes import pytest from pyseto import DecryptError, Key, NotSupportedError from pyseto.key_interface import KeyInterface",
"key for public does not have decrypt().\" in str(err.value) @pytest.mark.parametrize( \"version, key, msg\",",
"PASERK type: local.\"), (\"k1.public.AAAAAAAAAAAAAAAA\", \"Invalid PASERK type: public.\"), (\"k2.local.AAAAAAAAAAAAAAAA\", \"Invalid PASERK type: local.\"),",
"def test_key_from_paserk_for_public_key_with_wrapping_key(self, version, key): k = Key.new(version, \"public\", key) wk = token_bytes(32) with",
"key\", [ (1, \"public\", load_key(\"keys/public_key_rsa.pem\")), (2, \"public\", load_key(\"keys/public_key_ed25519.pem\")), (3, \"public\", load_key(\"keys/public_key_ecdsa_p384.pem\")), (4, \"public\",",
"), (2, load_key(\"keys/private_key_rsa.pem\"), \"The key is not Ed25519 key.\"), (2, load_key(\"keys/public_key_rsa.pem\"), \"The key",
"load_jwk(\"keys/public_key_ecdsa_p384.json\")), (4, load_jwk(\"keys/private_key_ed25519.json\")), (4, load_jwk(\"keys/public_key_ed25519.json\")), ], ) def test_key_from_asymmetric_params(self, version, key): k =",
"load_jwk(\"keys/public_key_ed25519.json\")), ], ) def test_key_from_asymmetric_params(self, version, key): k = Key.from_asymmetric_key_params(version, x=key[\"x\"], y=key[\"y\"], d=key[\"d\"])",
"{\"x\": b\"\", \"y\": b\"yyy\", \"d\": b\"ddd\"}, \"x and y (and d) should be",
"type: public.\"), (\"k2.local.AAAAAAAAAAAAAAAA\", \"Invalid PASERK type: local.\"), (\"k2.public.AAAAAAAAAAAAAAAA\", \"Invalid PASERK type: public.\"), (\"k3.local.AAAAAAAAAAAAAAAA\",",
"\"d\": b\"\"}, \"Failed to load key.\"), (2, {\"x\": b\"\", \"y\": b\"\", \"d\": b\"ddd\"},",
"], ) def test_key_from_paserk_for_public_key_with_password(self, version, key): k = Key.new(version, \"public\", key) wk =",
"0.\"), ( \"v*\", \"public\", load_key(\"keys/private_key_rsa.pem\"), \"Invalid version: v*.\", ), ( \"v0\", \"public\", load_key(\"keys/private_key_rsa.pem\"),",
"k.to_paserk(password=wk1) with pytest.raises(DecryptError) as err: Key.from_paserk(wpk, password=<PASSWORD>) pytest.fail(\"Key.from_paserk() should fail.\") assert \"Failed to",
"or unsupported PEM format.\"), ], ) def test_key_new_with_invalid_arg(self, version, purpose, key, msg): with",
"( \"v0\", \"public\", load_key(\"keys/private_key_rsa.pem\"), \"Invalid version: v0.\", ), ( 0, \"public\", load_key(\"keys/private_key_rsa.pem\"), \"Invalid",
"\"public\", load_key(\"keys/private_key_rsa.pem\"), \"Invalid version: 0.\", ), (1, \"xxx\", token_bytes(32), \"Invalid purpose: xxx.\"), (1,",
"k = Key.new(version, purpose, key) assert k.to_paserk().startswith(f\"k{k.version}.public.\") @pytest.mark.parametrize( \"version, purpose, key\", [ (1,",
"b\"\", \"y\": b\"\", \"d\": b\"ddd\"}, \"Failed to load key.\"), ( 4, {\"x\": b\"\",",
"as err: k.sign(b\"Hello world!\") pytest.fail(\"Key.sign() should fail.\") assert \"A key for local does",
"(3, load_key(\"keys/private_key_rsa.pem\"), \"The key is not ECDSA key.\"), (3, load_key(\"keys/public_key_rsa.pem\"), \"The key is",
"key.\", ), (2, load_key(\"keys/private_key_rsa.pem\"), \"The key is not Ed25519 key.\"), (2, load_key(\"keys/public_key_rsa.pem\"), \"The",
"key): k = Key.new(version, \"public\", key) wk = token_bytes(32) with pytest.raises(ValueError) as err:",
"in str(err.value) @pytest.mark.parametrize( \"version, key, msg\", [ ( 1, load_jwk(\"keys/private_key_rsa.json\"), \"v1.public is not",
"assert k.purpose == purpose with pytest.raises(NotSupportedError) as err: k.sign(b\"Hello world!\") pytest.fail(\"Key.sign() should fail.\")",
"load_key(\"keys/private_key_ecdsa_p384.pem\"), \"The key is not Ed25519 key.\", ), ( 2, load_key(\"keys/public_key_ecdsa_p384.pem\"), \"The key",
"format.\"), ], ) def test_key_new_with_invalid_arg(self, version, purpose, key, msg): with pytest.raises(ValueError) as err:",
"b\"ddd\"}, \"x and y (and d) should be set for v3.public.\", ), (",
"have verify().\" in str(err.value) @pytest.mark.parametrize( \"version, purpose, key\", [ (1, \"public\", load_key(\"keys/private_key_rsa.pem\")), (1,",
"v0.\"), (0, \"local\", token_bytes(32), \"Invalid version: 0.\"), ( \"v*\", \"public\", load_key(\"keys/private_key_rsa.pem\"), \"Invalid version:",
"Key. \"\"\" @pytest.mark.parametrize( \"version, purpose, key\", [ (1, \"local\", token_bytes(32)), (2, \"local\", token_bytes(32)),",
"Ed25519 key.\"), ( 4, load_key(\"keys/private_key_ecdsa_p384.pem\"), \"The key is not Ed25519 key.\", ), (",
"(\"v0\", \"local\", token_bytes(32), \"Invalid version: v0.\"), (0, \"local\", token_bytes(32), \"Invalid version: 0.\"), (",
"load_key(\"keys/public_key_rsa.pem\"), \"The key is not Ed25519 key.\"), ( 2, load_key(\"keys/private_key_ecdsa_p384.pem\"), \"The key is",
"\"xxx\", token_bytes(32), \"Invalid purpose: xxx.\"), (1, \"public\", \"-----BEGIN BAD\", \"Invalid or unsupported PEM",
"d should be set for v2.public.\", ), (2, {\"x\": b\"xxx\", \"y\": b\"\", \"d\":",
"(0, load_jwk(\"keys/private_key_ed25519.json\"), \"Invalid version: 0.\"), ( 2, {\"x\": b\"xxx\", \"y\": b\"\", \"d\": b\"ddd\"},",
"load_key(\"keys/private_key_ecdsa_p384.pem\")), (4, \"public\", load_key(\"keys/private_key_ed25519.pem\")), ], ) def test_key_to_paserk_secret(self, version, purpose, key): k =",
"\"The key is not Ed25519 key.\", ), ], ) def test_key_new_public_with_wrong_key(self, version, key,",
"pytest.raises(ValueError) as err: Key.from_paserk(paserk, password=\"<PASSWORD>\") pytest.fail(\"Key.from_paserk should fail.\") assert msg in str(err.value) @pytest.mark.parametrize(",
"4, load_key(\"keys/public_key_ecdsa_p384.pem\"), \"The key is not Ed25519 key.\", ), ], ) def test_key_new_public_with_wrong_key(self,",
"load key.\"), (4, {\"x\": b\"\", \"y\": b\"\", \"d\": b\"ddd\"}, \"Failed to load key.\"),",
"err: k.to_paserk(wrapping_key=\"xxx\", password=\"<PASSWORD>\") pytest.fail(\"to_paserk() should fail.\") assert \"Only one of wrapping_key or password",
"key\", [ (1, load_key(\"keys/private_key_rsa.pem\")), (2, load_key(\"keys/private_key_ed25519.pem\")), (3, load_key(\"keys/private_key_ecdsa_p384.pem\")), (4, load_key(\"keys/private_key_ed25519.pem\")), ], ) def",
"load key.\"), ( 3, { \"x\": base64url_decode(\"_XyN9woHaS0mPimSW-etwJMEDSzxIMjp4PjezavU8SHJoClz1bQrcmPb1ZJxHxhI\"), \"y\": base64url_decode(\"<KEY>\"), \"d\": b\"ddd\", }, \"Failed",
"as err: Key.from_paserk(wpk, password=<PASSWORD>) pytest.fail(\"Key.from_paserk() should fail.\") assert \"Failed to unwrap a key.\"",
"local does not have sign().\" in str(err.value) with pytest.raises(NotSupportedError) as err: k.verify(b\"xxxxxx\") pytest.fail(\"Key.verify()",
") def test_key_new_local(self, version, purpose, key): k = Key.new(version, purpose, key) assert isinstance(k,",
"purpose, key\", [ (1, \"public\", load_key(\"keys/private_key_rsa.pem\")), (2, \"public\", load_key(\"keys/private_key_ed25519.pem\")), (3, \"public\", load_key(\"keys/private_key_ecdsa_p384.pem\")), (4,",
"(\"k4.public.AAAAAAAAAAAAAAAA\", \"Invalid PASERK type: public.\"), ], ) def test_key_from_paserk_with_password_for_wrong_paserk(self, paserk, msg): with pytest.raises(ValueError)",
"Ed25519 key.\", ), ], ) def test_key_new_public_with_wrong_key(self, version, key, msg): with pytest.raises(ValueError) as",
"is not Ed25519 key.\", ), ( 4, load_key(\"keys/public_key_ecdsa_p384.pem\"), \"The key is not Ed25519",
"1, load_jwk(\"keys/private_key_rsa.json\"), \"v1.public is not supported on from_key_parameters.\", ), (999, load_jwk(\"keys/private_key_ed25519.json\"), \"Invalid version:",
"( 1, load_key(\"keys/public_key_ecdsa_p384.pem\"), \"The key is not RSA key.\", ), (2, load_key(\"keys/private_key_rsa.pem\"), \"The",
"should fail.\") assert \"Public key cannot be wrapped.\" in str(err.value) @pytest.mark.parametrize( \"version, key,",
"be set for v4.public.\", ), ], ) def test_key_from_asymmetric_params_with_invalid_arg(self, version, key, msg): with",
"password=\"<PASSWORD>\") pytest.fail(\"to_paserk() should fail.\") assert \"Only one of wrapping_key or password should be",
"(4, load_key(\"keys/private_key_ed25519.pem\")), ], ) def test_key_from_paserk_for_private_key_with_wrong_wrapping_key(self, version, key): k = Key.new(version, \"public\", key)",
"(4, load_jwk(\"keys/public_key_ed25519.json\")), ], ) def test_key_from_asymmetric_params(self, version, key): k = Key.from_asymmetric_key_params(version, x=key[\"x\"], y=key[\"y\"],",
"with pytest.raises(NotSupportedError) as err: k.encrypt(b\"Hello world!\") pytest.fail(\"Key.sign() should fail.\") assert \"A key for",
"pytest.fail(\"Key.from_paserk should fail.\") assert msg in str(err.value) @pytest.mark.parametrize( \"paserk, msg\", [ (\"v1.local.AAAAAAAAAAAAAAAA\", \"Invalid",
"\"public\", load_key(\"keys/private_key_ed25519.pem\")), (3, \"public\", load_key(\"keys/private_key_ecdsa_p384.pem\")), (4, \"public\", load_key(\"keys/private_key_ed25519.pem\")), ], ) def test_key_to_paserk_secret(self, version,",
"test_key_new_public_with_wrong_key(self, version, key, msg): with pytest.raises(ValueError) as err: Key.new(version, \"public\", key) pytest.fail(\"Key.new should",
"\"-----BEGIN BAD\", \"Invalid or unsupported PEM format.\"), ], ) def test_key_new_with_invalid_arg(self, version, purpose,",
"\"local\", token_bytes(32)), (3, \"local\", token_bytes(32)), (4, \"local\", token_bytes(32)), (1, \"public\", load_key(\"keys/private_key_rsa.pem\")), (2, \"public\",",
"is not Ed25519 key.\"), (4, load_key(\"keys/public_key_rsa.pem\"), \"The key is not Ed25519 key.\"), (",
"{\"x\": b\"xxx\", \"y\": b\"\", \"d\": b\"ddd\"}, \"x and y (and d) should be",
"public.\"), (\"k3.local.AAAAAAAAAAAAAAAA\", \"Invalid PASERK type: local.\"), (\"k3.public.AAAAAAAAAAAAAAAA\", \"Invalid PASERK type: public.\"), (\"k4.local.AAAAAAAAAAAAAAAA\", \"Invalid",
"@pytest.mark.parametrize( \"version, purpose, key\", [ (1, \"public\", load_key(\"keys/private_key_rsa.pem\")), (2, \"public\", load_key(\"keys/private_key_ed25519.pem\")), (3, \"public\",",
"\"Invalid PASERK type: public.\"), (\"k3.local.AAAAAAAAAAAAAAAA\", \"Invalid PASERK type: local.\"), (\"k3.public.AAAAAAAAAAAAAAAA\", \"Invalid PASERK type:",
"\"v0\", \"public\", load_key(\"keys/private_key_rsa.pem\"), \"Invalid version: v0.\", ), ( 0, \"public\", load_key(\"keys/private_key_rsa.pem\"), \"Invalid version:",
"fail.\") assert \"Public key cannot be wrapped.\" in str(err.value) @pytest.mark.parametrize( \"version, key\", [",
"assert \"Failed to unwrap a key.\" in str(err.value) @pytest.mark.parametrize( \"version, key\", [ (1,",
"def test_key_from_paserk_for_private_key_with_wrong_wrapping_key(self, version, key): k = Key.new(version, \"public\", key) wk1 = token_bytes(32) wk2",
"test_key_to_paserk_secret_with_wrapping_key_and_password(self, version, purpose, key): k = Key.new(version, purpose, key) with pytest.raises(ValueError) as err:",
"\"public\", key) wk = token_bytes(32) with pytest.raises(ValueError) as err: k.to_paserk(password=wk) pytest.fail(\"to_paserk() should fail.\")",
"assert k.version == version assert k.purpose == purpose with pytest.raises(NotSupportedError) as err: k.sign(b\"Hello",
"key.\", ), ( 4, {\"x\": b\"xxx\", \"y\": b\"\", \"d\": b\"ddd\"}, \"Only one of",
"Key.from_paserk(paserk, wrapping_key=\"xxx\", password=\"<PASSWORD>\") pytest.fail(\"Key.from_paserk should fail.\") assert \"Only one of wrapping_key or password",
"\"Invalid PASERK type: local.\"), (\"k1.public.AAAAAAAAAAAAAAAA\", \"Invalid PASERK type: public.\"), (\"k2.local.AAAAAAAAAAAAAAAA\", \"Invalid PASERK type:",
"assert k.to_paserk().startswith(f\"k{k.version}.secret.\") @pytest.mark.parametrize( \"version, purpose, key\", [ (1, \"local\", token_bytes(32)), (2, \"local\", token_bytes(32)),",
"token_bytes(32), \"Invalid version: 0.\"), ( \"v*\", \"public\", load_key(\"keys/private_key_rsa.pem\"), \"Invalid version: v*.\", ), (",
"(3, load_jwk(\"keys/public_key_ecdsa_p384.json\")), (4, load_jwk(\"keys/private_key_ed25519.json\")), (4, load_jwk(\"keys/public_key_ed25519.json\")), ], ) def test_key_from_asymmetric_params(self, version, key): k",
"\"A key for local does not have sign().\" in str(err.value) with pytest.raises(NotSupportedError) as",
"(3, load_key(\"keys/public_key_rsa.pem\"), \"The key is not ECDSA key.\"), (4, load_key(\"keys/private_key_rsa.pem\"), \"The key is",
"key.\"), (4, load_key(\"keys/private_key_rsa.pem\"), \"The key is not Ed25519 key.\"), (4, load_key(\"keys/public_key_rsa.pem\"), \"The key",
"\"Invalid purpose: xxx.\"), (1, \"public\", \"-----BEGIN BAD\", \"Invalid or unsupported PEM format.\"), ],",
"\"k2.local.AAAAAAAAAAAAAAAA\", \"k2.public.AAAAAAAAAAAAAAAA\", \"k3.local.AAAAAAAAAAAAAAAA\", \"k3.public.AAAAAAAAAAAAAAAA\", \"k4.local.AAAAAAAAAAAAAAAA\", \"k4.public.AAAAAAAAAAAAAAAA\", ], ) def test_key_from_paserk_with_wrapping_key_and_password(self, paserk): with pytest.raises(ValueError)",
"b\"\", \"y\": b\"\", \"d\": b\"\"}, \"x or d should be set for v4.public.\",",
"purpose, key) assert k.to_paserk().startswith(f\"k{k.version}.public.\") @pytest.mark.parametrize( \"version, purpose, key\", [ (1, \"public\", load_key(\"keys/private_key_rsa.pem\")), (2,",
"in str(err.value) @pytest.mark.parametrize( \"version, purpose, key, msg\", [ (\"v*\", \"local\", token_bytes(32), \"Invalid version:",
"ECDSA key.\", ), (3, load_key(\"keys/private_key_rsa.pem\"), \"The key is not ECDSA key.\"), (3, load_key(\"keys/public_key_rsa.pem\"),",
"\"k3.local.AAAAAAAAAAAAAAAA\", \"k3.public.AAAAAAAAAAAAAAAA\", \"k4.local.AAAAAAAAAAAAAAAA\", \"k4.public.AAAAAAAAAAAAAAAA\", ], ) def test_key_from_paserk_with_wrapping_key_and_password(self, paserk): with pytest.raises(ValueError) as err:",
"(2, load_key(\"keys/private_key_ed25519.pem\")), (3, load_key(\"keys/private_key_ecdsa_p384.pem\")), (4, load_key(\"keys/private_key_ed25519.pem\")), ], ) def test_key_from_paserk_for_private_key_with_wrong_wrapping_key(self, version, key): k",
"\"version, key\", [ (1, load_key(\"keys/public_key_rsa.pem\")), (2, load_key(\"keys/public_key_ed25519.pem\")), (3, load_key(\"keys/public_key_ecdsa_p384.pem\")), (4, load_key(\"keys/public_key_ed25519.pem\")), ], )",
"(1, \"public\", load_key(\"keys/private_key_rsa.pem\")), (2, \"public\", load_key(\"keys/private_key_ed25519.pem\")), (3, \"public\", load_key(\"keys/private_key_ecdsa_p384.pem\")), (4, \"public\", load_key(\"keys/private_key_ed25519.pem\")), ],",
"in str(err.value) @pytest.mark.parametrize( \"version, key\", [ (1, load_key(\"keys/public_key_rsa.pem\")), (2, load_key(\"keys/public_key_ed25519.pem\")), (3, load_key(\"keys/public_key_ecdsa_p384.pem\")), (4,",
"Key.new(version, purpose, key) pytest.fail(\"Key.new should fail.\") assert msg in str(err.value) @pytest.mark.parametrize( \"version, key\",",
"\"k3.public.AAAAAAAAAAAAAAAA\", \"k4.local.AAAAAAAAAAAAAAAA\", \"k4.public.AAAAAAAAAAAAAAAA\", ], ) def test_key_from_paserk_with_wrapping_key_and_password(self, paserk): with pytest.raises(ValueError) as err: Key.from_paserk(paserk,",
"b\"xxx\", \"y\": b\"\", \"d\": b\"ddd\"}, \"x and y (and d) should be set",
"PEM format.\"), ], ) def test_key_new_with_invalid_arg(self, version, purpose, key, msg): with pytest.raises(ValueError) as",
"err: k.sign(b\"Hello world!\") pytest.fail(\"Key.sign() should fail.\") assert \"A key for local does not",
"with pytest.raises(ValueError) as err: k.to_paserk(password=wk) pytest.fail(\"to_paserk() should fail.\") assert \"Public key cannot be",
"key for local does not have sign().\" in str(err.value) with pytest.raises(NotSupportedError) as err:",
"of x or d should be set for v4.public.\", ), (4, {\"x\": b\"xxx\",",
") def test_key_from_asymmetric_params(self, version, key): k = Key.from_asymmetric_key_params(version, x=key[\"x\"], y=key[\"y\"], d=key[\"d\"]) assert isinstance(k,",
"(\"k3.local.AAAAAAAAAAAAAAAA\", \"Invalid PASERK type: local.\"), (\"k3.public.AAAAAAAAAAAAAAAA\", \"Invalid PASERK type: public.\"), (\"k4.local.AAAAAAAAAAAAAAAA\", \"Invalid PASERK",
"str(err.value) @pytest.mark.parametrize( \"version, key, msg\", [ (1, load_key(\"keys/private_key_ed25519.pem\"), \"The key is not RSA",
"wrapped.\" in str(err.value) @pytest.mark.parametrize( \"version, key\", [ (1, load_key(\"keys/public_key_rsa.pem\")), (2, load_key(\"keys/public_key_ed25519.pem\")), (3, load_key(\"keys/public_key_ecdsa_p384.pem\")),",
"assert \"Public key cannot be wrapped.\" in str(err.value) @pytest.mark.parametrize( \"version, key\", [ (1,",
"\"public\", load_key(\"keys/private_key_rsa.pem\"), \"Invalid version: v*.\", ), ( \"v0\", \"public\", load_key(\"keys/private_key_rsa.pem\"), \"Invalid version: v0.\",",
"err: k.to_paserk(wrapping_key=wk) pytest.fail(\"to_paserk() should fail.\") assert \"Public key cannot be wrapped.\" in str(err.value)",
"), ( 3, {\"x\": b\"\", \"y\": b\"yyy\", \"d\": b\"ddd\"}, \"x and y (and",
"[ (1, \"public\", load_key(\"keys/private_key_rsa.pem\")), (2, \"public\", load_key(\"keys/private_key_ed25519.pem\")), (3, \"public\", load_key(\"keys/private_key_ecdsa_p384.pem\")), (4, \"public\", load_key(\"keys/private_key_ed25519.pem\")),",
"{\"x\": b\"\", \"y\": b\"\", \"d\": b\"\"}, \"x or d should be set for",
"set for v3.public.\", ), ( 3, {\"x\": b\"\", \"y\": b\"yyy\", \"d\": b\"ddd\"}, \"x",
"load_key(\"keys/public_key_ecdsa_p384.pem\")), (4, \"public\", load_key(\"keys/private_key_ed25519.pem\")), (4, \"public\", load_key(\"keys/public_key_ed25519.pem\")), ], ) def test_key_new_public(self, version, purpose,",
"xxx.\"), (1, \"public\", \"-----BEGIN BAD\", \"Invalid or unsupported PEM format.\"), ], ) def",
"\"d\": b\"\"}, \"Failed to load key.\"), ( 3, { \"x\": base64url_decode(\"_XyN9woHaS0mPimSW-etwJMEDSzxIMjp4PjezavU8SHJoClz1bQrcmPb1ZJxHxhI\"), \"y\": base64url_decode(\"<KEY>\"),",
"= Key.new(version, \"public\", key) wk = token_bytes(32) with pytest.raises(ValueError) as err: k.to_paserk(password=wk) pytest.fail(\"to_paserk()",
"\"local\", token_bytes(32)), (2, \"local\", token_bytes(32)), (3, \"local\", token_bytes(32)), (4, \"local\", token_bytes(32)), (1, \"public\",",
"\"public\", load_key(\"keys/private_key_rsa.pem\"), \"Invalid version: v0.\", ), ( 0, \"public\", load_key(\"keys/private_key_rsa.pem\"), \"Invalid version: 0.\",",
"= token_bytes(32) wpk = k.to_paserk(password=wk1) with pytest.raises(DecryptError) as err: Key.from_paserk(wpk, password=<PASSWORD>) pytest.fail(\"Key.from_paserk() should",
"load_jwk(\"keys/private_key_ed25519.json\")), (4, load_jwk(\"keys/public_key_ed25519.json\")), ], ) def test_key_from_asymmetric_params(self, version, key): k = Key.from_asymmetric_key_params(version, x=key[\"x\"],",
"(\"k2.public.AAAAAAAAAAAAAAAA\", \"Invalid PASERK type: public.\"), (\"k3.local.AAAAAAAAAAAAAAAA\", \"Invalid PASERK type: local.\"), (\"k3.public.AAAAAAAAAAAAAAAA\", \"Invalid PASERK",
"@pytest.mark.parametrize( \"version, key\", [ # (1, load_jwk(\"keys/private_key_rsa.json\")), # (1, load_jwk(\"keys/public_key_rsa.json\")), (2, load_jwk(\"keys/private_key_ed25519.json\")), (2,",
"for local does not have sign().\" in str(err.value) with pytest.raises(NotSupportedError) as err: k.verify(b\"xxxxxx\")",
"\"The key is not ECDSA key.\"), (3, load_key(\"keys/public_key_rsa.pem\"), \"The key is not ECDSA",
"be set for v3.public.\", ), ( 3, {\"x\": b\"\", \"y\": b\"yyy\", \"d\": b\"ddd\"},",
"\"k4.local.AAAAAAAAAAAAAAAA\", \"k4.public.AAAAAAAAAAAAAAAA\", ], ) def test_key_from_paserk_with_wrapping_key_and_password(self, paserk): with pytest.raises(ValueError) as err: Key.from_paserk(paserk, wrapping_key=\"xxx\",",
"to load key.\"), (2, {\"x\": b\"\", \"y\": b\"\", \"d\": b\"ddd\"}, \"Failed to load",
"\"version, key, msg\", [ ( 1, load_jwk(\"keys/private_key_rsa.json\"), \"v1.public is not supported on from_key_parameters.\",",
"\"public\", load_key(\"keys/public_key_ed25519.pem\")), (3, \"public\", load_key(\"keys/private_key_ecdsa_p384.pem\")), (3, \"public\", load_key(\"keys/public_key_ecdsa_p384.pem\")), (4, \"public\", load_key(\"keys/private_key_ed25519.pem\")), (4, \"public\",",
"to unwrap a key.\" in str(err.value) @pytest.mark.parametrize( \"version, key\", [ (1, load_key(\"keys/private_key_rsa.pem\")), (2,",
"(3, \"local\", token_bytes(32)), (4, \"local\", token_bytes(32)), ], ) def test_key_new_local(self, version, purpose, key):",
"NotSupportedError from pyseto.key_interface import KeyInterface from pyseto.utils import base64url_decode from .utils import load_jwk,",
"def test_key_from_asymmetric_params(self, version, key): k = Key.from_asymmetric_key_params(version, x=key[\"x\"], y=key[\"y\"], d=key[\"d\"]) assert isinstance(k, KeyInterface)",
"(3, \"public\", load_key(\"keys/private_key_ecdsa_p384.pem\")), (4, \"public\", load_key(\"keys/private_key_ed25519.pem\")), ], ) def test_key_to_paserk_secret_with_wrapping_key_and_password(self, version, purpose, key):",
"\"Only one of x or d should be set for v2.public.\", ), (2,",
"for Key. \"\"\" @pytest.mark.parametrize( \"version, purpose, key\", [ (1, \"local\", token_bytes(32)), (2, \"local\",",
"load_key(\"keys/public_key_ed25519.pem\"), \"The key is not RSA key.\"), ( 1, load_key(\"keys/private_key_ecdsa_p384.pem\"), \"The key is",
"fail.\") assert \"A key for local does not have sign().\" in str(err.value) with",
"Key.from_paserk(paserk, password=\"<PASSWORD>\") pytest.fail(\"Key.from_paserk should fail.\") assert msg in str(err.value) @pytest.mark.parametrize( \"paserk, msg\", [",
"\"Failed to unwrap a key.\" in str(err.value) @pytest.mark.parametrize( \"version, key\", [ (1, load_key(\"keys/private_key_rsa.pem\")),",
"key.\"), (4, {\"x\": b\"\", \"y\": b\"\", \"d\": b\"ddd\"}, \"Failed to load key.\"), (",
"with pytest.raises(ValueError) as err: k.to_paserk(wrapping_key=wk) pytest.fail(\"to_paserk() should fail.\") assert \"Public key cannot be",
"in str(err.value) @pytest.mark.parametrize( \"version\", [ 1, 2, 3, 4, ], ) def test_key_from_paserk_for_local_with_wrong_password(self,",
"purpose, key): k = Key.new(version, purpose, key) with pytest.raises(ValueError) as err: k.to_paserk(wrapping_key=\"xxx\", password=\"<PASSWORD>\")",
"type: local.\"), (\"k1.public.AAAAAAAAAAAAAAAA\", \"Invalid PASERK type: public.\"), (\"k2.local.AAAAAAAAAAAAAAAA\", \"Invalid PASERK type: local.\"), (\"k2.public.AAAAAAAAAAAAAAAA\",",
"msg\", [ (\"k1.local.AAAAAAAAAAAAAAAA\", \"Invalid PASERK type: local.\"), (\"k1.public.AAAAAAAAAAAAAAAA\", \"Invalid PASERK type: public.\"), (\"k2.local.AAAAAAAAAAAAAAAA\",",
"assert \"A key for local does not have sign().\" in str(err.value) with pytest.raises(NotSupportedError)",
"load_key(\"keys/public_key_rsa.pem\")), (2, \"public\", load_key(\"keys/private_key_ed25519.pem\")), (2, \"public\", load_key(\"keys/public_key_ed25519.pem\")), (3, \"public\", load_key(\"keys/private_key_ecdsa_p384.pem\")), (3, \"public\", load_key(\"keys/public_key_ecdsa_p384.pem\")),",
"{\"x\": b\"xxx\", \"y\": b\"\", \"d\": b\"\"}, \"Failed to load key.\"), (2, {\"x\": b\"\",",
"\"public\", load_key(\"keys/public_key_ed25519.pem\")), ], ) def test_key_new_public(self, version, purpose, key): k = Key.new(version, purpose,",
"as err: k.decrypt(b\"xxxxxx\") pytest.fail(\"Key.verify() should fail.\") assert \"A key for public does not",
"def test_key_new_public(self, version, purpose, key): k = Key.new(version, purpose, key) assert isinstance(k, KeyInterface)",
"should fail.\") assert \"Public key cannot be wrapped.\" in str(err.value) @pytest.mark.parametrize( \"version, key\",",
"key.\"), ( 2, {\"x\": b\"\", \"y\": b\"\", \"d\": b\"\"}, \"x or d should",
"], ) def test_key_new_local(self, version, purpose, key): k = Key.new(version, purpose, key) assert",
"as err: k.to_paserk(password=wk) pytest.fail(\"to_paserk() should fail.\") assert \"Public key cannot be wrapped.\" in",
"load_key(\"keys/public_key_ed25519.pem\")), ], ) def test_key_from_paserk_for_public_key_with_wrapping_key(self, version, key): k = Key.new(version, \"public\", key) wk",
".utils import load_jwk, load_key class TestKey: \"\"\" Tests for Key. \"\"\" @pytest.mark.parametrize( \"version,",
"= token_bytes(32) wk2 = token_bytes(32) wpk = k.to_paserk(password=wk1) with pytest.raises(DecryptError) as err: Key.from_paserk(wpk,",
"key.\"), ( 1, load_key(\"keys/private_key_ecdsa_p384.pem\"), \"The key is not RSA key.\", ), ( 1,",
"not RSA key.\", ), ( 1, load_key(\"keys/public_key_ecdsa_p384.pem\"), \"The key is not RSA key.\",",
"y (and d) should be set for v3.public.\", ), ( 3, {\"x\": b\"\",",
"version, key, msg): with pytest.raises(ValueError) as err: Key.new(version, \"public\", key) pytest.fail(\"Key.new should fail.\")",
"Ed25519 key.\", ), ( 3, load_key(\"keys/private_key_ed25519.pem\"), \"The key is not ECDSA key.\", ),",
"password should be specified.\" in str(err.value) @pytest.mark.parametrize( \"paserk, msg\", [ (\"k1.local.AAAAAAAAAAAAAAAA\", \"Invalid PASERK",
") def test_key_from_paserk_with_password_for_wrong_paserk(self, paserk, msg): with pytest.raises(ValueError) as err: Key.from_paserk(paserk, password=\"<PASSWORD>\") pytest.fail(\"Key.from_paserk should",
"with pytest.raises(ValueError) as err: Key.from_paserk(paserk, wrapping_key=\"xxx\", password=\"<PASSWORD>\") pytest.fail(\"Key.from_paserk should fail.\") assert \"Only one",
"\"local\", token_bytes(32), \"Invalid version: v0.\"), (0, \"local\", token_bytes(32), \"Invalid version: 0.\"), ( \"v*\",",
"def test_key_new_local(self, version, purpose, key): k = Key.new(version, purpose, key) assert isinstance(k, KeyInterface)",
"from_key_parameters.\", ), (999, load_jwk(\"keys/private_key_ed25519.json\"), \"Invalid version: 999.\"), (0, load_jwk(\"keys/private_key_ed25519.json\"), \"Invalid version: 0.\"), (",
"err: k.verify(b\"xxxxxx\") pytest.fail(\"Key.verify() should fail.\") assert \"A key for local does not have",
"(2, load_key(\"keys/private_key_rsa.pem\"), \"The key is not Ed25519 key.\"), (2, load_key(\"keys/public_key_rsa.pem\"), \"The key is",
"load_jwk(\"keys/private_key_ecdsa_p384.json\")), (3, load_jwk(\"keys/public_key_ecdsa_p384.json\")), (4, load_jwk(\"keys/private_key_ed25519.json\")), (4, load_jwk(\"keys/public_key_ed25519.json\")), ], ) def test_key_from_asymmetric_params(self, version, key):",
"of x or d should be set for v2.public.\", ), (2, {\"x\": b\"xxx\",",
"(3, {\"x\": b\"xxx\", \"y\": b\"yyy\", \"d\": b\"\"}, \"Failed to load key.\"), ( 3,",
"def test_key_from_paserk_for_public_key_with_password(self, version, key): k = Key.new(version, \"public\", key) wk = token_bytes(32) with",
"assert k.purpose == \"public\" @pytest.mark.parametrize( \"paserk\", [ \"k1.local.AAAAAAAAAAAAAAAA\", \"k1.public.AAAAAAAAAAAAAAAA\", \"k2.local.AAAAAAAAAAAAAAAA\", \"k2.public.AAAAAAAAAAAAAAAA\", \"k3.local.AAAAAAAAAAAAAAAA\", \"k3.public.AAAAAAAAAAAAAAAA\",",
"\"paserk, msg\", [ (\"v1.local.AAAAAAAAAAAAAAAA\", \"Invalid PASERK version: v1.\"), (\"*.local.AAAAAAAAAAAAAAAA\", \"Invalid PASERK version: *.\"),",
"test_key_from_paserk_for_public_key_with_wrapping_key(self, version, key): k = Key.new(version, \"public\", key) wk = token_bytes(32) with pytest.raises(ValueError)",
"DecryptError, Key, NotSupportedError from pyseto.key_interface import KeyInterface from pyseto.utils import base64url_decode from .utils",
"purpose with pytest.raises(NotSupportedError) as err: k.encrypt(b\"Hello world!\") pytest.fail(\"Key.sign() should fail.\") assert \"A key",
"(1, \"xxx\", token_bytes(32), \"Invalid purpose: xxx.\"), (1, \"public\", \"-----BEGIN BAD\", \"Invalid or unsupported",
"2, {\"x\": b\"\", \"y\": b\"\", \"d\": b\"\"}, \"x or d should be set",
"TestKey: \"\"\" Tests for Key. \"\"\" @pytest.mark.parametrize( \"version, purpose, key\", [ (1, \"local\",",
"\"y\": b\"\", \"d\": b\"\"}, \"Failed to load key.\"), (4, {\"x\": b\"\", \"y\": b\"\",",
"on from_key_parameters.\", ), (999, load_jwk(\"keys/private_key_ed25519.json\"), \"Invalid version: 999.\"), (0, load_jwk(\"keys/private_key_ed25519.json\"), \"Invalid version: 0.\"),",
"\"Failed to load key.\"), ( 4, {\"x\": b\"\", \"y\": b\"\", \"d\": b\"\"}, \"x",
") def test_key_from_paserk_with_wrapping_key_and_password(self, paserk): with pytest.raises(ValueError) as err: Key.from_paserk(paserk, wrapping_key=\"xxx\", password=\"<PASSWORD>\") pytest.fail(\"Key.from_paserk should",
"(4, load_key(\"keys/public_key_ed25519.pem\")), ], ) def test_key_from_paserk_for_public_key_with_wrapping_key(self, version, key): k = Key.new(version, \"public\", key)",
"b\"\"}, \"x or d should be set for v4.public.\", ), ], ) def",
"load_key(\"keys/public_key_ed25519.pem\")), ], ) def test_key_new_public(self, version, purpose, key): k = Key.new(version, purpose, key)",
"load_key(\"keys/private_key_ed25519.pem\")), ], ) def test_key_to_paserk_secret(self, version, purpose, key): k = Key.new(version, purpose, key)",
"cannot be wrapped.\" in str(err.value) @pytest.mark.parametrize( \"version, key, msg\", [ ( 1, load_jwk(\"keys/private_key_rsa.json\"),",
"\"Public key cannot be wrapped.\" in str(err.value) @pytest.mark.parametrize( \"version, key\", [ (1, load_key(\"keys/public_key_rsa.pem\")),",
"v2.public.\", ), (2, {\"x\": b\"xxx\", \"y\": b\"\", \"d\": b\"\"}, \"Failed to load key.\"),",
"pytest.raises(ValueError) as err: Key.from_asymmetric_key_params(version, x=key[\"x\"], y=key[\"y\"], d=key[\"d\"]) pytest.fail(\"Key.from_asymmetric_key_params() should fail.\") assert msg in",
"\"Invalid version: v0.\", ), ( 0, \"public\", load_key(\"keys/private_key_rsa.pem\"), \"Invalid version: 0.\", ), (1,",
"with pytest.raises(DecryptError) as err: Key.from_paserk(wpk, password=<PASSWORD>) pytest.fail(\"Key.from_paserk() should fail.\") assert \"Failed to unwrap",
"verify().\" in str(err.value) @pytest.mark.parametrize( \"version, purpose, key\", [ (1, \"public\", load_key(\"keys/private_key_rsa.pem\")), (1, \"public\",",
"], ) def test_key_new_with_invalid_arg(self, version, purpose, key, msg): with pytest.raises(ValueError) as err: Key.new(version,",
"should be set for v4.public.\", ), (4, {\"x\": b\"xxx\", \"y\": b\"\", \"d\": b\"\"},",
"RSA key.\", ), (2, load_key(\"keys/private_key_rsa.pem\"), \"The key is not Ed25519 key.\"), (2, load_key(\"keys/public_key_rsa.pem\"),",
"version: v0.\"), (0, \"local\", token_bytes(32), \"Invalid version: 0.\"), ( \"v*\", \"public\", load_key(\"keys/private_key_rsa.pem\"), \"Invalid",
"not ECDSA key.\"), (3, load_key(\"keys/public_key_rsa.pem\"), \"The key is not ECDSA key.\"), (4, load_key(\"keys/private_key_rsa.pem\"),",
"v1.\"), (\"*.local.AAAAAAAAAAAAAAAA\", \"Invalid PASERK version: *.\"), (\"k1.xxx.AAAAAAAAAAAAAAAA\", \"Invalid PASERK key type: xxx.\"), ],",
"load_key(\"keys/private_key_rsa.pem\"), \"The key is not ECDSA key.\"), (3, load_key(\"keys/public_key_rsa.pem\"), \"The key is not",
"Ed25519 key.\", ), ( 4, load_key(\"keys/public_key_ecdsa_p384.pem\"), \"The key is not Ed25519 key.\", ),",
"( \"v*\", \"public\", load_key(\"keys/private_key_rsa.pem\"), \"Invalid version: v*.\", ), ( \"v0\", \"public\", load_key(\"keys/private_key_rsa.pem\"), \"Invalid",
"\"x\": base64url_decode(\"_XyN9woHaS0mPimSW-etwJMEDSzxIMjp4PjezavU8SHJoClz1bQrcmPb1ZJxHxhI\"), \"y\": base64url_decode(\"<KEY>\"), \"d\": b\"ddd\", }, \"Failed to load key.\", ), (",
"\"d\": b\"ddd\"}, \"Failed to load key.\"), ( 4, {\"x\": b\"\", \"y\": b\"\", \"d\":",
"version: 0.\"), ( \"v*\", \"public\", load_key(\"keys/private_key_rsa.pem\"), \"Invalid version: v*.\", ), ( \"v0\", \"public\",",
"( 3, load_key(\"keys/private_key_ed25519.pem\"), \"The key is not ECDSA key.\", ), ( 3, load_key(\"keys/public_key_ed25519.pem\"),",
"assert isinstance(k, KeyInterface) assert k.version == version assert k.purpose == purpose with pytest.raises(NotSupportedError)",
"load_jwk(\"keys/public_key_rsa.json\")), (2, load_jwk(\"keys/private_key_ed25519.json\")), (2, load_jwk(\"keys/public_key_ed25519.json\")), (3, load_jwk(\"keys/private_key_ecdsa_p384.json\")), (3, load_jwk(\"keys/public_key_ecdsa_p384.json\")), (4, load_jwk(\"keys/private_key_ed25519.json\")), (4, load_jwk(\"keys/public_key_ed25519.json\")),",
"test_key_to_paserk_secret(self, version, purpose, key): k = Key.new(version, purpose, key) assert k.to_paserk().startswith(f\"k{k.version}.secret.\") @pytest.mark.parametrize( \"version,",
"\"y\": b\"\", \"d\": b\"ddd\"}, \"Only one of x or d should be set",
"\"local\", token_bytes(32)), (4, \"local\", token_bytes(32)), (1, \"public\", load_key(\"keys/private_key_rsa.pem\")), (2, \"public\", load_key(\"keys/private_key_ed25519.pem\")), (3, \"public\",",
"), ], ) def test_key_new_public_with_wrong_key(self, version, key, msg): with pytest.raises(ValueError) as err: Key.new(version,",
"token_bytes(32) wpk = k.to_paserk(password=wk1) with pytest.raises(DecryptError) as err: Key.from_paserk(wpk, password=<PASSWORD>) pytest.fail(\"Key.from_paserk() should fail.\")",
"decrypt().\" in str(err.value) @pytest.mark.parametrize( \"version, key, msg\", [ (1, load_key(\"keys/private_key_ed25519.pem\"), \"The key is",
"(1, \"local\", token_bytes(32)), (2, \"local\", token_bytes(32)), (3, \"local\", token_bytes(32)), (4, \"local\", token_bytes(32)), ],",
"assert k.version == version assert k.purpose == purpose with pytest.raises(NotSupportedError) as err: k.encrypt(b\"Hello",
"from pyseto.key_interface import KeyInterface from pyseto.utils import base64url_decode from .utils import load_jwk, load_key",
"fail.\") assert msg in str(err.value) @pytest.mark.parametrize( \"paserk, msg\", [ (\"v1.local.AAAAAAAAAAAAAAAA\", \"Invalid PASERK version:",
"load_key(\"keys/public_key_ed25519.pem\"), \"The key is not ECDSA key.\", ), (3, load_key(\"keys/private_key_rsa.pem\"), \"The key is",
"in str(err.value) @pytest.mark.parametrize( \"version, purpose, key\", [ (1, \"public\", load_key(\"keys/private_key_rsa.pem\")), (1, \"public\", load_key(\"keys/public_key_rsa.pem\")),",
"as err: Key.new(version, \"public\", key) pytest.fail(\"Key.new should fail.\") assert msg in str(err.value) @pytest.mark.parametrize(",
"# (1, load_jwk(\"keys/public_key_rsa.json\")), (2, load_jwk(\"keys/private_key_ed25519.json\")), (2, load_jwk(\"keys/public_key_ed25519.json\")), (3, load_jwk(\"keys/private_key_ecdsa_p384.json\")), (3, load_jwk(\"keys/public_key_ecdsa_p384.json\")), (4, load_jwk(\"keys/private_key_ed25519.json\")),",
"type: local.\"), (\"k2.public.AAAAAAAAAAAAAAAA\", \"Invalid PASERK type: public.\"), (\"k3.local.AAAAAAAAAAAAAAAA\", \"Invalid PASERK type: local.\"), (\"k3.public.AAAAAAAAAAAAAAAA\",",
"pytest.fail(\"Key.from_paserk should fail.\") assert msg in str(err.value) @pytest.mark.parametrize( \"version\", [ 1, 2, 3,",
"pytest.raises(NotSupportedError) as err: k.decrypt(b\"xxxxxx\") pytest.fail(\"Key.verify() should fail.\") assert \"A key for public does",
"RSA key.\", ), ( 1, load_key(\"keys/public_key_ecdsa_p384.pem\"), \"The key is not RSA key.\", ),",
"paserk, msg): with pytest.raises(ValueError) as err: Key.from_paserk(paserk, password=\"<PASSWORD>\") pytest.fail(\"Key.from_paserk should fail.\") assert msg",
"of wrapping_key or password should be specified.\" in str(err.value) @pytest.mark.parametrize( \"paserk, msg\", [",
"b\"\", \"d\": b\"\"}, \"Failed to load key.\"), (4, {\"x\": b\"\", \"y\": b\"\", \"d\":",
"x=key[\"x\"], y=key[\"y\"], d=key[\"d\"]) pytest.fail(\"Key.from_asymmetric_key_params() should fail.\") assert msg in str(err.value) @pytest.mark.parametrize( \"version, purpose,",
"\"local\", token_bytes(32)), ], ) def test_key_new_local(self, version, purpose, key): k = Key.new(version, purpose,",
"not have sign().\" in str(err.value) with pytest.raises(NotSupportedError) as err: k.verify(b\"xxxxxx\") pytest.fail(\"Key.verify() should fail.\")",
"fail.\") assert msg in str(err.value) @pytest.mark.parametrize( \"version\", [ 1, 2, 3, 4, ],",
"for local does not have verify().\" in str(err.value) @pytest.mark.parametrize( \"version, purpose, key\", [",
"\"version, key\", [ (1, load_key(\"keys/private_key_rsa.pem\")), (2, load_key(\"keys/private_key_ed25519.pem\")), (3, load_key(\"keys/private_key_ecdsa_p384.pem\")), (4, load_key(\"keys/private_key_ed25519.pem\")), ], )",
"\"y\": b\"\", \"d\": b\"\"}, \"x or d should be set for v4.public.\", ),",
"b\"ddd\"}, \"Only one of x or d should be set for v4.public.\", ),",
"unwrap a key.\" in str(err.value) @pytest.mark.parametrize( \"version, key\", [ (1, load_key(\"keys/public_key_rsa.pem\")), (2, load_key(\"keys/public_key_ed25519.pem\")),",
"pytest.fail(\"to_paserk() should fail.\") assert \"Only one of wrapping_key or password should be specified.\"",
"== purpose with pytest.raises(NotSupportedError) as err: k.sign(b\"Hello world!\") pytest.fail(\"Key.sign() should fail.\") assert \"A",
"key.\", ), ( 4, load_key(\"keys/public_key_ecdsa_p384.pem\"), \"The key is not Ed25519 key.\", ), ],",
"\"local\", token_bytes(32), \"Invalid version: v*.\"), (\"v0\", \"local\", token_bytes(32), \"Invalid version: v0.\"), (0, \"local\",",
"\"Failed to load key.\"), ( 3, { \"x\": base64url_decode(\"_XyN9woHaS0mPimSW-etwJMEDSzxIMjp4PjezavU8SHJoClz1bQrcmPb1ZJxHxhI\"), \"y\": base64url_decode(\"<KEY>\"), \"d\": b\"ddd\",",
"b\"\", \"d\": b\"\"}, \"x or d should be set for v4.public.\", ), ],",
"def test_key_from_paserk_for_local_with_wrong_password(self, version): k = Key.new(version, \"local\", token_bytes(32)) wk1 = token_bytes(32) wk2 =",
"(2, \"public\", load_key(\"keys/public_key_ed25519.pem\")), (3, \"public\", load_key(\"keys/public_key_ecdsa_p384.pem\")), (4, \"public\", load_key(\"keys/public_key_ed25519.pem\")), ], ) def test_key_to_paserk_public(self,",
"pytest from pyseto import DecryptError, Key, NotSupportedError from pyseto.key_interface import KeyInterface from pyseto.utils",
"Tests for Key. \"\"\" @pytest.mark.parametrize( \"version, purpose, key\", [ (1, \"local\", token_bytes(32)), (2,",
"key, msg): with pytest.raises(ValueError) as err: Key.from_asymmetric_key_params(version, x=key[\"x\"], y=key[\"y\"], d=key[\"d\"]) pytest.fail(\"Key.from_asymmetric_key_params() should fail.\")",
"\"version, key, msg\", [ (1, load_key(\"keys/private_key_ed25519.pem\"), \"The key is not RSA key.\"), (1,",
"x=key[\"x\"], y=key[\"y\"], d=key[\"d\"]) assert isinstance(k, KeyInterface) assert k.version == version assert k.purpose ==",
"1, 2, 3, 4, ], ) def test_key_from_paserk_for_local_with_wrong_wrapping_key(self, version): k = Key.new(version, \"local\",",
") def test_key_new_public(self, version, purpose, key): k = Key.new(version, purpose, key) assert isinstance(k,",
"(1, load_key(\"keys/private_key_rsa.pem\")), (2, load_key(\"keys/private_key_ed25519.pem\")), (3, load_key(\"keys/private_key_ecdsa_p384.pem\")), (4, load_key(\"keys/private_key_ed25519.pem\")), ], ) def test_key_from_paserk_for_private_key_with_wrong_wrapping_key(self, version,",
"load_key(\"keys/private_key_ecdsa_p384.pem\")), (4, \"public\", load_key(\"keys/private_key_ed25519.pem\")), ], ) def test_key_to_paserk_secret_with_wrapping_key_and_password(self, version, purpose, key): k =",
"isinstance(k, KeyInterface) assert k.version == version assert k.purpose == purpose with pytest.raises(NotSupportedError) as",
"as err: Key.from_paserk(paserk) pytest.fail(\"Key.from_paserk should fail.\") assert msg in str(err.value) @pytest.mark.parametrize( \"version\", [",
"be specified.\" in str(err.value) @pytest.mark.parametrize( \"paserk, msg\", [ (\"k1.local.AAAAAAAAAAAAAAAA\", \"Invalid PASERK type: local.\"),",
"err: k.decrypt(b\"xxxxxx\") pytest.fail(\"Key.verify() should fail.\") assert \"A key for public does not have",
"key.\", ), (3, load_key(\"keys/private_key_rsa.pem\"), \"The key is not ECDSA key.\"), (3, load_key(\"keys/public_key_rsa.pem\"), \"The",
"\"public\", load_key(\"keys/public_key_ecdsa_p384.pem\")), (4, \"public\", load_key(\"keys/private_key_ed25519.pem\")), (4, \"public\", load_key(\"keys/public_key_ed25519.pem\")), ], ) def test_key_new_public(self, version,",
"load_key(\"keys/public_key_rsa.pem\"), \"The key is not Ed25519 key.\"), ( 4, load_key(\"keys/private_key_ecdsa_p384.pem\"), \"The key is",
"key is not Ed25519 key.\", ), ], ) def test_key_new_public_with_wrong_key(self, version, key, msg):",
"wk2 = token_bytes(32) wpk = k.to_paserk(password=wk1) with pytest.raises(DecryptError) as err: Key.from_paserk(wpk, password=<PASSWORD>) pytest.fail(\"Key.from_paserk()",
"msg\", [ ( 1, load_jwk(\"keys/private_key_rsa.json\"), \"v1.public is not supported on from_key_parameters.\", ), (999,",
"load_key(\"keys/public_key_rsa.pem\")), (2, \"public\", load_key(\"keys/public_key_ed25519.pem\")), (3, \"public\", load_key(\"keys/public_key_ecdsa_p384.pem\")), (4, \"public\", load_key(\"keys/public_key_ed25519.pem\")), ], ) def",
"\"version, purpose, key, msg\", [ (\"v*\", \"local\", token_bytes(32), \"Invalid version: v*.\"), (\"v0\", \"local\",",
"RSA key.\"), (1, load_key(\"keys/public_key_ed25519.pem\"), \"The key is not RSA key.\"), ( 1, load_key(\"keys/private_key_ecdsa_p384.pem\"),",
") def test_key_from_paserk_for_local_with_wrong_password(self, version): k = Key.new(version, \"local\", token_bytes(32)) wk1 = token_bytes(32) wk2",
"is not Ed25519 key.\", ), ( 2, load_key(\"keys/public_key_ecdsa_p384.pem\"), \"The key is not Ed25519",
"test_key_new_public(self, version, purpose, key): k = Key.new(version, purpose, key) assert isinstance(k, KeyInterface) assert",
"3, load_key(\"keys/public_key_ed25519.pem\"), \"The key is not ECDSA key.\", ), (3, load_key(\"keys/private_key_rsa.pem\"), \"The key",
"(2, load_key(\"keys/public_key_ed25519.pem\")), (3, load_key(\"keys/public_key_ecdsa_p384.pem\")), (4, load_key(\"keys/public_key_ed25519.pem\")), ], ) def test_key_from_paserk_for_public_key_with_wrapping_key(self, version, key): k",
"b\"ddd\", }, \"Failed to load key.\", ), ( 4, {\"x\": b\"xxx\", \"y\": b\"\",",
"(\"k4.local.AAAAAAAAAAAAAAAA\", \"Invalid PASERK type: local.\"), (\"k4.public.AAAAAAAAAAAAAAAA\", \"Invalid PASERK type: public.\"), ], ) def",
"pyseto.utils import base64url_decode from .utils import load_jwk, load_key class TestKey: \"\"\" Tests for",
"= token_bytes(32) wk2 = token_bytes(32) wpk = k.to_paserk(wrapping_key=wk1) with pytest.raises(DecryptError) as err: Key.from_paserk(wpk,",
"is not Ed25519 key.\", ), ( 3, load_key(\"keys/private_key_ed25519.pem\"), \"The key is not ECDSA",
"\"x or d should be set for v4.public.\", ), ], ) def test_key_from_asymmetric_params_with_invalid_arg(self,",
"key is not RSA key.\"), (1, load_key(\"keys/public_key_ed25519.pem\"), \"The key is not RSA key.\"),",
"load_key(\"keys/private_key_ed25519.pem\")), ], ) def test_key_from_paserk_for_private_key_with_wrong_wrapping_key(self, version, key): k = Key.new(version, \"public\", key) wk1",
"@pytest.mark.parametrize( \"paserk, msg\", [ (\"v1.local.AAAAAAAAAAAAAAAA\", \"Invalid PASERK version: v1.\"), (\"*.local.AAAAAAAAAAAAAAAA\", \"Invalid PASERK version:",
"key.\" in str(err.value) @pytest.mark.parametrize( \"version, key\", [ (1, load_key(\"keys/public_key_rsa.pem\")), (2, load_key(\"keys/public_key_ed25519.pem\")), (3, load_key(\"keys/public_key_ecdsa_p384.pem\")),",
"key): k = Key.new(version, purpose, key) with pytest.raises(ValueError) as err: k.to_paserk(wrapping_key=\"xxx\", password=\"<PASSWORD>\") pytest.fail(\"to_paserk()",
"(2, load_key(\"keys/public_key_ed25519.pem\")), (3, load_key(\"keys/public_key_ecdsa_p384.pem\")), (4, load_key(\"keys/public_key_ed25519.pem\")), ], ) def test_key_from_paserk_for_public_key_with_password(self, version, key): k",
"for public does not have encrypt().\" in str(err.value) with pytest.raises(NotSupportedError) as err: k.decrypt(b\"xxxxxx\")",
"key is not RSA key.\"), ( 1, load_key(\"keys/private_key_ecdsa_p384.pem\"), \"The key is not RSA",
"Key.from_asymmetric_key_params(version, x=key[\"x\"], y=key[\"y\"], d=key[\"d\"]) assert isinstance(k, KeyInterface) assert k.version == version assert k.purpose",
"in str(err.value) @pytest.mark.parametrize( \"version\", [ 1, 2, 3, 4, ], ) def test_key_from_paserk_for_local_with_wrong_wrapping_key(self,",
"\"paserk, msg\", [ (\"k1.local.AAAAAAAAAAAAAAAA\", \"Invalid PASERK type: local.\"), (\"k1.public.AAAAAAAAAAAAAAAA\", \"Invalid PASERK type: public.\"),",
"\"x or d should be set for v2.public.\", ), ( 3, {\"x\": b\"xxx\",",
"1, load_key(\"keys/public_key_ecdsa_p384.pem\"), \"The key is not RSA key.\", ), (2, load_key(\"keys/private_key_rsa.pem\"), \"The key",
"(4, \"public\", load_key(\"keys/public_key_ed25519.pem\")), ], ) def test_key_new_public(self, version, purpose, key): k = Key.new(version,",
"key.\" in str(err.value) @pytest.mark.parametrize( \"version\", [ 1, 2, 3, 4, ], ) def",
"Key.from_asymmetric_key_params(version, x=key[\"x\"], y=key[\"y\"], d=key[\"d\"]) pytest.fail(\"Key.from_asymmetric_key_params() should fail.\") assert msg in str(err.value) @pytest.mark.parametrize( \"version,",
"k.purpose == \"public\" @pytest.mark.parametrize( \"paserk\", [ \"k1.local.AAAAAAAAAAAAAAAA\", \"k1.public.AAAAAAAAAAAAAAAA\", \"k2.local.AAAAAAAAAAAAAAAA\", \"k2.public.AAAAAAAAAAAAAAAA\", \"k3.local.AAAAAAAAAAAAAAAA\", \"k3.public.AAAAAAAAAAAAAAAA\", \"k4.local.AAAAAAAAAAAAAAAA\",",
"pytest.fail(\"Key.new should fail.\") assert msg in str(err.value) @pytest.mark.parametrize( \"version, purpose, key, msg\", [",
"load_key(\"keys/public_key_ed25519.pem\")), ], ) def test_key_from_paserk_for_public_key_with_password(self, version, key): k = Key.new(version, \"public\", key) wk",
"\"Failed to unwrap a key.\" in str(err.value) @pytest.mark.parametrize( \"version, key\", [ (1, load_key(\"keys/public_key_rsa.pem\")),",
"purpose, key) pytest.fail(\"Key.new should fail.\") assert msg in str(err.value) @pytest.mark.parametrize( \"version, key\", [",
"not ECDSA key.\", ), ( 3, load_key(\"keys/public_key_ed25519.pem\"), \"The key is not ECDSA key.\",",
"as err: k.encrypt(b\"Hello world!\") pytest.fail(\"Key.sign() should fail.\") assert \"A key for public does",
"pytest.raises(NotSupportedError) as err: k.encrypt(b\"Hello world!\") pytest.fail(\"Key.sign() should fail.\") assert \"A key for public",
"purpose, key\", [ (1, \"public\", load_key(\"keys/private_key_rsa.pem\")), (1, \"public\", load_key(\"keys/public_key_rsa.pem\")), (2, \"public\", load_key(\"keys/private_key_ed25519.pem\")), (2,",
"), (2, {\"x\": b\"xxx\", \"y\": b\"\", \"d\": b\"\"}, \"Failed to load key.\"), (2,",
"wk = token_bytes(32) with pytest.raises(ValueError) as err: k.to_paserk(password=wk) pytest.fail(\"to_paserk() should fail.\") assert \"Public",
"= Key.new(version, \"local\", token_bytes(32)) wk1 = token_bytes(32) wk2 = token_bytes(32) wpk = k.to_paserk(password=wk1)",
"b\"\"}, \"Failed to load key.\"), ( 3, { \"x\": base64url_decode(\"_XyN9woHaS0mPimSW-etwJMEDSzxIMjp4PjezavU8SHJoClz1bQrcmPb1ZJxHxhI\"), \"y\": base64url_decode(\"<KEY>\"), \"d\":",
"(1, load_key(\"keys/private_key_ed25519.pem\"), \"The key is not RSA key.\"), (1, load_key(\"keys/public_key_ed25519.pem\"), \"The key is",
"have encrypt().\" in str(err.value) with pytest.raises(NotSupportedError) as err: k.decrypt(b\"xxxxxx\") pytest.fail(\"Key.verify() should fail.\") assert",
"load_key(\"keys/public_key_ecdsa_p384.pem\"), \"The key is not Ed25519 key.\", ), ( 3, load_key(\"keys/private_key_ed25519.pem\"), \"The key",
"@pytest.mark.parametrize( \"version, key, msg\", [ (1, load_key(\"keys/private_key_ed25519.pem\"), \"The key is not RSA key.\"),",
"Ed25519 key.\"), (2, load_key(\"keys/public_key_rsa.pem\"), \"The key is not Ed25519 key.\"), ( 2, load_key(\"keys/private_key_ecdsa_p384.pem\"),",
"[ (1, load_key(\"keys/public_key_rsa.pem\")), (2, load_key(\"keys/public_key_ed25519.pem\")), (3, load_key(\"keys/public_key_ecdsa_p384.pem\")), (4, load_key(\"keys/public_key_ed25519.pem\")), ], ) def test_key_from_paserk_for_public_key_with_password(self,",
"\"Invalid PASERK type: public.\"), (\"k4.local.AAAAAAAAAAAAAAAA\", \"Invalid PASERK type: local.\"), (\"k4.public.AAAAAAAAAAAAAAAA\", \"Invalid PASERK type:",
"= Key.new(version, purpose, key) with pytest.raises(ValueError) as err: k.to_paserk(wrapping_key=\"xxx\", password=\"<PASSWORD>\") pytest.fail(\"to_paserk() should fail.\")",
"(4, \"public\", load_key(\"keys/private_key_ed25519.pem\")), ], ) def test_key_to_paserk_secret(self, version, purpose, key): k = Key.new(version,",
"import pytest from pyseto import DecryptError, Key, NotSupportedError from pyseto.key_interface import KeyInterface from",
"version, purpose, key): k = Key.new(version, purpose, key) assert k.to_paserk().startswith(f\"k{k.version}.public.\") @pytest.mark.parametrize( \"version, purpose,",
"0.\", ), (1, \"xxx\", token_bytes(32), \"Invalid purpose: xxx.\"), (1, \"public\", \"-----BEGIN BAD\", \"Invalid",
"version, key): k = Key.from_asymmetric_key_params(version, x=key[\"x\"], y=key[\"y\"], d=key[\"d\"]) assert isinstance(k, KeyInterface) assert k.version",
"key\", [ (1, \"local\", token_bytes(32)), (2, \"local\", token_bytes(32)), (3, \"local\", token_bytes(32)), (4, \"local\",",
"not Ed25519 key.\", ), ( 4, load_key(\"keys/public_key_ecdsa_p384.pem\"), \"The key is not Ed25519 key.\",",
"k = Key.new(version, purpose, key) with pytest.raises(ValueError) as err: k.to_paserk(wrapping_key=\"xxx\", password=\"<PASSWORD>\") pytest.fail(\"to_paserk() should",
"Key.new(version, purpose, key) assert k.to_paserk().startswith(f\"k{k.version}.public.\") @pytest.mark.parametrize( \"version, purpose, key\", [ (1, \"public\", load_key(\"keys/private_key_rsa.pem\")),",
"(2, \"local\", token_bytes(32)), (3, \"local\", token_bytes(32)), (4, \"local\", token_bytes(32)), (1, \"public\", load_key(\"keys/private_key_rsa.pem\")), (2,",
"wpk = k.to_paserk(wrapping_key=wk1) with pytest.raises(DecryptError) as err: Key.from_paserk(wpk, wrapping_key=wk2) pytest.fail(\"Key.from_paserk() should fail.\") assert",
"should be specified.\" in str(err.value) @pytest.mark.parametrize( \"paserk, msg\", [ (\"k1.local.AAAAAAAAAAAAAAAA\", \"Invalid PASERK type:",
"set for v2.public.\", ), ( 3, {\"x\": b\"xxx\", \"y\": b\"\", \"d\": b\"ddd\"}, \"x",
"token_bytes(32), \"Invalid purpose: xxx.\"), (1, \"public\", \"-----BEGIN BAD\", \"Invalid or unsupported PEM format.\"),",
"msg in str(err.value) @pytest.mark.parametrize( \"version, purpose, key\", [ (1, \"public\", load_key(\"keys/public_key_rsa.pem\")), (2, \"public\",",
"should be set for v4.public.\", ), ], ) def test_key_from_asymmetric_params_with_invalid_arg(self, version, key, msg):",
"(\"v1.local.AAAAAAAAAAAAAAAA\", \"Invalid PASERK version: v1.\"), (\"*.local.AAAAAAAAAAAAAAAA\", \"Invalid PASERK version: *.\"), (\"k1.xxx.AAAAAAAAAAAAAAAA\", \"Invalid PASERK",
"k = Key.from_asymmetric_key_params(version, x=key[\"x\"], y=key[\"y\"], d=key[\"d\"]) assert isinstance(k, KeyInterface) assert k.version == version",
"\"Only one of wrapping_key or password should be specified.\" in str(err.value) @pytest.mark.parametrize( \"paserk,",
"b\"\"}, \"Failed to load key.\"), (4, {\"x\": b\"\", \"y\": b\"\", \"d\": b\"ddd\"}, \"Failed",
"from pyseto import DecryptError, Key, NotSupportedError from pyseto.key_interface import KeyInterface from pyseto.utils import",
"does not have sign().\" in str(err.value) with pytest.raises(NotSupportedError) as err: k.verify(b\"xxxxxx\") pytest.fail(\"Key.verify() should",
"type: xxx.\"), ], ) def test_key_from_paserk_with_invalid_args(self, paserk, msg): with pytest.raises(ValueError) as err: Key.from_paserk(paserk)",
"\"k4.public.AAAAAAAAAAAAAAAA\", ], ) def test_key_from_paserk_with_wrapping_key_and_password(self, paserk): with pytest.raises(ValueError) as err: Key.from_paserk(paserk, wrapping_key=\"xxx\", password=\"<PASSWORD>\")",
"@pytest.mark.parametrize( \"paserk\", [ \"k1.local.AAAAAAAAAAAAAAAA\", \"k1.public.AAAAAAAAAAAAAAAA\", \"k2.local.AAAAAAAAAAAAAAAA\", \"k2.public.AAAAAAAAAAAAAAAA\", \"k3.local.AAAAAAAAAAAAAAAA\", \"k3.public.AAAAAAAAAAAAAAAA\", \"k4.local.AAAAAAAAAAAAAAAA\", \"k4.public.AAAAAAAAAAAAAAAA\", ], )",
"( 1, load_jwk(\"keys/private_key_rsa.json\"), \"v1.public is not supported on from_key_parameters.\", ), (999, load_jwk(\"keys/private_key_ed25519.json\"), \"Invalid",
"not RSA key.\"), ( 1, load_key(\"keys/private_key_ecdsa_p384.pem\"), \"The key is not RSA key.\", ),",
"wrapping_key=\"xxx\", password=\"<PASSWORD>\") pytest.fail(\"Key.from_paserk should fail.\") assert \"Only one of wrapping_key or password should",
"), ( 2, load_key(\"keys/public_key_ecdsa_p384.pem\"), \"The key is not Ed25519 key.\", ), ( 3,",
"assert k.version == version assert k.purpose == \"public\" @pytest.mark.parametrize( \"paserk\", [ \"k1.local.AAAAAAAAAAAAAAAA\", \"k1.public.AAAAAAAAAAAAAAAA\",",
"world!\") pytest.fail(\"Key.sign() should fail.\") assert \"A key for local does not have sign().\"",
"in str(err.value) with pytest.raises(NotSupportedError) as err: k.verify(b\"xxxxxx\") pytest.fail(\"Key.verify() should fail.\") assert \"A key",
"load_key(\"keys/private_key_ecdsa_p384.pem\"), \"The key is not RSA key.\", ), ( 1, load_key(\"keys/public_key_ecdsa_p384.pem\"), \"The key",
"\"local\", token_bytes(32)) wk1 = token_bytes(32) wk2 = token_bytes(32) wpk = k.to_paserk(wrapping_key=wk1) with pytest.raises(DecryptError)",
"a key.\" in str(err.value) @pytest.mark.parametrize( \"version, key\", [ (1, load_key(\"keys/public_key_rsa.pem\")), (2, load_key(\"keys/public_key_ed25519.pem\")), (3,",
"with pytest.raises(ValueError) as err: Key.from_paserk(paserk, password=\"<PASSWORD>\") pytest.fail(\"Key.from_paserk should fail.\") assert msg in str(err.value)",
"key is not ECDSA key.\"), (3, load_key(\"keys/public_key_rsa.pem\"), \"The key is not ECDSA key.\"),",
"(2, \"public\", load_key(\"keys/private_key_ed25519.pem\")), (3, \"public\", load_key(\"keys/private_key_ecdsa_p384.pem\")), (4, \"public\", load_key(\"keys/private_key_ed25519.pem\")), ], ) def test_key_to_paserk_secret(self,",
"key cannot be wrapped.\" in str(err.value) @pytest.mark.parametrize( \"version, key\", [ (1, load_key(\"keys/public_key_rsa.pem\")), (2,",
"\"A key for public does not have encrypt().\" in str(err.value) with pytest.raises(NotSupportedError) as",
"not RSA key.\", ), (2, load_key(\"keys/private_key_rsa.pem\"), \"The key is not Ed25519 key.\"), (2,",
"3, {\"x\": b\"xxx\", \"y\": b\"\", \"d\": b\"ddd\"}, \"x and y (and d) should",
"\"Invalid version: 0.\"), ( 2, {\"x\": b\"xxx\", \"y\": b\"\", \"d\": b\"ddd\"}, \"Only one",
"), ], ) def test_key_from_asymmetric_params_with_invalid_arg(self, version, key, msg): with pytest.raises(ValueError) as err: Key.from_asymmetric_key_params(version,",
"msg in str(err.value) @pytest.mark.parametrize( \"version\", [ 1, 2, 3, 4, ], ) def",
"load_key(\"keys/public_key_rsa.pem\"), \"The key is not ECDSA key.\"), (4, load_key(\"keys/private_key_rsa.pem\"), \"The key is not",
"KeyInterface) assert k.version == version assert k.purpose == purpose with pytest.raises(NotSupportedError) as err:",
"3, { \"x\": base64url_decode(\"_XyN9woHaS0mPimSW-etwJMEDSzxIMjp4PjezavU8SHJoClz1bQrcmPb1ZJxHxhI\"), \"y\": base64url_decode(\"<KEY>\"), \"d\": b\"ddd\", }, \"Failed to load key.\",",
"\"local\", token_bytes(32)), (3, \"local\", token_bytes(32)), (4, \"local\", token_bytes(32)), ], ) def test_key_new_local(self, version,",
"fail.\") assert \"Failed to unwrap a key.\" in str(err.value) @pytest.mark.parametrize( \"version\", [ 1,",
"version: v0.\", ), ( 0, \"public\", load_key(\"keys/private_key_rsa.pem\"), \"Invalid version: 0.\", ), (1, \"xxx\",",
"token_bytes(32), \"Invalid version: v*.\"), (\"v0\", \"local\", token_bytes(32), \"Invalid version: v0.\"), (0, \"local\", token_bytes(32),",
"err: Key.from_paserk(paserk, password=\"<PASSWORD>\") pytest.fail(\"Key.from_paserk should fail.\") assert msg in str(err.value) @pytest.mark.parametrize( \"paserk, msg\",",
"b\"ddd\"}, \"Failed to load key.\"), ( 4, {\"x\": b\"\", \"y\": b\"\", \"d\": b\"\"},",
"(1, \"local\", token_bytes(32)), (2, \"local\", token_bytes(32)), (3, \"local\", token_bytes(32)), (4, \"local\", token_bytes(32)), (1,",
"Key, NotSupportedError from pyseto.key_interface import KeyInterface from pyseto.utils import base64url_decode from .utils import",
"\"\"\" @pytest.mark.parametrize( \"version, purpose, key\", [ (1, \"local\", token_bytes(32)), (2, \"local\", token_bytes(32)), (3,",
"token_bytes(32)), ], ) def test_key_new_local(self, version, purpose, key): k = Key.new(version, purpose, key)",
"assert \"A key for public does not have decrypt().\" in str(err.value) @pytest.mark.parametrize( \"version,",
"load_jwk(\"keys/private_key_ed25519.json\"), \"Invalid version: 0.\"), ( 2, {\"x\": b\"xxx\", \"y\": b\"\", \"d\": b\"ddd\"}, \"Only",
"2, {\"x\": b\"xxx\", \"y\": b\"\", \"d\": b\"ddd\"}, \"Only one of x or d",
"is not RSA key.\", ), ( 1, load_key(\"keys/public_key_ecdsa_p384.pem\"), \"The key is not RSA",
"{\"x\": b\"\", \"y\": b\"\", \"d\": b\"ddd\"}, \"Failed to load key.\"), ( 4, {\"x\":",
"for v4.public.\", ), (4, {\"x\": b\"xxx\", \"y\": b\"\", \"d\": b\"\"}, \"Failed to load",
"Key.new(version, \"local\", token_bytes(32)) wk1 = token_bytes(32) wk2 = token_bytes(32) wpk = k.to_paserk(wrapping_key=wk1) with",
"d should be set for v2.public.\", ), ( 3, {\"x\": b\"xxx\", \"y\": b\"\",",
"load_key(\"keys/private_key_ecdsa_p384.pem\")), (3, \"public\", load_key(\"keys/public_key_ecdsa_p384.pem\")), (4, \"public\", load_key(\"keys/private_key_ed25519.pem\")), (4, \"public\", load_key(\"keys/public_key_ed25519.pem\")), ], ) def",
"\"v1.public is not supported on from_key_parameters.\", ), (999, load_jwk(\"keys/private_key_ed25519.json\"), \"Invalid version: 999.\"), (0,",
"base64url_decode(\"_XyN9woHaS0mPimSW-etwJMEDSzxIMjp4PjezavU8SHJoClz1bQrcmPb1ZJxHxhI\"), \"y\": base64url_decode(\"<KEY>\"), \"d\": b\"ddd\", }, \"Failed to load key.\", ), ( 4,",
"), ( 4, {\"x\": b\"xxx\", \"y\": b\"\", \"d\": b\"ddd\"}, \"Only one of x",
"load_key(\"keys/public_key_ed25519.pem\")), (3, \"public\", load_key(\"keys/public_key_ecdsa_p384.pem\")), (4, \"public\", load_key(\"keys/public_key_ed25519.pem\")), ], ) def test_key_to_paserk_public(self, version, purpose,",
"key.\"), (1, load_key(\"keys/public_key_ed25519.pem\"), \"The key is not RSA key.\"), ( 1, load_key(\"keys/private_key_ecdsa_p384.pem\"), \"The",
"key for public does not have encrypt().\" in str(err.value) with pytest.raises(NotSupportedError) as err:",
"k.verify(b\"xxxxxx\") pytest.fail(\"Key.verify() should fail.\") assert \"A key for local does not have verify().\"",
"str(err.value) @pytest.mark.parametrize( \"paserk, msg\", [ (\"k1.local.AAAAAAAAAAAAAAAA\", \"Invalid PASERK type: local.\"), (\"k1.public.AAAAAAAAAAAAAAAA\", \"Invalid PASERK",
") def test_key_from_paserk_for_local_with_wrong_wrapping_key(self, version): k = Key.new(version, \"local\", token_bytes(32)) wk1 = token_bytes(32) wk2",
"pytest.raises(ValueError) as err: k.to_paserk(wrapping_key=\"xxx\", password=\"<PASSWORD>\") pytest.fail(\"to_paserk() should fail.\") assert \"Only one of wrapping_key",
"b\"\", \"d\": b\"\"}, \"Failed to load key.\"), (2, {\"x\": b\"\", \"y\": b\"\", \"d\":",
"(\"v*\", \"local\", token_bytes(32), \"Invalid version: v*.\"), (\"v0\", \"local\", token_bytes(32), \"Invalid version: v0.\"), (0,",
"or d should be set for v4.public.\", ), (4, {\"x\": b\"xxx\", \"y\": b\"\",",
"k.to_paserk().startswith(f\"k{k.version}.public.\") @pytest.mark.parametrize( \"version, purpose, key\", [ (1, \"public\", load_key(\"keys/private_key_rsa.pem\")), (2, \"public\", load_key(\"keys/private_key_ed25519.pem\")), (3,",
"\"public\", load_key(\"keys/private_key_ed25519.pem\")), (4, \"public\", load_key(\"keys/public_key_ed25519.pem\")), ], ) def test_key_new_public(self, version, purpose, key): k",
"token_bytes(32)), (4, \"local\", token_bytes(32)), ], ) def test_key_new_local(self, version, purpose, key): k =",
"KeyInterface) assert k.version == version assert k.purpose == \"public\" @pytest.mark.parametrize( \"paserk\", [ \"k1.local.AAAAAAAAAAAAAAAA\",",
"x or d should be set for v2.public.\", ), (2, {\"x\": b\"xxx\", \"y\":",
"assert k.to_paserk().startswith(f\"k{k.version}.public.\") @pytest.mark.parametrize( \"version, purpose, key\", [ (1, \"public\", load_key(\"keys/private_key_rsa.pem\")), (2, \"public\", load_key(\"keys/private_key_ed25519.pem\")),",
"key.\"), (4, load_key(\"keys/public_key_rsa.pem\"), \"The key is not Ed25519 key.\"), ( 4, load_key(\"keys/private_key_ecdsa_p384.pem\"), \"The",
"as err: k.to_paserk(wrapping_key=\"xxx\", password=\"<PASSWORD>\") pytest.fail(\"to_paserk() should fail.\") assert \"Only one of wrapping_key or",
"Key.new(version, purpose, key) assert isinstance(k, KeyInterface) assert k.version == version assert k.purpose ==",
"v4.public.\", ), (4, {\"x\": b\"xxx\", \"y\": b\"\", \"d\": b\"\"}, \"Failed to load key.\"),",
"with pytest.raises(ValueError) as err: Key.from_asymmetric_key_params(version, x=key[\"x\"], y=key[\"y\"], d=key[\"d\"]) pytest.fail(\"Key.from_asymmetric_key_params() should fail.\") assert msg",
"pytest.raises(ValueError) as err: k.to_paserk(password=wk) pytest.fail(\"to_paserk() should fail.\") assert \"Public key cannot be wrapped.\"",
"\"local\", token_bytes(32), \"Invalid version: 0.\"), ( \"v*\", \"public\", load_key(\"keys/private_key_rsa.pem\"), \"Invalid version: v*.\", ),",
"1, 2, 3, 4, ], ) def test_key_from_paserk_for_local_with_wrong_password(self, version): k = Key.new(version, \"local\",",
"( 2, {\"x\": b\"\", \"y\": b\"\", \"d\": b\"\"}, \"x or d should be",
"), (4, {\"x\": b\"xxx\", \"y\": b\"\", \"d\": b\"\"}, \"Failed to load key.\"), (4,",
"(3, load_key(\"keys/private_key_ecdsa_p384.pem\")), (4, load_key(\"keys/private_key_ed25519.pem\")), ], ) def test_key_from_paserk_for_private_key_with_wrong_wrapping_key(self, version, key): k = Key.new(version,",
"@pytest.mark.parametrize( \"version, purpose, key\", [ (1, \"local\", token_bytes(32)), (2, \"local\", token_bytes(32)), (3, \"local\",",
"\"public\", load_key(\"keys/public_key_ecdsa_p384.pem\")), (4, \"public\", load_key(\"keys/public_key_ed25519.pem\")), ], ) def test_key_to_paserk_public(self, version, purpose, key): k",
"*.\"), (\"k1.xxx.AAAAAAAAAAAAAAAA\", \"Invalid PASERK key type: xxx.\"), ], ) def test_key_from_paserk_with_invalid_args(self, paserk, msg):",
"k = Key.new(version, purpose, key) assert k.to_paserk().startswith(f\"k{k.version}.secret.\") @pytest.mark.parametrize( \"version, purpose, key\", [ (1,",
"test_key_new_local(self, version, purpose, key): k = Key.new(version, purpose, key) assert isinstance(k, KeyInterface) assert",
"one of x or d should be set for v2.public.\", ), (2, {\"x\":",
"key): k = Key.new(version, purpose, key) assert isinstance(k, KeyInterface) assert k.version == version",
") def test_key_new_public_with_wrong_key(self, version, key, msg): with pytest.raises(ValueError) as err: Key.new(version, \"public\", key)",
"], ) def test_key_to_paserk_secret_with_wrapping_key_and_password(self, version, purpose, key): k = Key.new(version, purpose, key) with",
"\"public\", load_key(\"keys/public_key_rsa.pem\")), (2, \"public\", load_key(\"keys/private_key_ed25519.pem\")), (2, \"public\", load_key(\"keys/public_key_ed25519.pem\")), (3, \"public\", load_key(\"keys/private_key_ecdsa_p384.pem\")), (3, \"public\",",
"== version assert k.purpose == purpose with pytest.raises(NotSupportedError) as err: k.sign(b\"Hello world!\") pytest.fail(\"Key.sign()",
"in str(err.value) @pytest.mark.parametrize( \"paserk, msg\", [ (\"v1.local.AAAAAAAAAAAAAAAA\", \"Invalid PASERK version: v1.\"), (\"*.local.AAAAAAAAAAAAAAAA\", \"Invalid",
"k.to_paserk(wrapping_key=wk1) with pytest.raises(DecryptError) as err: Key.from_paserk(wpk, wrapping_key=wk2) pytest.fail(\"Key.from_paserk() should fail.\") assert \"Failed to",
"\"public\", key) wk = token_bytes(32) with pytest.raises(ValueError) as err: k.to_paserk(wrapping_key=wk) pytest.fail(\"to_paserk() should fail.\")",
"be set for v3.public.\", ), (3, {\"x\": b\"xxx\", \"y\": b\"yyy\", \"d\": b\"\"}, \"Failed",
"Key.new(version, \"public\", key) wk1 = token_bytes(32) wk2 = token_bytes(32) wpk = k.to_paserk(wrapping_key=wk1) with",
"msg\", [ (\"v1.local.AAAAAAAAAAAAAAAA\", \"Invalid PASERK version: v1.\"), (\"*.local.AAAAAAAAAAAAAAAA\", \"Invalid PASERK version: *.\"), (\"k1.xxx.AAAAAAAAAAAAAAAA\",",
"(1, \"public\", \"-----BEGIN BAD\", \"Invalid or unsupported PEM format.\"), ], ) def test_key_new_with_invalid_arg(self,",
"a key.\" in str(err.value) @pytest.mark.parametrize( \"version\", [ 1, 2, 3, 4, ], )",
"local.\"), (\"k1.public.AAAAAAAAAAAAAAAA\", \"Invalid PASERK type: public.\"), (\"k2.local.AAAAAAAAAAAAAAAA\", \"Invalid PASERK type: local.\"), (\"k2.public.AAAAAAAAAAAAAAAA\", \"Invalid",
"Key.new(version, \"local\", token_bytes(32)) wk1 = token_bytes(32) wk2 = token_bytes(32) wpk = k.to_paserk(password=wk1) with",
"load_key(\"keys/public_key_rsa.pem\")), (2, load_key(\"keys/public_key_ed25519.pem\")), (3, load_key(\"keys/public_key_ecdsa_p384.pem\")), (4, load_key(\"keys/public_key_ed25519.pem\")), ], ) def test_key_from_paserk_for_public_key_with_wrapping_key(self, version, key):",
"}, \"Failed to load key.\", ), ( 4, {\"x\": b\"xxx\", \"y\": b\"\", \"d\":",
"token_bytes(32) with pytest.raises(ValueError) as err: k.to_paserk(wrapping_key=wk) pytest.fail(\"to_paserk() should fail.\") assert \"Public key cannot",
"with pytest.raises(ValueError) as err: k.to_paserk(wrapping_key=\"xxx\", password=\"<PASSWORD>\") pytest.fail(\"to_paserk() should fail.\") assert \"Only one of",
"\"public\", load_key(\"keys/private_key_ed25519.pem\")), (3, \"public\", load_key(\"keys/private_key_ecdsa_p384.pem\")), (4, \"public\", load_key(\"keys/private_key_ed25519.pem\")), ], ) def test_key_to_paserk_secret_with_wrapping_key_and_password(self, version,",
"\"Invalid version: 0.\"), ( \"v*\", \"public\", load_key(\"keys/private_key_rsa.pem\"), \"Invalid version: v*.\", ), ( \"v0\",",
"(\"k2.local.AAAAAAAAAAAAAAAA\", \"Invalid PASERK type: local.\"), (\"k2.public.AAAAAAAAAAAAAAAA\", \"Invalid PASERK type: public.\"), (\"k3.local.AAAAAAAAAAAAAAAA\", \"Invalid PASERK",
"load_key(\"keys/private_key_ed25519.pem\")), (3, \"public\", load_key(\"keys/private_key_ecdsa_p384.pem\")), (4, \"public\", load_key(\"keys/private_key_ed25519.pem\")), ], ) def test_key_to_paserk_secret(self, version, purpose,",
"load_key(\"keys/private_key_rsa.pem\"), \"Invalid version: 0.\", ), (1, \"xxx\", token_bytes(32), \"Invalid purpose: xxx.\"), (1, \"public\",",
"should fail.\") assert msg in str(err.value) @pytest.mark.parametrize( \"version\", [ 1, 2, 3, 4,",
"not ECDSA key.\"), (4, load_key(\"keys/private_key_rsa.pem\"), \"The key is not Ed25519 key.\"), (4, load_key(\"keys/public_key_rsa.pem\"),",
"with pytest.raises(NotSupportedError) as err: k.sign(b\"Hello world!\") pytest.fail(\"Key.sign() should fail.\") assert \"A key for",
"err: Key.new(version, \"public\", key) pytest.fail(\"Key.new should fail.\") assert msg in str(err.value) @pytest.mark.parametrize( \"version,",
"Key.new(version, \"public\", key) pytest.fail(\"Key.new should fail.\") assert msg in str(err.value) @pytest.mark.parametrize( \"version, purpose,",
"@pytest.mark.parametrize( \"version\", [ 1, 2, 3, 4, ], ) def test_key_from_paserk_for_local_with_wrong_password(self, version): k",
"(4, {\"x\": b\"xxx\", \"y\": b\"\", \"d\": b\"\"}, \"Failed to load key.\"), (4, {\"x\":",
"str(err.value) with pytest.raises(NotSupportedError) as err: k.verify(b\"xxxxxx\") pytest.fail(\"Key.verify() should fail.\") assert \"A key for",
"does not have encrypt().\" in str(err.value) with pytest.raises(NotSupportedError) as err: k.decrypt(b\"xxxxxx\") pytest.fail(\"Key.verify() should",
"to load key.\"), ( 3, { \"x\": base64url_decode(\"_XyN9woHaS0mPimSW-etwJMEDSzxIMjp4PjezavU8SHJoClz1bQrcmPb1ZJxHxhI\"), \"y\": base64url_decode(\"<KEY>\"), \"d\": b\"ddd\", },",
"err: Key.from_asymmetric_key_params(version, x=key[\"x\"], y=key[\"y\"], d=key[\"d\"]) pytest.fail(\"Key.from_asymmetric_key_params() should fail.\") assert msg in str(err.value) @pytest.mark.parametrize(",
"key) assert k.to_paserk().startswith(f\"k{k.version}.public.\") @pytest.mark.parametrize( \"version, purpose, key\", [ (1, \"public\", load_key(\"keys/private_key_rsa.pem\")), (2, \"public\",",
"key.\", ), ( 2, load_key(\"keys/public_key_ecdsa_p384.pem\"), \"The key is not Ed25519 key.\", ), (",
"purpose, key, msg): with pytest.raises(ValueError) as err: Key.new(version, purpose, key) pytest.fail(\"Key.new should fail.\")",
"\"The key is not RSA key.\"), ( 1, load_key(\"keys/private_key_ecdsa_p384.pem\"), \"The key is not",
"\"public\", load_key(\"keys/private_key_ed25519.pem\")), (2, \"public\", load_key(\"keys/public_key_ed25519.pem\")), (3, \"public\", load_key(\"keys/private_key_ecdsa_p384.pem\")), (3, \"public\", load_key(\"keys/public_key_ecdsa_p384.pem\")), (4, \"public\",",
"paserk): with pytest.raises(ValueError) as err: Key.from_paserk(paserk, wrapping_key=\"xxx\", password=\"<PASSWORD>\") pytest.fail(\"Key.from_paserk should fail.\") assert \"Only",
"token_bytes(32)), (4, \"local\", token_bytes(32)), (1, \"public\", load_key(\"keys/private_key_rsa.pem\")), (2, \"public\", load_key(\"keys/private_key_ed25519.pem\")), (3, \"public\", load_key(\"keys/private_key_ecdsa_p384.pem\")),",
"b\"\"}, \"x or d should be set for v2.public.\", ), ( 3, {\"x\":",
"def test_key_to_paserk_public(self, version, purpose, key): k = Key.new(version, purpose, key) assert k.to_paserk().startswith(f\"k{k.version}.public.\") @pytest.mark.parametrize(",
"local.\"), (\"k2.public.AAAAAAAAAAAAAAAA\", \"Invalid PASERK type: public.\"), (\"k3.local.AAAAAAAAAAAAAAAA\", \"Invalid PASERK type: local.\"), (\"k3.public.AAAAAAAAAAAAAAAA\", \"Invalid",
"or d should be set for v4.public.\", ), ], ) def test_key_from_asymmetric_params_with_invalid_arg(self, version,",
"err: k.to_paserk(password=wk) pytest.fail(\"to_paserk() should fail.\") assert \"Public key cannot be wrapped.\" in str(err.value)",
"should fail.\") assert msg in str(err.value) @pytest.mark.parametrize( \"version, key\", [ # (1, load_jwk(\"keys/private_key_rsa.json\")),",
"and y (and d) should be set for v3.public.\", ), (3, {\"x\": b\"xxx\",",
"pyseto.key_interface import KeyInterface from pyseto.utils import base64url_decode from .utils import load_jwk, load_key class",
"as err: Key.new(version, purpose, key) pytest.fail(\"Key.new should fail.\") assert msg in str(err.value) @pytest.mark.parametrize(",
"str(err.value) @pytest.mark.parametrize( \"version, purpose, key\", [ (1, \"public\", load_key(\"keys/public_key_rsa.pem\")), (2, \"public\", load_key(\"keys/public_key_ed25519.pem\")), (3,",
"pytest.raises(NotSupportedError) as err: k.verify(b\"xxxxxx\") pytest.fail(\"Key.verify() should fail.\") assert \"A key for local does",
"PASERK version: *.\"), (\"k1.xxx.AAAAAAAAAAAAAAAA\", \"Invalid PASERK key type: xxx.\"), ], ) def test_key_from_paserk_with_invalid_args(self,",
"token_bytes(32)), (1, \"public\", load_key(\"keys/private_key_rsa.pem\")), (2, \"public\", load_key(\"keys/private_key_ed25519.pem\")), (3, \"public\", load_key(\"keys/private_key_ecdsa_p384.pem\")), (4, \"public\", load_key(\"keys/private_key_ed25519.pem\")),",
"\"Invalid PASERK type: local.\"), (\"k3.public.AAAAAAAAAAAAAAAA\", \"Invalid PASERK type: public.\"), (\"k4.local.AAAAAAAAAAAAAAAA\", \"Invalid PASERK type:",
"pytest.fail(\"Key.from_paserk() should fail.\") assert \"Failed to unwrap a key.\" in str(err.value) @pytest.mark.parametrize( \"version,",
"token_bytes(32)), (3, \"local\", token_bytes(32)), (4, \"local\", token_bytes(32)), (1, \"public\", load_key(\"keys/private_key_rsa.pem\")), (2, \"public\", load_key(\"keys/private_key_ed25519.pem\")),",
"msg): with pytest.raises(ValueError) as err: Key.new(version, \"public\", key) pytest.fail(\"Key.new should fail.\") assert msg",
"(and d) should be set for v3.public.\", ), ( 3, {\"x\": b\"\", \"y\":",
"load_key(\"keys/public_key_ecdsa_p384.pem\")), (4, load_key(\"keys/public_key_ed25519.pem\")), ], ) def test_key_from_paserk_for_public_key_with_password(self, version, key): k = Key.new(version, \"public\",",
"purpose, key, msg\", [ (\"v*\", \"local\", token_bytes(32), \"Invalid version: v*.\"), (\"v0\", \"local\", token_bytes(32),",
"test_key_from_paserk_for_local_with_wrong_wrapping_key(self, version): k = Key.new(version, \"local\", token_bytes(32)) wk1 = token_bytes(32) wk2 = token_bytes(32)",
"pytest.fail(\"Key.from_asymmetric_key_params() should fail.\") assert msg in str(err.value) @pytest.mark.parametrize( \"version, purpose, key\", [ (1,",
"\"d\": b\"ddd\"}, \"Only one of x or d should be set for v2.public.\",",
"ECDSA key.\"), (4, load_key(\"keys/private_key_rsa.pem\"), \"The key is not Ed25519 key.\"), (4, load_key(\"keys/public_key_rsa.pem\"), \"The",
"msg\", [ (1, load_key(\"keys/private_key_ed25519.pem\"), \"The key is not RSA key.\"), (1, load_key(\"keys/public_key_ed25519.pem\"), \"The",
"( 0, \"public\", load_key(\"keys/private_key_rsa.pem\"), \"Invalid version: 0.\", ), (1, \"xxx\", token_bytes(32), \"Invalid purpose:",
"err: Key.new(version, purpose, key) pytest.fail(\"Key.new should fail.\") assert msg in str(err.value) @pytest.mark.parametrize( \"version,",
"k.sign(b\"Hello world!\") pytest.fail(\"Key.sign() should fail.\") assert \"A key for local does not have",
"\"Invalid or unsupported PEM format.\"), ], ) def test_key_new_with_invalid_arg(self, version, purpose, key, msg):",
"assert isinstance(k, KeyInterface) assert k.version == version assert k.purpose == \"public\" @pytest.mark.parametrize( \"paserk\",",
"\"paserk\", [ \"k1.local.AAAAAAAAAAAAAAAA\", \"k1.public.AAAAAAAAAAAAAAAA\", \"k2.local.AAAAAAAAAAAAAAAA\", \"k2.public.AAAAAAAAAAAAAAAA\", \"k3.local.AAAAAAAAAAAAAAAA\", \"k3.public.AAAAAAAAAAAAAAAA\", \"k4.local.AAAAAAAAAAAAAAAA\", \"k4.public.AAAAAAAAAAAAAAAA\", ], ) def",
"[ (1, load_key(\"keys/private_key_ed25519.pem\"), \"The key is not RSA key.\"), (1, load_key(\"keys/public_key_ed25519.pem\"), \"The key",
"\"The key is not Ed25519 key.\", ), ( 2, load_key(\"keys/public_key_ecdsa_p384.pem\"), \"The key is",
"\"k1.local.AAAAAAAAAAAAAAAA\", \"k1.public.AAAAAAAAAAAAAAAA\", \"k2.local.AAAAAAAAAAAAAAAA\", \"k2.public.AAAAAAAAAAAAAAAA\", \"k3.local.AAAAAAAAAAAAAAAA\", \"k3.public.AAAAAAAAAAAAAAAA\", \"k4.local.AAAAAAAAAAAAAAAA\", \"k4.public.AAAAAAAAAAAAAAAA\", ], ) def test_key_from_paserk_with_wrapping_key_and_password(self, paserk):",
"assert msg in str(err.value) @pytest.mark.parametrize( \"paserk, msg\", [ (\"v1.local.AAAAAAAAAAAAAAAA\", \"Invalid PASERK version: v1.\"),",
"load_key(\"keys/private_key_ecdsa_p384.pem\")), (4, load_key(\"keys/private_key_ed25519.pem\")), ], ) def test_key_from_paserk_for_private_key_with_wrong_wrapping_key(self, version, key): k = Key.new(version, \"public\",",
") def test_key_from_paserk_for_private_key_with_wrong_wrapping_key(self, version, key): k = Key.new(version, \"public\", key) wk1 = token_bytes(32)",
"\"Invalid PASERK version: v1.\"), (\"*.local.AAAAAAAAAAAAAAAA\", \"Invalid PASERK version: *.\"), (\"k1.xxx.AAAAAAAAAAAAAAAA\", \"Invalid PASERK key",
"(4, \"public\", load_key(\"keys/private_key_ed25519.pem\")), (4, \"public\", load_key(\"keys/public_key_ed25519.pem\")), ], ) def test_key_new_public(self, version, purpose, key):",
"version: v1.\"), (\"*.local.AAAAAAAAAAAAAAAA\", \"Invalid PASERK version: *.\"), (\"k1.xxx.AAAAAAAAAAAAAAAA\", \"Invalid PASERK key type: xxx.\"),",
"pytest.raises(NotSupportedError) as err: k.sign(b\"Hello world!\") pytest.fail(\"Key.sign() should fail.\") assert \"A key for local",
"key) pytest.fail(\"Key.new should fail.\") assert msg in str(err.value) @pytest.mark.parametrize( \"version, purpose, key, msg\",",
"encrypt().\" in str(err.value) with pytest.raises(NotSupportedError) as err: k.decrypt(b\"xxxxxx\") pytest.fail(\"Key.verify() should fail.\") assert \"A",
"assert msg in str(err.value) @pytest.mark.parametrize( \"version, key\", [ # (1, load_jwk(\"keys/private_key_rsa.json\")), # (1,",
"), (3, {\"x\": b\"xxx\", \"y\": b\"yyy\", \"d\": b\"\"}, \"Failed to load key.\"), (",
"( 1, load_key(\"keys/private_key_ecdsa_p384.pem\"), \"The key is not RSA key.\", ), ( 1, load_key(\"keys/public_key_ecdsa_p384.pem\"),",
"purpose, key): k = Key.new(version, purpose, key) assert k.to_paserk().startswith(f\"k{k.version}.secret.\") @pytest.mark.parametrize( \"version, purpose, key\",",
"(2, \"public\", load_key(\"keys/private_key_ed25519.pem\")), (3, \"public\", load_key(\"keys/private_key_ecdsa_p384.pem\")), (4, \"public\", load_key(\"keys/private_key_ed25519.pem\")), ], ) def test_key_to_paserk_secret_with_wrapping_key_and_password(self,",
"= Key.new(version, \"public\", key) wk1 = token_bytes(32) wk2 = token_bytes(32) wpk = k.to_paserk(wrapping_key=wk1)",
"PASERK type: public.\"), (\"k4.local.AAAAAAAAAAAAAAAA\", \"Invalid PASERK type: local.\"), (\"k4.public.AAAAAAAAAAAAAAAA\", \"Invalid PASERK type: public.\"),",
"be wrapped.\" in str(err.value) @pytest.mark.parametrize( \"version, key\", [ (1, load_key(\"keys/public_key_rsa.pem\")), (2, load_key(\"keys/public_key_ed25519.pem\")), (3,",
"token_bytes(32)) wk1 = token_bytes(32) wk2 = token_bytes(32) wpk = k.to_paserk(wrapping_key=wk1) with pytest.raises(DecryptError) as",
"(4, load_key(\"keys/private_key_rsa.pem\"), \"The key is not Ed25519 key.\"), (4, load_key(\"keys/public_key_rsa.pem\"), \"The key is",
"be set for v2.public.\", ), (2, {\"x\": b\"xxx\", \"y\": b\"\", \"d\": b\"\"}, \"Failed",
"RSA key.\"), ( 1, load_key(\"keys/private_key_ecdsa_p384.pem\"), \"The key is not RSA key.\", ), (",
"x or d should be set for v4.public.\", ), (4, {\"x\": b\"xxx\", \"y\":",
"key.\"), ( 3, { \"x\": base64url_decode(\"_XyN9woHaS0mPimSW-etwJMEDSzxIMjp4PjezavU8SHJoClz1bQrcmPb1ZJxHxhI\"), \"y\": base64url_decode(\"<KEY>\"), \"d\": b\"ddd\", }, \"Failed to",
"test_key_to_paserk_public(self, version, purpose, key): k = Key.new(version, purpose, key) assert k.to_paserk().startswith(f\"k{k.version}.public.\") @pytest.mark.parametrize( \"version,",
"should fail.\") assert \"A key for public does not have decrypt().\" in str(err.value)",
"msg in str(err.value) @pytest.mark.parametrize( \"version, purpose, key, msg\", [ (\"v*\", \"local\", token_bytes(32), \"Invalid",
"], ) def test_key_from_paserk_for_local_with_wrong_password(self, version): k = Key.new(version, \"local\", token_bytes(32)) wk1 = token_bytes(32)",
"test_key_from_paserk_for_public_key_with_password(self, version, key): k = Key.new(version, \"public\", key) wk = token_bytes(32) with pytest.raises(ValueError)",
"(1, load_key(\"keys/public_key_rsa.pem\")), (2, load_key(\"keys/public_key_ed25519.pem\")), (3, load_key(\"keys/public_key_ecdsa_p384.pem\")), (4, load_key(\"keys/public_key_ed25519.pem\")), ], ) def test_key_from_paserk_for_public_key_with_wrapping_key(self, version,",
"msg): with pytest.raises(ValueError) as err: Key.from_paserk(paserk, password=\"<PASSWORD>\") pytest.fail(\"Key.from_paserk should fail.\") assert msg in",
"b\"xxx\", \"y\": b\"yyy\", \"d\": b\"\"}, \"Failed to load key.\"), ( 3, { \"x\":",
"wk1 = token_bytes(32) wk2 = token_bytes(32) wpk = k.to_paserk(password=wk1) with pytest.raises(DecryptError) as err:",
"str(err.value) @pytest.mark.parametrize( \"version, purpose, key\", [ (1, \"public\", load_key(\"keys/private_key_rsa.pem\")), (1, \"public\", load_key(\"keys/public_key_rsa.pem\")), (2,",
"version assert k.purpose == purpose with pytest.raises(NotSupportedError) as err: k.sign(b\"Hello world!\") pytest.fail(\"Key.sign() should",
"PASERK type: public.\"), ], ) def test_key_from_paserk_with_password_for_wrong_paserk(self, paserk, msg): with pytest.raises(ValueError) as err:",
"token_bytes(32)), (2, \"local\", token_bytes(32)), (3, \"local\", token_bytes(32)), (4, \"local\", token_bytes(32)), (1, \"public\", load_key(\"keys/private_key_rsa.pem\")),",
"key, msg\", [ (\"v*\", \"local\", token_bytes(32), \"Invalid version: v*.\"), (\"v0\", \"local\", token_bytes(32), \"Invalid",
"= token_bytes(32) with pytest.raises(ValueError) as err: k.to_paserk(password=wk) pytest.fail(\"to_paserk() should fail.\") assert \"Public key",
"version: 999.\"), (0, load_jwk(\"keys/private_key_ed25519.json\"), \"Invalid version: 0.\"), ( 2, {\"x\": b\"xxx\", \"y\": b\"\",",
"(3, load_key(\"keys/public_key_ecdsa_p384.pem\")), (4, load_key(\"keys/public_key_ed25519.pem\")), ], ) def test_key_from_paserk_for_public_key_with_wrapping_key(self, version, key): k = Key.new(version,",
"world!\") pytest.fail(\"Key.sign() should fail.\") assert \"A key for public does not have encrypt().\"",
"), (1, \"xxx\", token_bytes(32), \"Invalid purpose: xxx.\"), (1, \"public\", \"-----BEGIN BAD\", \"Invalid or",
"\"Invalid PASERK version: *.\"), (\"k1.xxx.AAAAAAAAAAAAAAAA\", \"Invalid PASERK key type: xxx.\"), ], ) def",
"is not ECDSA key.\"), (3, load_key(\"keys/public_key_rsa.pem\"), \"The key is not ECDSA key.\"), (4,",
"fail.\") assert msg in str(err.value) @pytest.mark.parametrize( \"version, purpose, key, msg\", [ (\"v*\", \"local\",",
"d) should be set for v3.public.\", ), (3, {\"x\": b\"xxx\", \"y\": b\"yyy\", \"d\":",
"(4, {\"x\": b\"\", \"y\": b\"\", \"d\": b\"ddd\"}, \"Failed to load key.\"), ( 4,",
"purpose, key): k = Key.new(version, purpose, key) assert k.to_paserk().startswith(f\"k{k.version}.public.\") @pytest.mark.parametrize( \"version, purpose, key\",",
"\"The key is not ECDSA key.\"), (4, load_key(\"keys/private_key_rsa.pem\"), \"The key is not Ed25519",
"\"\"\" Tests for Key. \"\"\" @pytest.mark.parametrize( \"version, purpose, key\", [ (1, \"local\", token_bytes(32)),",
"msg in str(err.value) @pytest.mark.parametrize( \"version, key\", [ # (1, load_jwk(\"keys/private_key_rsa.json\")), # (1, load_jwk(\"keys/public_key_rsa.json\")),",
"Ed25519 key.\"), (4, load_key(\"keys/public_key_rsa.pem\"), \"The key is not Ed25519 key.\"), ( 4, load_key(\"keys/private_key_ecdsa_p384.pem\"),",
"(3, load_jwk(\"keys/private_key_ecdsa_p384.json\")), (3, load_jwk(\"keys/public_key_ecdsa_p384.json\")), (4, load_jwk(\"keys/private_key_ed25519.json\")), (4, load_jwk(\"keys/public_key_ed25519.json\")), ], ) def test_key_from_asymmetric_params(self, version,",
"= token_bytes(32) with pytest.raises(ValueError) as err: k.to_paserk(wrapping_key=wk) pytest.fail(\"to_paserk() should fail.\") assert \"Public key",
"to load key.\"), ( 4, {\"x\": b\"\", \"y\": b\"\", \"d\": b\"\"}, \"x or",
"as err: Key.from_asymmetric_key_params(version, x=key[\"x\"], y=key[\"y\"], d=key[\"d\"]) pytest.fail(\"Key.from_asymmetric_key_params() should fail.\") assert msg in str(err.value)",
") def test_key_to_paserk_secret(self, version, purpose, key): k = Key.new(version, purpose, key) assert k.to_paserk().startswith(f\"k{k.version}.secret.\")",
"test_key_from_asymmetric_params_with_invalid_arg(self, version, key, msg): with pytest.raises(ValueError) as err: Key.from_asymmetric_key_params(version, x=key[\"x\"], y=key[\"y\"], d=key[\"d\"]) pytest.fail(\"Key.from_asymmetric_key_params()",
"in str(err.value) @pytest.mark.parametrize( \"version, purpose, key\", [ (1, \"public\", load_key(\"keys/public_key_rsa.pem\")), (2, \"public\", load_key(\"keys/public_key_ed25519.pem\")),",
"v*.\", ), ( \"v0\", \"public\", load_key(\"keys/private_key_rsa.pem\"), \"Invalid version: v0.\", ), ( 0, \"public\",",
"[ (1, \"local\", token_bytes(32)), (2, \"local\", token_bytes(32)), (3, \"local\", token_bytes(32)), (4, \"local\", token_bytes(32)),",
"k.version == version assert k.purpose == \"public\" @pytest.mark.parametrize( \"paserk\", [ \"k1.local.AAAAAAAAAAAAAAAA\", \"k1.public.AAAAAAAAAAAAAAAA\", \"k2.local.AAAAAAAAAAAAAAAA\",",
"not Ed25519 key.\", ), ], ) def test_key_new_public_with_wrong_key(self, version, key, msg): with pytest.raises(ValueError)",
"{\"x\": b\"xxx\", \"y\": b\"\", \"d\": b\"ddd\"}, \"Only one of x or d should",
"fail.\") assert \"Failed to unwrap a key.\" in str(err.value) @pytest.mark.parametrize( \"version, key\", [",
"\"d\": b\"ddd\"}, \"Only one of x or d should be set for v4.public.\",",
"pytest.fail(\"Key.verify() should fail.\") assert \"A key for public does not have decrypt().\" in",
"(1, \"public\", load_key(\"keys/private_key_rsa.pem\")), (1, \"public\", load_key(\"keys/public_key_rsa.pem\")), (2, \"public\", load_key(\"keys/private_key_ed25519.pem\")), (2, \"public\", load_key(\"keys/public_key_ed25519.pem\")), (3,",
"\"Invalid version: 0.\", ), (1, \"xxx\", token_bytes(32), \"Invalid purpose: xxx.\"), (1, \"public\", \"-----BEGIN",
"err: Key.from_paserk(wpk, wrapping_key=wk2) pytest.fail(\"Key.from_paserk() should fail.\") assert \"Failed to unwrap a key.\" in",
"key): k = Key.new(version, \"public\", key) wk1 = token_bytes(32) wk2 = token_bytes(32) wpk",
"(4, \"public\", load_key(\"keys/public_key_ed25519.pem\")), ], ) def test_key_to_paserk_public(self, version, purpose, key): k = Key.new(version,",
"b\"\", \"d\": b\"ddd\"}, \"Only one of x or d should be set for",
"assert msg in str(err.value) @pytest.mark.parametrize( \"version, purpose, key, msg\", [ (\"v*\", \"local\", token_bytes(32),",
"fail.\") assert \"Only one of wrapping_key or password should be specified.\" in str(err.value)",
"with pytest.raises(ValueError) as err: Key.new(version, purpose, key) pytest.fail(\"Key.new should fail.\") assert msg in",
"str(err.value) @pytest.mark.parametrize( \"version, key\", [ (1, load_key(\"keys/private_key_rsa.pem\")), (2, load_key(\"keys/private_key_ed25519.pem\")), (3, load_key(\"keys/private_key_ecdsa_p384.pem\")), (4, load_key(\"keys/private_key_ed25519.pem\")),",
"3, {\"x\": b\"\", \"y\": b\"yyy\", \"d\": b\"ddd\"}, \"x and y (and d) should",
"\"public\", load_key(\"keys/public_key_ed25519.pem\")), ], ) def test_key_to_paserk_public(self, version, purpose, key): k = Key.new(version, purpose,",
"msg): with pytest.raises(ValueError) as err: Key.from_paserk(paserk) pytest.fail(\"Key.from_paserk should fail.\") assert msg in str(err.value)",
"(\"*.local.AAAAAAAAAAAAAAAA\", \"Invalid PASERK version: *.\"), (\"k1.xxx.AAAAAAAAAAAAAAAA\", \"Invalid PASERK key type: xxx.\"), ], )",
"set for v2.public.\", ), (2, {\"x\": b\"xxx\", \"y\": b\"\", \"d\": b\"\"}, \"Failed to",
"not Ed25519 key.\"), ( 2, load_key(\"keys/private_key_ecdsa_p384.pem\"), \"The key is not Ed25519 key.\", ),",
"(4, load_jwk(\"keys/private_key_ed25519.json\")), (4, load_jwk(\"keys/public_key_ed25519.json\")), ], ) def test_key_from_asymmetric_params(self, version, key): k = Key.from_asymmetric_key_params(version,",
"fail.\") assert \"A key for public does not have encrypt().\" in str(err.value) with",
"type: public.\"), (\"k4.local.AAAAAAAAAAAAAAAA\", \"Invalid PASERK type: local.\"), (\"k4.public.AAAAAAAAAAAAAAAA\", \"Invalid PASERK type: public.\"), ],",
"Ed25519 key.\", ), ( 2, load_key(\"keys/public_key_ecdsa_p384.pem\"), \"The key is not Ed25519 key.\", ),",
"\"d\": b\"\"}, \"x or d should be set for v2.public.\", ), ( 3,",
"(3, \"public\", load_key(\"keys/private_key_ecdsa_p384.pem\")), (4, \"public\", load_key(\"keys/private_key_ed25519.pem\")), ], ) def test_key_to_paserk_secret(self, version, purpose, key):",
"\"version, purpose, key\", [ (1, \"public\", load_key(\"keys/private_key_rsa.pem\")), (2, \"public\", load_key(\"keys/private_key_ed25519.pem\")), (3, \"public\", load_key(\"keys/private_key_ecdsa_p384.pem\")),",
"[ (\"v1.local.AAAAAAAAAAAAAAAA\", \"Invalid PASERK version: v1.\"), (\"*.local.AAAAAAAAAAAAAAAA\", \"Invalid PASERK version: *.\"), (\"k1.xxx.AAAAAAAAAAAAAAAA\", \"Invalid",
"{ \"x\": base64url_decode(\"_XyN9woHaS0mPimSW-etwJMEDSzxIMjp4PjezavU8SHJoClz1bQrcmPb1ZJxHxhI\"), \"y\": base64url_decode(\"<KEY>\"), \"d\": b\"ddd\", }, \"Failed to load key.\", ),",
"\"public\", load_key(\"keys/private_key_ed25519.pem\")), ], ) def test_key_to_paserk_secret(self, version, purpose, key): k = Key.new(version, purpose,",
"Key.new(version, purpose, key) assert k.to_paserk().startswith(f\"k{k.version}.secret.\") @pytest.mark.parametrize( \"version, purpose, key\", [ (1, \"local\", token_bytes(32)),",
"(1, \"public\", load_key(\"keys/public_key_rsa.pem\")), (2, \"public\", load_key(\"keys/public_key_ed25519.pem\")), (3, \"public\", load_key(\"keys/public_key_ecdsa_p384.pem\")), (4, \"public\", load_key(\"keys/public_key_ed25519.pem\")), ],",
"key) with pytest.raises(ValueError) as err: k.to_paserk(wrapping_key=\"xxx\", password=\"<PASSWORD>\") pytest.fail(\"to_paserk() should fail.\") assert \"Only one",
"(2, \"public\", load_key(\"keys/public_key_ed25519.pem\")), (3, \"public\", load_key(\"keys/private_key_ecdsa_p384.pem\")), (3, \"public\", load_key(\"keys/public_key_ecdsa_p384.pem\")), (4, \"public\", load_key(\"keys/private_key_ed25519.pem\")), (4,",
"test_key_from_paserk_for_local_with_wrong_password(self, version): k = Key.new(version, \"local\", token_bytes(32)) wk1 = token_bytes(32) wk2 = token_bytes(32)",
"key.\", ), ( 3, load_key(\"keys/public_key_ed25519.pem\"), \"The key is not ECDSA key.\", ), (3,",
"version: 0.\", ), (1, \"xxx\", token_bytes(32), \"Invalid purpose: xxx.\"), (1, \"public\", \"-----BEGIN BAD\",",
"\"y\": b\"\", \"d\": b\"\"}, \"x or d should be set for v2.public.\", ),",
"# (1, load_jwk(\"keys/private_key_rsa.json\")), # (1, load_jwk(\"keys/public_key_rsa.json\")), (2, load_jwk(\"keys/private_key_ed25519.json\")), (2, load_jwk(\"keys/public_key_ed25519.json\")), (3, load_jwk(\"keys/private_key_ecdsa_p384.json\")), (3,",
"have sign().\" in str(err.value) with pytest.raises(NotSupportedError) as err: k.verify(b\"xxxxxx\") pytest.fail(\"Key.verify() should fail.\") assert",
"pytest.raises(ValueError) as err: Key.from_paserk(paserk) pytest.fail(\"Key.from_paserk should fail.\") assert msg in str(err.value) @pytest.mark.parametrize( \"version\",",
"d should be set for v4.public.\", ), (4, {\"x\": b\"xxx\", \"y\": b\"\", \"d\":",
"\"y\": b\"\", \"d\": b\"ddd\"}, \"Failed to load key.\"), ( 4, {\"x\": b\"\", \"y\":",
"key, msg\", [ ( 1, load_jwk(\"keys/private_key_rsa.json\"), \"v1.public is not supported on from_key_parameters.\", ),",
"local does not have verify().\" in str(err.value) @pytest.mark.parametrize( \"version, purpose, key\", [ (1,",
"key is not Ed25519 key.\", ), ( 2, load_key(\"keys/public_key_ecdsa_p384.pem\"), \"The key is not",
"version assert k.purpose == \"public\" @pytest.mark.parametrize( \"paserk\", [ \"k1.local.AAAAAAAAAAAAAAAA\", \"k1.public.AAAAAAAAAAAAAAAA\", \"k2.local.AAAAAAAAAAAAAAAA\", \"k2.public.AAAAAAAAAAAAAAAA\", \"k3.local.AAAAAAAAAAAAAAAA\",",
"0, \"public\", load_key(\"keys/private_key_rsa.pem\"), \"Invalid version: 0.\", ), (1, \"xxx\", token_bytes(32), \"Invalid purpose: xxx.\"),",
"d=key[\"d\"]) assert isinstance(k, KeyInterface) assert k.version == version assert k.purpose == \"public\" @pytest.mark.parametrize(",
"(\"k3.public.AAAAAAAAAAAAAAAA\", \"Invalid PASERK type: public.\"), (\"k4.local.AAAAAAAAAAAAAAAA\", \"Invalid PASERK type: local.\"), (\"k4.public.AAAAAAAAAAAAAAAA\", \"Invalid PASERK",
"is not ECDSA key.\"), (4, load_key(\"keys/private_key_rsa.pem\"), \"The key is not Ed25519 key.\"), (4,",
"or d should be set for v2.public.\", ), ( 3, {\"x\": b\"xxx\", \"y\":",
"key.\"), ( 4, load_key(\"keys/private_key_ecdsa_p384.pem\"), \"The key is not Ed25519 key.\", ), ( 4,",
"\"Invalid PASERK type: local.\"), (\"k4.public.AAAAAAAAAAAAAAAA\", \"Invalid PASERK type: public.\"), ], ) def test_key_from_paserk_with_password_for_wrong_paserk(self,",
"as err: k.verify(b\"xxxxxx\") pytest.fail(\"Key.verify() should fail.\") assert \"A key for local does not",
"purpose: xxx.\"), (1, \"public\", \"-----BEGIN BAD\", \"Invalid or unsupported PEM format.\"), ], )",
"be set for v4.public.\", ), (4, {\"x\": b\"xxx\", \"y\": b\"\", \"d\": b\"\"}, \"Failed",
"k.version == version assert k.purpose == purpose with pytest.raises(NotSupportedError) as err: k.encrypt(b\"Hello world!\")",
"\"Failed to load key.\"), ( 2, {\"x\": b\"\", \"y\": b\"\", \"d\": b\"\"}, \"x",
"\"public\", load_key(\"keys/private_key_ecdsa_p384.pem\")), (4, \"public\", load_key(\"keys/private_key_ed25519.pem\")), ], ) def test_key_to_paserk_secret(self, version, purpose, key): k",
"k.version == version assert k.purpose == purpose with pytest.raises(NotSupportedError) as err: k.sign(b\"Hello world!\")",
"version, key): k = Key.new(version, \"public\", key) wk = token_bytes(32) with pytest.raises(ValueError) as",
"(1, load_key(\"keys/public_key_rsa.pem\")), (2, load_key(\"keys/public_key_ed25519.pem\")), (3, load_key(\"keys/public_key_ecdsa_p384.pem\")), (4, load_key(\"keys/public_key_ed25519.pem\")), ], ) def test_key_from_paserk_for_public_key_with_password(self, version,",
"], ) def test_key_from_paserk_with_wrapping_key_and_password(self, paserk): with pytest.raises(ValueError) as err: Key.from_paserk(paserk, wrapping_key=\"xxx\", password=\"<PASSWORD>\") pytest.fail(\"Key.from_paserk",
"import load_jwk, load_key class TestKey: \"\"\" Tests for Key. \"\"\" @pytest.mark.parametrize( \"version, purpose,",
"load_key(\"keys/private_key_ed25519.pem\"), \"The key is not RSA key.\"), (1, load_key(\"keys/public_key_ed25519.pem\"), \"The key is not",
"purpose, key) assert k.to_paserk().startswith(f\"k{k.version}.secret.\") @pytest.mark.parametrize( \"version, purpose, key\", [ (1, \"local\", token_bytes(32)), (2,",
"with pytest.raises(NotSupportedError) as err: k.verify(b\"xxxxxx\") pytest.fail(\"Key.verify() should fail.\") assert \"A key for local",
"( 4, load_key(\"keys/private_key_ecdsa_p384.pem\"), \"The key is not Ed25519 key.\", ), ( 4, load_key(\"keys/public_key_ecdsa_p384.pem\"),",
"\"A key for local does not have verify().\" in str(err.value) @pytest.mark.parametrize( \"version, purpose,",
"key is not Ed25519 key.\", ), ( 3, load_key(\"keys/private_key_ed25519.pem\"), \"The key is not",
"not ECDSA key.\", ), (3, load_key(\"keys/private_key_rsa.pem\"), \"The key is not ECDSA key.\"), (3,",
"0.\"), ( 2, {\"x\": b\"xxx\", \"y\": b\"\", \"d\": b\"ddd\"}, \"Only one of x",
"load_key(\"keys/private_key_rsa.pem\"), \"The key is not Ed25519 key.\"), (2, load_key(\"keys/public_key_rsa.pem\"), \"The key is not",
"load key.\"), ( 4, {\"x\": b\"\", \"y\": b\"\", \"d\": b\"\"}, \"x or d",
"key): k = Key.new(version, purpose, key) assert k.to_paserk().startswith(f\"k{k.version}.public.\") @pytest.mark.parametrize( \"version, purpose, key\", [",
"load_key(\"keys/private_key_rsa.pem\"), \"Invalid version: v*.\", ), ( \"v0\", \"public\", load_key(\"keys/private_key_rsa.pem\"), \"Invalid version: v0.\", ),",
"key.\"), (2, {\"x\": b\"\", \"y\": b\"\", \"d\": b\"ddd\"}, \"Failed to load key.\"), (",
"test_key_from_paserk_with_password_for_wrong_paserk(self, paserk, msg): with pytest.raises(ValueError) as err: Key.from_paserk(paserk, password=\"<PASSWORD>\") pytest.fail(\"Key.from_paserk should fail.\") assert",
"b\"yyy\", \"d\": b\"\"}, \"Failed to load key.\"), ( 3, { \"x\": base64url_decode(\"_XyN9woHaS0mPimSW-etwJMEDSzxIMjp4PjezavU8SHJoClz1bQrcmPb1ZJxHxhI\"), \"y\":",
"is not Ed25519 key.\"), ( 4, load_key(\"keys/private_key_ecdsa_p384.pem\"), \"The key is not Ed25519 key.\",",
"\"public\", key) wk1 = token_bytes(32) wk2 = token_bytes(32) wpk = k.to_paserk(wrapping_key=wk1) with pytest.raises(DecryptError)",
"1, load_key(\"keys/private_key_ecdsa_p384.pem\"), \"The key is not RSA key.\", ), ( 1, load_key(\"keys/public_key_ecdsa_p384.pem\"), \"The",
"cannot be wrapped.\" in str(err.value) @pytest.mark.parametrize( \"version, key\", [ (1, load_key(\"keys/public_key_rsa.pem\")), (2, load_key(\"keys/public_key_ed25519.pem\")),",
"key is not RSA key.\", ), ( 1, load_key(\"keys/public_key_ecdsa_p384.pem\"), \"The key is not",
"\"v*\", \"public\", load_key(\"keys/private_key_rsa.pem\"), \"Invalid version: v*.\", ), ( \"v0\", \"public\", load_key(\"keys/private_key_rsa.pem\"), \"Invalid version:",
"Key.new(version, purpose, key) with pytest.raises(ValueError) as err: k.to_paserk(wrapping_key=\"xxx\", password=\"<PASSWORD>\") pytest.fail(\"to_paserk() should fail.\") assert",
"v2.public.\", ), ( 3, {\"x\": b\"xxx\", \"y\": b\"\", \"d\": b\"ddd\"}, \"x and y",
"set for v3.public.\", ), (3, {\"x\": b\"xxx\", \"y\": b\"yyy\", \"d\": b\"\"}, \"Failed to",
"str(err.value) with pytest.raises(NotSupportedError) as err: k.decrypt(b\"xxxxxx\") pytest.fail(\"Key.verify() should fail.\") assert \"A key for",
"ECDSA key.\"), (3, load_key(\"keys/public_key_rsa.pem\"), \"The key is not ECDSA key.\"), (4, load_key(\"keys/private_key_rsa.pem\"), \"The",
"xxx.\"), ], ) def test_key_from_paserk_with_invalid_args(self, paserk, msg): with pytest.raises(ValueError) as err: Key.from_paserk(paserk) pytest.fail(\"Key.from_paserk",
"pytest.raises(ValueError) as err: Key.new(version, purpose, key) pytest.fail(\"Key.new should fail.\") assert msg in str(err.value)",
"for v3.public.\", ), (3, {\"x\": b\"xxx\", \"y\": b\"yyy\", \"d\": b\"\"}, \"Failed to load",
"], ) def test_key_new_public(self, version, purpose, key): k = Key.new(version, purpose, key) assert",
"\"Invalid PASERK key type: xxx.\"), ], ) def test_key_from_paserk_with_invalid_args(self, paserk, msg): with pytest.raises(ValueError)",
"load_key(\"keys/private_key_ed25519.pem\")), ], ) def test_key_to_paserk_secret_with_wrapping_key_and_password(self, version, purpose, key): k = Key.new(version, purpose, key)",
"is not supported on from_key_parameters.\", ), (999, load_jwk(\"keys/private_key_ed25519.json\"), \"Invalid version: 999.\"), (0, load_jwk(\"keys/private_key_ed25519.json\"),",
"as err: k.to_paserk(wrapping_key=wk) pytest.fail(\"to_paserk() should fail.\") assert \"Public key cannot be wrapped.\" in",
"v3.public.\", ), ( 3, {\"x\": b\"\", \"y\": b\"yyy\", \"d\": b\"ddd\"}, \"x and y",
"version, purpose, key): k = Key.new(version, purpose, key) with pytest.raises(ValueError) as err: k.to_paserk(wrapping_key=\"xxx\",",
"\"Invalid version: v0.\"), (0, \"local\", token_bytes(32), \"Invalid version: 0.\"), ( \"v*\", \"public\", load_key(\"keys/private_key_rsa.pem\"),",
"load_key(\"keys/private_key_rsa.pem\")), (1, \"public\", load_key(\"keys/public_key_rsa.pem\")), (2, \"public\", load_key(\"keys/private_key_ed25519.pem\")), (2, \"public\", load_key(\"keys/public_key_ed25519.pem\")), (3, \"public\", load_key(\"keys/private_key_ecdsa_p384.pem\")),",
"fail.\") assert \"Public key cannot be wrapped.\" in str(err.value) @pytest.mark.parametrize( \"version, key, msg\",",
"( 2, {\"x\": b\"xxx\", \"y\": b\"\", \"d\": b\"ddd\"}, \"Only one of x or",
"one of wrapping_key or password should be specified.\" in str(err.value) @pytest.mark.parametrize( \"paserk, msg\",",
"key.\", ), ( 1, load_key(\"keys/public_key_ecdsa_p384.pem\"), \"The key is not RSA key.\", ), (2,",
"base64url_decode(\"<KEY>\"), \"d\": b\"ddd\", }, \"Failed to load key.\", ), ( 4, {\"x\": b\"xxx\",",
"\"k1.public.AAAAAAAAAAAAAAAA\", \"k2.local.AAAAAAAAAAAAAAAA\", \"k2.public.AAAAAAAAAAAAAAAA\", \"k3.local.AAAAAAAAAAAAAAAA\", \"k3.public.AAAAAAAAAAAAAAAA\", \"k4.local.AAAAAAAAAAAAAAAA\", \"k4.public.AAAAAAAAAAAAAAAA\", ], ) def test_key_from_paserk_with_wrapping_key_and_password(self, paserk): with",
"@pytest.mark.parametrize( \"version, key\", [ (1, load_key(\"keys/private_key_rsa.pem\")), (2, load_key(\"keys/private_key_ed25519.pem\")), (3, load_key(\"keys/private_key_ecdsa_p384.pem\")), (4, load_key(\"keys/private_key_ed25519.pem\")), ],",
"[ # (1, load_jwk(\"keys/private_key_rsa.json\")), # (1, load_jwk(\"keys/public_key_rsa.json\")), (2, load_jwk(\"keys/private_key_ed25519.json\")), (2, load_jwk(\"keys/public_key_ed25519.json\")), (3, load_jwk(\"keys/private_key_ecdsa_p384.json\")),",
"\"y\": b\"\", \"d\": b\"ddd\"}, \"x and y (and d) should be set for",
"), (999, load_jwk(\"keys/private_key_ed25519.json\"), \"Invalid version: 999.\"), (0, load_jwk(\"keys/private_key_ed25519.json\"), \"Invalid version: 0.\"), ( 2,",
"[ 1, 2, 3, 4, ], ) def test_key_from_paserk_for_local_with_wrong_password(self, version): k = Key.new(version,",
"[ (\"v*\", \"local\", token_bytes(32), \"Invalid version: v*.\"), (\"v0\", \"local\", token_bytes(32), \"Invalid version: v0.\"),",
"load key.\", ), ( 4, {\"x\": b\"xxx\", \"y\": b\"\", \"d\": b\"ddd\"}, \"Only one",
"not have verify().\" in str(err.value) @pytest.mark.parametrize( \"version, purpose, key\", [ (1, \"public\", load_key(\"keys/private_key_rsa.pem\")),",
"def test_key_new_with_invalid_arg(self, version, purpose, key, msg): with pytest.raises(ValueError) as err: Key.new(version, purpose, key)",
"assert \"A key for public does not have encrypt().\" in str(err.value) with pytest.raises(NotSupportedError)",
"( 3, load_key(\"keys/public_key_ed25519.pem\"), \"The key is not ECDSA key.\", ), (3, load_key(\"keys/private_key_rsa.pem\"), \"The",
"@pytest.mark.parametrize( \"paserk, msg\", [ (\"k1.local.AAAAAAAAAAAAAAAA\", \"Invalid PASERK type: local.\"), (\"k1.public.AAAAAAAAAAAAAAAA\", \"Invalid PASERK type:",
"\"k2.public.AAAAAAAAAAAAAAAA\", \"k3.local.AAAAAAAAAAAAAAAA\", \"k3.public.AAAAAAAAAAAAAAAA\", \"k4.local.AAAAAAAAAAAAAAAA\", \"k4.public.AAAAAAAAAAAAAAAA\", ], ) def test_key_from_paserk_with_wrapping_key_and_password(self, paserk): with pytest.raises(ValueError) as",
"\"The key is not Ed25519 key.\", ), ( 3, load_key(\"keys/private_key_ed25519.pem\"), \"The key is",
"wrapped.\" in str(err.value) @pytest.mark.parametrize( \"version, key, msg\", [ ( 1, load_jwk(\"keys/private_key_rsa.json\"), \"v1.public is",
"import KeyInterface from pyseto.utils import base64url_decode from .utils import load_jwk, load_key class TestKey:",
"assert k.purpose == purpose with pytest.raises(NotSupportedError) as err: k.encrypt(b\"Hello world!\") pytest.fail(\"Key.sign() should fail.\")",
"err: k.encrypt(b\"Hello world!\") pytest.fail(\"Key.sign() should fail.\") assert \"A key for public does not",
"\"Invalid PASERK type: public.\"), ], ) def test_key_from_paserk_with_password_for_wrong_paserk(self, paserk, msg): with pytest.raises(ValueError) as",
"\"public\", load_key(\"keys/private_key_rsa.pem\")), (1, \"public\", load_key(\"keys/public_key_rsa.pem\")), (2, \"public\", load_key(\"keys/private_key_ed25519.pem\")), (2, \"public\", load_key(\"keys/public_key_ed25519.pem\")), (3, \"public\",",
"msg in str(err.value) @pytest.mark.parametrize( \"paserk, msg\", [ (\"v1.local.AAAAAAAAAAAAAAAA\", \"Invalid PASERK version: v1.\"), (\"*.local.AAAAAAAAAAAAAAAA\",",
"a key.\" in str(err.value) @pytest.mark.parametrize( \"version, key\", [ (1, load_key(\"keys/private_key_rsa.pem\")), (2, load_key(\"keys/private_key_ed25519.pem\")), (3,",
"is not RSA key.\"), (1, load_key(\"keys/public_key_ed25519.pem\"), \"The key is not RSA key.\"), (",
"should fail.\") assert msg in str(err.value) @pytest.mark.parametrize( \"version, purpose, key\", [ (1, \"public\",",
"secrets import token_bytes import pytest from pyseto import DecryptError, Key, NotSupportedError from pyseto.key_interface",
"(0, \"local\", token_bytes(32), \"Invalid version: 0.\"), ( \"v*\", \"public\", load_key(\"keys/private_key_rsa.pem\"), \"Invalid version: v*.\",",
"password=\"<PASSWORD>\") pytest.fail(\"Key.from_paserk should fail.\") assert \"Only one of wrapping_key or password should be",
"PASERK type: local.\"), (\"k3.public.AAAAAAAAAAAAAAAA\", \"Invalid PASERK type: public.\"), (\"k4.local.AAAAAAAAAAAAAAAA\", \"Invalid PASERK type: local.\"),",
"\"public\" @pytest.mark.parametrize( \"paserk\", [ \"k1.local.AAAAAAAAAAAAAAAA\", \"k1.public.AAAAAAAAAAAAAAAA\", \"k2.local.AAAAAAAAAAAAAAAA\", \"k2.public.AAAAAAAAAAAAAAAA\", \"k3.local.AAAAAAAAAAAAAAAA\", \"k3.public.AAAAAAAAAAAAAAAA\", \"k4.local.AAAAAAAAAAAAAAAA\", \"k4.public.AAAAAAAAAAAAAAAA\", ],",
"(2, load_key(\"keys/public_key_rsa.pem\"), \"The key is not Ed25519 key.\"), ( 2, load_key(\"keys/private_key_ecdsa_p384.pem\"), \"The key",
"4, {\"x\": b\"xxx\", \"y\": b\"\", \"d\": b\"ddd\"}, \"Only one of x or d",
"purpose, key\", [ (1, \"public\", load_key(\"keys/public_key_rsa.pem\")), (2, \"public\", load_key(\"keys/public_key_ed25519.pem\")), (3, \"public\", load_key(\"keys/public_key_ecdsa_p384.pem\")), (4,",
"), ( 0, \"public\", load_key(\"keys/private_key_rsa.pem\"), \"Invalid version: 0.\", ), (1, \"xxx\", token_bytes(32), \"Invalid",
"isinstance(k, KeyInterface) assert k.version == version assert k.purpose == \"public\" @pytest.mark.parametrize( \"paserk\", [",
"( 4, load_key(\"keys/public_key_ecdsa_p384.pem\"), \"The key is not Ed25519 key.\", ), ], ) def",
"= k.to_paserk(password=wk1) with pytest.raises(DecryptError) as err: Key.from_paserk(wpk, password=<PASSWORD>) pytest.fail(\"Key.from_paserk() should fail.\") assert \"Failed",
"(2, {\"x\": b\"xxx\", \"y\": b\"\", \"d\": b\"\"}, \"Failed to load key.\"), (2, {\"x\":",
"pytest.fail(\"Key.sign() should fail.\") assert \"A key for local does not have sign().\" in",
"load_jwk(\"keys/public_key_ed25519.json\")), (3, load_jwk(\"keys/private_key_ecdsa_p384.json\")), (3, load_jwk(\"keys/public_key_ecdsa_p384.json\")), (4, load_jwk(\"keys/private_key_ed25519.json\")), (4, load_jwk(\"keys/public_key_ed25519.json\")), ], ) def test_key_from_asymmetric_params(self,",
"def test_key_from_paserk_with_wrapping_key_and_password(self, paserk): with pytest.raises(ValueError) as err: Key.from_paserk(paserk, wrapping_key=\"xxx\", password=\"<PASSWORD>\") pytest.fail(\"Key.from_paserk should fail.\")",
"), ( \"v0\", \"public\", load_key(\"keys/private_key_rsa.pem\"), \"Invalid version: v0.\", ), ( 0, \"public\", load_key(\"keys/private_key_rsa.pem\"),",
"pytest.raises(ValueError) as err: k.to_paserk(wrapping_key=wk) pytest.fail(\"to_paserk() should fail.\") assert \"Public key cannot be wrapped.\"",
"not Ed25519 key.\", ), ( 3, load_key(\"keys/private_key_ed25519.pem\"), \"The key is not ECDSA key.\",",
"(1, load_jwk(\"keys/private_key_rsa.json\")), # (1, load_jwk(\"keys/public_key_rsa.json\")), (2, load_jwk(\"keys/private_key_ed25519.json\")), (2, load_jwk(\"keys/public_key_ed25519.json\")), (3, load_jwk(\"keys/private_key_ecdsa_p384.json\")), (3, load_jwk(\"keys/public_key_ecdsa_p384.json\")),",
"b\"yyy\", \"d\": b\"ddd\"}, \"x and y (and d) should be set for v3.public.\",",
"not Ed25519 key.\"), (2, load_key(\"keys/public_key_rsa.pem\"), \"The key is not Ed25519 key.\"), ( 2,",
"token_bytes(32) wpk = k.to_paserk(wrapping_key=wk1) with pytest.raises(DecryptError) as err: Key.from_paserk(wpk, wrapping_key=wk2) pytest.fail(\"Key.from_paserk() should fail.\")",
"4, {\"x\": b\"\", \"y\": b\"\", \"d\": b\"\"}, \"x or d should be set",
"key.\"), ( 2, load_key(\"keys/private_key_ecdsa_p384.pem\"), \"The key is not Ed25519 key.\", ), ( 2,",
"key.\", ), ], ) def test_key_new_public_with_wrong_key(self, version, key, msg): with pytest.raises(ValueError) as err:",
"(\"k1.xxx.AAAAAAAAAAAAAAAA\", \"Invalid PASERK key type: xxx.\"), ], ) def test_key_from_paserk_with_invalid_args(self, paserk, msg): with",
"k = Key.new(version, \"local\", token_bytes(32)) wk1 = token_bytes(32) wk2 = token_bytes(32) wpk =",
"token_bytes(32) with pytest.raises(ValueError) as err: k.to_paserk(password=wk) pytest.fail(\"to_paserk() should fail.\") assert \"Public key cannot",
"wrapping_key or password should be specified.\" in str(err.value) @pytest.mark.parametrize( \"paserk, msg\", [ (\"k1.local.AAAAAAAAAAAAAAAA\",",
"\"The key is not Ed25519 key.\"), (4, load_key(\"keys/public_key_rsa.pem\"), \"The key is not Ed25519",
"v3.public.\", ), (3, {\"x\": b\"xxx\", \"y\": b\"yyy\", \"d\": b\"\"}, \"Failed to load key.\"),",
"], ) def test_key_from_paserk_for_local_with_wrong_wrapping_key(self, version): k = Key.new(version, \"local\", token_bytes(32)) wk1 = token_bytes(32)",
"b\"xxx\", \"y\": b\"\", \"d\": b\"\"}, \"Failed to load key.\"), (2, {\"x\": b\"\", \"y\":",
"k = Key.new(version, purpose, key) assert isinstance(k, KeyInterface) assert k.version == version assert",
"or password should be specified.\" in str(err.value) @pytest.mark.parametrize( \"paserk, msg\", [ (\"k1.local.AAAAAAAAAAAAAAAA\", \"Invalid",
"type: public.\"), (\"k3.local.AAAAAAAAAAAAAAAA\", \"Invalid PASERK type: local.\"), (\"k3.public.AAAAAAAAAAAAAAAA\", \"Invalid PASERK type: public.\"), (\"k4.local.AAAAAAAAAAAAAAAA\",",
"4, ], ) def test_key_from_paserk_for_local_with_wrong_wrapping_key(self, version): k = Key.new(version, \"local\", token_bytes(32)) wk1 =",
"d should be set for v4.public.\", ), ], ) def test_key_from_asymmetric_params_with_invalid_arg(self, version, key,",
"[ (1, load_key(\"keys/public_key_rsa.pem\")), (2, load_key(\"keys/public_key_ed25519.pem\")), (3, load_key(\"keys/public_key_ecdsa_p384.pem\")), (4, load_key(\"keys/public_key_ed25519.pem\")), ], ) def test_key_from_paserk_for_public_key_with_wrapping_key(self,",
"should be set for v3.public.\", ), (3, {\"x\": b\"xxx\", \"y\": b\"yyy\", \"d\": b\"\"},",
"is not Ed25519 key.\", ), ], ) def test_key_new_public_with_wrong_key(self, version, key, msg): with",
"pytest.raises(ValueError) as err: Key.new(version, \"public\", key) pytest.fail(\"Key.new should fail.\") assert msg in str(err.value)",
"3, 4, ], ) def test_key_from_paserk_for_local_with_wrong_wrapping_key(self, version): k = Key.new(version, \"local\", token_bytes(32)) wk1",
"sign().\" in str(err.value) with pytest.raises(NotSupportedError) as err: k.verify(b\"xxxxxx\") pytest.fail(\"Key.verify() should fail.\") assert \"A",
"key is not ECDSA key.\", ), (3, load_key(\"keys/private_key_rsa.pem\"), \"The key is not ECDSA",
"pyseto import DecryptError, Key, NotSupportedError from pyseto.key_interface import KeyInterface from pyseto.utils import base64url_decode",
"\"The key is not Ed25519 key.\"), (2, load_key(\"keys/public_key_rsa.pem\"), \"The key is not Ed25519",
"with pytest.raises(DecryptError) as err: Key.from_paserk(wpk, wrapping_key=wk2) pytest.fail(\"Key.from_paserk() should fail.\") assert \"Failed to unwrap",
"not Ed25519 key.\"), (4, load_key(\"keys/public_key_rsa.pem\"), \"The key is not Ed25519 key.\"), ( 4,",
"2, 3, 4, ], ) def test_key_from_paserk_for_local_with_wrong_password(self, version): k = Key.new(version, \"local\", token_bytes(32))",
"(999, load_jwk(\"keys/private_key_ed25519.json\"), \"Invalid version: 999.\"), (0, load_jwk(\"keys/private_key_ed25519.json\"), \"Invalid version: 0.\"), ( 2, {\"x\":",
"(2, \"public\", load_key(\"keys/private_key_ed25519.pem\")), (2, \"public\", load_key(\"keys/public_key_ed25519.pem\")), (3, \"public\", load_key(\"keys/private_key_ecdsa_p384.pem\")), (3, \"public\", load_key(\"keys/public_key_ecdsa_p384.pem\")), (4,",
"\"y\": b\"\", \"d\": b\"ddd\"}, \"Failed to load key.\"), ( 2, {\"x\": b\"\", \"y\":",
"version: *.\"), (\"k1.xxx.AAAAAAAAAAAAAAAA\", \"Invalid PASERK key type: xxx.\"), ], ) def test_key_from_paserk_with_invalid_args(self, paserk,",
"version: v*.\"), (\"v0\", \"local\", token_bytes(32), \"Invalid version: v0.\"), (0, \"local\", token_bytes(32), \"Invalid version:",
"(2, load_jwk(\"keys/public_key_ed25519.json\")), (3, load_jwk(\"keys/private_key_ecdsa_p384.json\")), (3, load_jwk(\"keys/public_key_ecdsa_p384.json\")), (4, load_jwk(\"keys/private_key_ed25519.json\")), (4, load_jwk(\"keys/public_key_ed25519.json\")), ], ) def",
"should fail.\") assert \"Only one of wrapping_key or password should be specified.\" in",
"key, msg\", [ (1, load_key(\"keys/private_key_ed25519.pem\"), \"The key is not RSA key.\"), (1, load_key(\"keys/public_key_ed25519.pem\"),",
"load_jwk(\"keys/private_key_ed25519.json\")), (2, load_jwk(\"keys/public_key_ed25519.json\")), (3, load_jwk(\"keys/private_key_ecdsa_p384.json\")), (3, load_jwk(\"keys/public_key_ecdsa_p384.json\")), (4, load_jwk(\"keys/private_key_ed25519.json\")), (4, load_jwk(\"keys/public_key_ed25519.json\")), ], )",
"= Key.new(version, \"local\", token_bytes(32)) wk1 = token_bytes(32) wk2 = token_bytes(32) wpk = k.to_paserk(wrapping_key=wk1)",
"d) should be set for v3.public.\", ), ( 3, {\"x\": b\"\", \"y\": b\"yyy\",",
"msg): with pytest.raises(ValueError) as err: Key.from_asymmetric_key_params(version, x=key[\"x\"], y=key[\"y\"], d=key[\"d\"]) pytest.fail(\"Key.from_asymmetric_key_params() should fail.\") assert",
"pytest.fail(\"Key.verify() should fail.\") assert \"A key for local does not have verify().\" in",
"= Key.new(version, purpose, key) assert k.to_paserk().startswith(f\"k{k.version}.public.\") @pytest.mark.parametrize( \"version, purpose, key\", [ (1, \"public\",",
"], ) def test_key_from_paserk_with_password_for_wrong_paserk(self, paserk, msg): with pytest.raises(ValueError) as err: Key.from_paserk(paserk, password=\"<PASSWORD>\") pytest.fail(\"Key.from_paserk",
"\"version\", [ 1, 2, 3, 4, ], ) def test_key_from_paserk_for_local_with_wrong_password(self, version): k =",
"ECDSA key.\", ), ( 3, load_key(\"keys/public_key_ed25519.pem\"), \"The key is not ECDSA key.\", ),",
"b\"\"}, \"Failed to load key.\"), (2, {\"x\": b\"\", \"y\": b\"\", \"d\": b\"ddd\"}, \"Failed",
"(3, load_key(\"keys/public_key_ecdsa_p384.pem\")), (4, load_key(\"keys/public_key_ed25519.pem\")), ], ) def test_key_from_paserk_for_public_key_with_password(self, version, key): k = Key.new(version,",
"\"public\", key) pytest.fail(\"Key.new should fail.\") assert msg in str(err.value) @pytest.mark.parametrize( \"version, purpose, key,",
"Key.from_paserk(wpk, password=<PASSWORD>) pytest.fail(\"Key.from_paserk() should fail.\") assert \"Failed to unwrap a key.\" in str(err.value)",
"for v2.public.\", ), (2, {\"x\": b\"xxx\", \"y\": b\"\", \"d\": b\"\"}, \"Failed to load",
"load_key(\"keys/public_key_ed25519.pem\")), ], ) def test_key_to_paserk_public(self, version, purpose, key): k = Key.new(version, purpose, key)",
"KeyInterface from pyseto.utils import base64url_decode from .utils import load_jwk, load_key class TestKey: \"\"\"",
"pytest.fail(\"to_paserk() should fail.\") assert \"Public key cannot be wrapped.\" in str(err.value) @pytest.mark.parametrize( \"version,",
"def test_key_to_paserk_secret_with_wrapping_key_and_password(self, version, purpose, key): k = Key.new(version, purpose, key) with pytest.raises(ValueError) as",
"key is not ECDSA key.\", ), ( 3, load_key(\"keys/public_key_ed25519.pem\"), \"The key is not",
"wk = token_bytes(32) with pytest.raises(ValueError) as err: k.to_paserk(wrapping_key=wk) pytest.fail(\"to_paserk() should fail.\") assert \"Public",
"b\"\", \"y\": b\"\", \"d\": b\"\"}, \"x or d should be set for v2.public.\",",
"str(err.value) @pytest.mark.parametrize( \"version\", [ 1, 2, 3, 4, ], ) def test_key_from_paserk_for_local_with_wrong_wrapping_key(self, version):",
"load_key(\"keys/private_key_rsa.pem\"), \"Invalid version: v0.\", ), ( 0, \"public\", load_key(\"keys/private_key_rsa.pem\"), \"Invalid version: 0.\", ),",
"), ( 3, load_key(\"keys/private_key_ed25519.pem\"), \"The key is not ECDSA key.\", ), ( 3,",
"k.to_paserk(wrapping_key=wk) pytest.fail(\"to_paserk() should fail.\") assert \"Public key cannot be wrapped.\" in str(err.value) @pytest.mark.parametrize(",
"in str(err.value) @pytest.mark.parametrize( \"version, key\", [ (1, load_key(\"keys/private_key_rsa.pem\")), (2, load_key(\"keys/private_key_ed25519.pem\")), (3, load_key(\"keys/private_key_ecdsa_p384.pem\")), (4,",
"key is not Ed25519 key.\"), (4, load_key(\"keys/public_key_rsa.pem\"), \"The key is not Ed25519 key.\"),",
"pytest.fail(\"Key.from_paserk() should fail.\") assert \"Failed to unwrap a key.\" in str(err.value) @pytest.mark.parametrize( \"version\",",
"{\"x\": b\"xxx\", \"y\": b\"yyy\", \"d\": b\"\"}, \"Failed to load key.\"), ( 3, {",
"fail.\") assert \"A key for local does not have verify().\" in str(err.value) @pytest.mark.parametrize(",
"load_key class TestKey: \"\"\" Tests for Key. \"\"\" @pytest.mark.parametrize( \"version, purpose, key\", [",
"\"local\", token_bytes(32)), (2, \"local\", token_bytes(32)), (3, \"local\", token_bytes(32)), (4, \"local\", token_bytes(32)), ], )",
"in str(err.value) @pytest.mark.parametrize( \"version, key\", [ # (1, load_jwk(\"keys/private_key_rsa.json\")), # (1, load_jwk(\"keys/public_key_rsa.json\")), (2,",
"pytest.raises(DecryptError) as err: Key.from_paserk(wpk, password=<PASSWORD>) pytest.fail(\"Key.from_paserk() should fail.\") assert \"Failed to unwrap a",
"unwrap a key.\" in str(err.value) @pytest.mark.parametrize( \"version, key\", [ (1, load_key(\"keys/private_key_rsa.pem\")), (2, load_key(\"keys/private_key_ed25519.pem\")),",
"local.\"), (\"k4.public.AAAAAAAAAAAAAAAA\", \"Invalid PASERK type: public.\"), ], ) def test_key_from_paserk_with_password_for_wrong_paserk(self, paserk, msg): with",
"b\"\", \"y\": b\"\", \"d\": b\"ddd\"}, \"Failed to load key.\"), ( 2, {\"x\": b\"\",",
"b\"xxx\", \"y\": b\"\", \"d\": b\"ddd\"}, \"Only one of x or d should be",
"\"The key is not ECDSA key.\", ), ( 3, load_key(\"keys/public_key_ed25519.pem\"), \"The key is",
"key) assert isinstance(k, KeyInterface) assert k.version == version assert k.purpose == purpose with",
"load_key(\"keys/private_key_ed25519.pem\"), \"The key is not ECDSA key.\", ), ( 3, load_key(\"keys/public_key_ed25519.pem\"), \"The key",
"load_key(\"keys/private_key_ecdsa_p384.pem\"), \"The key is not Ed25519 key.\", ), ( 4, load_key(\"keys/public_key_ecdsa_p384.pem\"), \"The key",
"(1, load_jwk(\"keys/public_key_rsa.json\")), (2, load_jwk(\"keys/private_key_ed25519.json\")), (2, load_jwk(\"keys/public_key_ed25519.json\")), (3, load_jwk(\"keys/private_key_ecdsa_p384.json\")), (3, load_jwk(\"keys/public_key_ecdsa_p384.json\")), (4, load_jwk(\"keys/private_key_ed25519.json\")), (4,",
"wk2 = token_bytes(32) wpk = k.to_paserk(wrapping_key=wk1) with pytest.raises(DecryptError) as err: Key.from_paserk(wpk, wrapping_key=wk2) pytest.fail(\"Key.from_paserk()",
"(4, \"public\", load_key(\"keys/private_key_ed25519.pem\")), ], ) def test_key_to_paserk_secret_with_wrapping_key_and_password(self, version, purpose, key): k = Key.new(version,",
"should fail.\") assert \"A key for public does not have encrypt().\" in str(err.value)",
"is not ECDSA key.\", ), ( 3, load_key(\"keys/public_key_ed25519.pem\"), \"The key is not ECDSA",
"def test_key_from_paserk_with_invalid_args(self, paserk, msg): with pytest.raises(ValueError) as err: Key.from_paserk(paserk) pytest.fail(\"Key.from_paserk should fail.\") assert",
"( 2, load_key(\"keys/private_key_ecdsa_p384.pem\"), \"The key is not Ed25519 key.\", ), ( 2, load_key(\"keys/public_key_ecdsa_p384.pem\"),",
"token_bytes(32) wk2 = token_bytes(32) wpk = k.to_paserk(wrapping_key=wk1) with pytest.raises(DecryptError) as err: Key.from_paserk(wpk, wrapping_key=wk2)",
"\"version, purpose, key\", [ (1, \"public\", load_key(\"keys/public_key_rsa.pem\")), (2, \"public\", load_key(\"keys/public_key_ed25519.pem\")), (3, \"public\", load_key(\"keys/public_key_ecdsa_p384.pem\")),",
"\"version\", [ 1, 2, 3, 4, ], ) def test_key_from_paserk_for_local_with_wrong_wrapping_key(self, version): k =",
"token_bytes(32)) wk1 = token_bytes(32) wk2 = token_bytes(32) wpk = k.to_paserk(password=wk1) with pytest.raises(DecryptError) as",
"supported on from_key_parameters.\", ), (999, load_jwk(\"keys/private_key_ed25519.json\"), \"Invalid version: 999.\"), (0, load_jwk(\"keys/private_key_ed25519.json\"), \"Invalid version:",
"[ (1, \"public\", load_key(\"keys/private_key_rsa.pem\")), (1, \"public\", load_key(\"keys/public_key_rsa.pem\")), (2, \"public\", load_key(\"keys/private_key_ed25519.pem\")), (2, \"public\", load_key(\"keys/public_key_ed25519.pem\")),",
"\"d\": b\"ddd\"}, \"Failed to load key.\"), ( 2, {\"x\": b\"\", \"y\": b\"\", \"d\":",
"(3, \"public\", load_key(\"keys/public_key_ecdsa_p384.pem\")), (4, \"public\", load_key(\"keys/private_key_ed25519.pem\")), (4, \"public\", load_key(\"keys/public_key_ed25519.pem\")), ], ) def test_key_new_public(self,",
"password=<PASSWORD>) pytest.fail(\"Key.from_paserk() should fail.\") assert \"Failed to unwrap a key.\" in str(err.value) @pytest.mark.parametrize(",
"\"local\", token_bytes(32)), (1, \"public\", load_key(\"keys/private_key_rsa.pem\")), (2, \"public\", load_key(\"keys/private_key_ed25519.pem\")), (3, \"public\", load_key(\"keys/private_key_ecdsa_p384.pem\")), (4, \"public\",",
"\"version, purpose, key\", [ (1, \"local\", token_bytes(32)), (2, \"local\", token_bytes(32)), (3, \"local\", token_bytes(32)),",
"is not RSA key.\", ), (2, load_key(\"keys/private_key_rsa.pem\"), \"The key is not Ed25519 key.\"),",
"is not ECDSA key.\", ), (3, load_key(\"keys/private_key_rsa.pem\"), \"The key is not ECDSA key.\"),",
"PASERK type: local.\"), (\"k4.public.AAAAAAAAAAAAAAAA\", \"Invalid PASERK type: public.\"), ], ) def test_key_from_paserk_with_password_for_wrong_paserk(self, paserk,",
"version: v*.\", ), ( \"v0\", \"public\", load_key(\"keys/private_key_rsa.pem\"), \"Invalid version: v0.\", ), ( 0,",
") def test_key_from_paserk_with_invalid_args(self, paserk, msg): with pytest.raises(ValueError) as err: Key.from_paserk(paserk) pytest.fail(\"Key.from_paserk should fail.\")",
"version: 0.\"), ( 2, {\"x\": b\"xxx\", \"y\": b\"\", \"d\": b\"ddd\"}, \"Only one of",
"(3, \"public\", load_key(\"keys/public_key_ecdsa_p384.pem\")), (4, \"public\", load_key(\"keys/public_key_ed25519.pem\")), ], ) def test_key_to_paserk_public(self, version, purpose, key):",
"4, ], ) def test_key_from_paserk_for_local_with_wrong_password(self, version): k = Key.new(version, \"local\", token_bytes(32)) wk1 =",
"be wrapped.\" in str(err.value) @pytest.mark.parametrize( \"version, key, msg\", [ ( 1, load_jwk(\"keys/private_key_rsa.json\"), \"v1.public",
"wk1 = token_bytes(32) wk2 = token_bytes(32) wpk = k.to_paserk(wrapping_key=wk1) with pytest.raises(DecryptError) as err:",
"\"public\", load_key(\"keys/private_key_ecdsa_p384.pem\")), (3, \"public\", load_key(\"keys/public_key_ecdsa_p384.pem\")), (4, \"public\", load_key(\"keys/private_key_ed25519.pem\")), (4, \"public\", load_key(\"keys/public_key_ed25519.pem\")), ], )",
"load_key(\"keys/private_key_ed25519.pem\")), (3, load_key(\"keys/private_key_ecdsa_p384.pem\")), (4, load_key(\"keys/private_key_ed25519.pem\")), ], ) def test_key_from_paserk_for_private_key_with_wrong_wrapping_key(self, version, key): k =",
"2, load_key(\"keys/private_key_ecdsa_p384.pem\"), \"The key is not Ed25519 key.\", ), ( 2, load_key(\"keys/public_key_ecdsa_p384.pem\"), \"The",
"(2, load_jwk(\"keys/private_key_ed25519.json\")), (2, load_jwk(\"keys/public_key_ed25519.json\")), (3, load_jwk(\"keys/private_key_ecdsa_p384.json\")), (3, load_jwk(\"keys/public_key_ecdsa_p384.json\")), (4, load_jwk(\"keys/private_key_ed25519.json\")), (4, load_jwk(\"keys/public_key_ed25519.json\")), ],",
"assert \"Public key cannot be wrapped.\" in str(err.value) @pytest.mark.parametrize( \"version, key, msg\", [",
"load_key(\"keys/public_key_ecdsa_p384.pem\")), (4, \"public\", load_key(\"keys/public_key_ed25519.pem\")), ], ) def test_key_to_paserk_public(self, version, purpose, key): k =",
"k.purpose == purpose with pytest.raises(NotSupportedError) as err: k.sign(b\"Hello world!\") pytest.fail(\"Key.sign() should fail.\") assert",
"should be set for v3.public.\", ), ( 3, {\"x\": b\"\", \"y\": b\"yyy\", \"d\":",
"test_key_from_paserk_with_invalid_args(self, paserk, msg): with pytest.raises(ValueError) as err: Key.from_paserk(paserk) pytest.fail(\"Key.from_paserk should fail.\") assert msg",
"@pytest.mark.parametrize( \"version, purpose, key\", [ (1, \"public\", load_key(\"keys/private_key_rsa.pem\")), (1, \"public\", load_key(\"keys/public_key_rsa.pem\")), (2, \"public\",",
"( 2, load_key(\"keys/public_key_ecdsa_p384.pem\"), \"The key is not Ed25519 key.\", ), ( 3, load_key(\"keys/private_key_ed25519.pem\"),",
"\"The key is not Ed25519 key.\", ), ( 4, load_key(\"keys/public_key_ecdsa_p384.pem\"), \"The key is",
"3, 4, ], ) def test_key_from_paserk_for_local_with_wrong_password(self, version): k = Key.new(version, \"local\", token_bytes(32)) wk1",
"k = Key.new(version, \"public\", key) wk = token_bytes(32) with pytest.raises(ValueError) as err: k.to_paserk(wrapping_key=wk)",
"b\"\", \"y\": b\"yyy\", \"d\": b\"ddd\"}, \"x and y (and d) should be set",
"in str(err.value) @pytest.mark.parametrize( \"paserk, msg\", [ (\"k1.local.AAAAAAAAAAAAAAAA\", \"Invalid PASERK type: local.\"), (\"k1.public.AAAAAAAAAAAAAAAA\", \"Invalid",
"not have decrypt().\" in str(err.value) @pytest.mark.parametrize( \"version, key, msg\", [ (1, load_key(\"keys/private_key_ed25519.pem\"), \"The",
"version, purpose, key): k = Key.new(version, purpose, key) assert k.to_paserk().startswith(f\"k{k.version}.secret.\") @pytest.mark.parametrize( \"version, purpose,",
"key\", [ (1, \"public\", load_key(\"keys/private_key_rsa.pem\")), (2, \"public\", load_key(\"keys/private_key_ed25519.pem\")), (3, \"public\", load_key(\"keys/private_key_ecdsa_p384.pem\")), (4, \"public\",",
"], ) def test_key_to_paserk_secret(self, version, purpose, key): k = Key.new(version, purpose, key) assert",
"load_key(\"keys/private_key_ed25519.pem\")), (2, \"public\", load_key(\"keys/public_key_ed25519.pem\")), (3, \"public\", load_key(\"keys/private_key_ecdsa_p384.pem\")), (3, \"public\", load_key(\"keys/public_key_ecdsa_p384.pem\")), (4, \"public\", load_key(\"keys/private_key_ed25519.pem\")),",
"{\"x\": b\"xxx\", \"y\": b\"\", \"d\": b\"\"}, \"Failed to load key.\"), (4, {\"x\": b\"\",",
"= Key.new(version, \"public\", key) wk = token_bytes(32) with pytest.raises(ValueError) as err: k.to_paserk(wrapping_key=wk) pytest.fail(\"to_paserk()",
"[ (\"k1.local.AAAAAAAAAAAAAAAA\", \"Invalid PASERK type: local.\"), (\"k1.public.AAAAAAAAAAAAAAAA\", \"Invalid PASERK type: public.\"), (\"k2.local.AAAAAAAAAAAAAAAA\", \"Invalid",
"for v3.public.\", ), ( 3, {\"x\": b\"\", \"y\": b\"yyy\", \"d\": b\"ddd\"}, \"x and",
"\"version, key\", [ # (1, load_jwk(\"keys/private_key_rsa.json\")), # (1, load_jwk(\"keys/public_key_rsa.json\")), (2, load_jwk(\"keys/private_key_ed25519.json\")), (2, load_jwk(\"keys/public_key_ed25519.json\")),",
"password=\"<PASSWORD>\") pytest.fail(\"Key.from_paserk should fail.\") assert msg in str(err.value) @pytest.mark.parametrize( \"paserk, msg\", [ (\"v1.local.AAAAAAAAAAAAAAAA\",",
"load_key(\"keys/private_key_rsa.pem\"), \"The key is not Ed25519 key.\"), (4, load_key(\"keys/public_key_rsa.pem\"), \"The key is not",
"load_key(\"keys/public_key_ecdsa_p384.pem\")), (4, load_key(\"keys/public_key_ed25519.pem\")), ], ) def test_key_from_paserk_for_public_key_with_wrapping_key(self, version, key): k = Key.new(version, \"public\",",
"assert msg in str(err.value) @pytest.mark.parametrize( \"version\", [ 1, 2, 3, 4, ], )",
"[ (1, \"public\", load_key(\"keys/public_key_rsa.pem\")), (2, \"public\", load_key(\"keys/public_key_ed25519.pem\")), (3, \"public\", load_key(\"keys/public_key_ecdsa_p384.pem\")), (4, \"public\", load_key(\"keys/public_key_ed25519.pem\")),",
"b\"ddd\"}, \"x and y (and d) should be set for v3.public.\", ), (3,",
"to unwrap a key.\" in str(err.value) @pytest.mark.parametrize( \"version\", [ 1, 2, 3, 4,",
"b\"\", \"d\": b\"ddd\"}, \"x and y (and d) should be set for v3.public.\",",
") def test_key_from_paserk_for_public_key_with_password(self, version, key): k = Key.new(version, \"public\", key) wk = token_bytes(32)",
"), ( 4, load_key(\"keys/public_key_ecdsa_p384.pem\"), \"The key is not Ed25519 key.\", ), ], )",
"999.\"), (0, load_jwk(\"keys/private_key_ed25519.json\"), \"Invalid version: 0.\"), ( 2, {\"x\": b\"xxx\", \"y\": b\"\", \"d\":",
"\"d\": b\"ddd\", }, \"Failed to load key.\", ), ( 4, {\"x\": b\"xxx\", \"y\":",
"set for v4.public.\", ), ], ) def test_key_from_asymmetric_params_with_invalid_arg(self, version, key, msg): with pytest.raises(ValueError)",
"\"version, purpose, key\", [ (1, \"public\", load_key(\"keys/private_key_rsa.pem\")), (1, \"public\", load_key(\"keys/public_key_rsa.pem\")), (2, \"public\", load_key(\"keys/private_key_ed25519.pem\")),",
"\"Failed to unwrap a key.\" in str(err.value) @pytest.mark.parametrize( \"version\", [ 1, 2, 3,",
"is not Ed25519 key.\"), ( 2, load_key(\"keys/private_key_ecdsa_p384.pem\"), \"The key is not Ed25519 key.\",",
"[ \"k1.local.AAAAAAAAAAAAAAAA\", \"k1.public.AAAAAAAAAAAAAAAA\", \"k2.local.AAAAAAAAAAAAAAAA\", \"k2.public.AAAAAAAAAAAAAAAA\", \"k3.local.AAAAAAAAAAAAAAAA\", \"k3.public.AAAAAAAAAAAAAAAA\", \"k4.local.AAAAAAAAAAAAAAAA\", \"k4.public.AAAAAAAAAAAAAAAA\", ], ) def test_key_from_paserk_with_wrapping_key_and_password(self,",
"assert msg in str(err.value) @pytest.mark.parametrize( \"version, purpose, key\", [ (1, \"public\", load_key(\"keys/public_key_rsa.pem\")), (2,",
"load_key(\"keys/public_key_ed25519.pem\")), (3, load_key(\"keys/public_key_ecdsa_p384.pem\")), (4, load_key(\"keys/public_key_ed25519.pem\")), ], ) def test_key_from_paserk_for_public_key_with_password(self, version, key): k =",
"fail.\") assert \"A key for public does not have decrypt().\" in str(err.value) @pytest.mark.parametrize(",
"], ) def test_key_from_paserk_for_public_key_with_wrapping_key(self, version, key): k = Key.new(version, \"public\", key) wk =",
"unwrap a key.\" in str(err.value) @pytest.mark.parametrize( \"version\", [ 1, 2, 3, 4, ],",
"public does not have encrypt().\" in str(err.value) with pytest.raises(NotSupportedError) as err: k.decrypt(b\"xxxxxx\") pytest.fail(\"Key.verify()",
"to load key.\"), (4, {\"x\": b\"\", \"y\": b\"\", \"d\": b\"ddd\"}, \"Failed to load",
"PASERK type: public.\"), (\"k2.local.AAAAAAAAAAAAAAAA\", \"Invalid PASERK type: local.\"), (\"k2.public.AAAAAAAAAAAAAAAA\", \"Invalid PASERK type: public.\"),",
"version, key, msg): with pytest.raises(ValueError) as err: Key.from_asymmetric_key_params(version, x=key[\"x\"], y=key[\"y\"], d=key[\"d\"]) pytest.fail(\"Key.from_asymmetric_key_params() should",
"= Key.new(version, purpose, key) assert isinstance(k, KeyInterface) assert k.version == version assert k.purpose",
"key is not Ed25519 key.\"), ( 2, load_key(\"keys/private_key_ecdsa_p384.pem\"), \"The key is not Ed25519",
"public.\"), ], ) def test_key_from_paserk_with_password_for_wrong_paserk(self, paserk, msg): with pytest.raises(ValueError) as err: Key.from_paserk(paserk, password=\"<PASSWORD>\")",
"err: Key.from_paserk(paserk) pytest.fail(\"Key.from_paserk should fail.\") assert msg in str(err.value) @pytest.mark.parametrize( \"version\", [ 1,",
") def test_key_from_paserk_for_public_key_with_wrapping_key(self, version, key): k = Key.new(version, \"public\", key) wk = token_bytes(32)",
"k = Key.new(version, \"public\", key) wk = token_bytes(32) with pytest.raises(ValueError) as err: k.to_paserk(password=wk)",
"msg): with pytest.raises(ValueError) as err: Key.new(version, purpose, key) pytest.fail(\"Key.new should fail.\") assert msg",
"y=key[\"y\"], d=key[\"d\"]) assert isinstance(k, KeyInterface) assert k.version == version assert k.purpose == \"public\"",
"{\"x\": b\"\", \"y\": b\"\", \"d\": b\"ddd\"}, \"Failed to load key.\"), ( 2, {\"x\":",
"not RSA key.\"), (1, load_key(\"keys/public_key_ed25519.pem\"), \"The key is not RSA key.\"), ( 1,",
"load_key(\"keys/public_key_ecdsa_p384.pem\"), \"The key is not Ed25519 key.\", ), ], ) def test_key_new_public_with_wrong_key(self, version,",
"= k.to_paserk(wrapping_key=wk1) with pytest.raises(DecryptError) as err: Key.from_paserk(wpk, wrapping_key=wk2) pytest.fail(\"Key.from_paserk() should fail.\") assert \"Failed",
"load_key(\"keys/public_key_ed25519.pem\")), (3, load_key(\"keys/public_key_ecdsa_p384.pem\")), (4, load_key(\"keys/public_key_ed25519.pem\")), ], ) def test_key_from_paserk_for_public_key_with_wrapping_key(self, version, key): k =",
"b\"\", \"d\": b\"\"}, \"x or d should be set for v2.public.\", ), (",
"in str(err.value) with pytest.raises(NotSupportedError) as err: k.decrypt(b\"xxxxxx\") pytest.fail(\"Key.verify() should fail.\") assert \"A key",
"wpk = k.to_paserk(password=wk1) with pytest.raises(DecryptError) as err: Key.from_paserk(wpk, password=<PASSWORD>) pytest.fail(\"Key.from_paserk() should fail.\") assert",
"key is not Ed25519 key.\", ), ( 4, load_key(\"keys/public_key_ecdsa_p384.pem\"), \"The key is not",
"], ) def test_key_new_public_with_wrong_key(self, version, key, msg): with pytest.raises(ValueError) as err: Key.new(version, \"public\",",
"b\"ddd\"}, \"Only one of x or d should be set for v2.public.\", ),",
"key) assert k.to_paserk().startswith(f\"k{k.version}.secret.\") @pytest.mark.parametrize( \"version, purpose, key\", [ (1, \"local\", token_bytes(32)), (2, \"local\",",
"(1, \"public\", load_key(\"keys/public_key_rsa.pem\")), (2, \"public\", load_key(\"keys/private_key_ed25519.pem\")), (2, \"public\", load_key(\"keys/public_key_ed25519.pem\")), (3, \"public\", load_key(\"keys/private_key_ecdsa_p384.pem\")), (3,",
"\"Failed to load key.\"), (4, {\"x\": b\"\", \"y\": b\"\", \"d\": b\"ddd\"}, \"Failed to",
"purpose, key\", [ (1, \"local\", token_bytes(32)), (2, \"local\", token_bytes(32)), (3, \"local\", token_bytes(32)), (4,",
"3, load_key(\"keys/private_key_ed25519.pem\"), \"The key is not ECDSA key.\", ), ( 3, load_key(\"keys/public_key_ed25519.pem\"), \"The",
"not Ed25519 key.\"), ( 4, load_key(\"keys/private_key_ecdsa_p384.pem\"), \"The key is not Ed25519 key.\", ),",
"\"Invalid version: v*.\"), (\"v0\", \"local\", token_bytes(32), \"Invalid version: v0.\"), (0, \"local\", token_bytes(32), \"Invalid",
"version, purpose, key, msg): with pytest.raises(ValueError) as err: Key.new(version, purpose, key) pytest.fail(\"Key.new should",
"2, 3, 4, ], ) def test_key_from_paserk_for_local_with_wrong_wrapping_key(self, version): k = Key.new(version, \"local\", token_bytes(32))",
"\"y\": b\"yyy\", \"d\": b\"ddd\"}, \"x and y (and d) should be set for",
"= Key.from_asymmetric_key_params(version, x=key[\"x\"], y=key[\"y\"], d=key[\"d\"]) assert isinstance(k, KeyInterface) assert k.version == version assert",
"test_key_from_paserk_for_private_key_with_wrong_wrapping_key(self, version, key): k = Key.new(version, \"public\", key) wk1 = token_bytes(32) wk2 =",
"not Ed25519 key.\", ), ( 2, load_key(\"keys/public_key_ecdsa_p384.pem\"), \"The key is not Ed25519 key.\",",
"does not have verify().\" in str(err.value) @pytest.mark.parametrize( \"version, purpose, key\", [ (1, \"public\",",
"key.\", ), ( 3, load_key(\"keys/private_key_ed25519.pem\"), \"The key is not ECDSA key.\", ), (",
"key for local does not have verify().\" in str(err.value) @pytest.mark.parametrize( \"version, purpose, key\",",
"public.\"), (\"k4.local.AAAAAAAAAAAAAAAA\", \"Invalid PASERK type: local.\"), (\"k4.public.AAAAAAAAAAAAAAAA\", \"Invalid PASERK type: public.\"), ], )",
"version, key): k = Key.new(version, \"public\", key) wk1 = token_bytes(32) wk2 = token_bytes(32)",
"str(err.value) @pytest.mark.parametrize( \"version, key\", [ (1, load_key(\"keys/public_key_rsa.pem\")), (2, load_key(\"keys/public_key_ed25519.pem\")), (3, load_key(\"keys/public_key_ecdsa_p384.pem\")), (4, load_key(\"keys/public_key_ed25519.pem\")),",
"load_jwk, load_key class TestKey: \"\"\" Tests for Key. \"\"\" @pytest.mark.parametrize( \"version, purpose, key\",",
"), ( 3, {\"x\": b\"xxx\", \"y\": b\"\", \"d\": b\"ddd\"}, \"x and y (and",
"not supported on from_key_parameters.\", ), (999, load_jwk(\"keys/private_key_ed25519.json\"), \"Invalid version: 999.\"), (0, load_jwk(\"keys/private_key_ed25519.json\"), \"Invalid",
"b\"xxx\", \"y\": b\"\", \"d\": b\"\"}, \"Failed to load key.\"), (4, {\"x\": b\"\", \"y\":",
"[ 1, 2, 3, 4, ], ) def test_key_from_paserk_for_local_with_wrong_wrapping_key(self, version): k = Key.new(version,",
"), ( 3, load_key(\"keys/public_key_ed25519.pem\"), \"The key is not ECDSA key.\", ), (3, load_key(\"keys/private_key_rsa.pem\"),",
"b\"\", \"d\": b\"ddd\"}, \"Failed to load key.\"), ( 4, {\"x\": b\"\", \"y\": b\"\",",
"pytest.fail(\"Key.sign() should fail.\") assert \"A key for public does not have encrypt().\" in",
"fail.\") assert msg in str(err.value) @pytest.mark.parametrize( \"version, key\", [ # (1, load_jwk(\"keys/private_key_rsa.json\")), #",
"(3, \"public\", load_key(\"keys/private_key_ecdsa_p384.pem\")), (3, \"public\", load_key(\"keys/public_key_ecdsa_p384.pem\")), (4, \"public\", load_key(\"keys/private_key_ed25519.pem\")), (4, \"public\", load_key(\"keys/public_key_ed25519.pem\")), ],",
"key\", [ # (1, load_jwk(\"keys/private_key_rsa.json\")), # (1, load_jwk(\"keys/public_key_rsa.json\")), (2, load_jwk(\"keys/private_key_ed25519.json\")), (2, load_jwk(\"keys/public_key_ed25519.json\")), (3,"
] |
[
"= ({},{}) for i in range rows: visited[i] = False parents[i] = -1",
"-1 return (visited,parents) def DFS(adjMAT,visited,parent,v): visited[v] = True for k in neighbours(v): if",
"= True for k in neighbours(v): if (not visited[k]): parent[k] = v (visited,parent)",
"range rows: visited[i] = False parents[i] = -1 return (visited,parents) def DFS(adjMAT,visited,parent,v): visited[v]",
"parents[i] = -1 return (visited,parents) def DFS(adjMAT,visited,parent,v): visited[v] = True for k in",
"(rows,cols) = adjMAT.shape (visited,parents) = ({},{}) for i in range rows: visited[i] =",
"for i in range rows: visited[i] = False parents[i] = -1 return (visited,parents)",
"(visited,parents) def DFS(adjMAT,visited,parent,v): visited[v] = True for k in neighbours(v): if (not visited[k]):",
"adjMAT.shape (visited,parents) = ({},{}) for i in range rows: visited[i] = False parents[i]",
"in neighbours(v): if (not visited[k]): parent[k] = v (visited,parent) = DFS(adjMAT,visited,parent,k) return (visited,parent)",
"= -1 return (visited,parents) def DFS(adjMAT,visited,parent,v): visited[v] = True for k in neighbours(v):",
"k in neighbours(v): if (not visited[k]): parent[k] = v (visited,parent) = DFS(adjMAT,visited,parent,k) return",
"DFS(adjMAT,visited,parent,v): visited[v] = True for k in neighbours(v): if (not visited[k]): parent[k] =",
"True for k in neighbours(v): if (not visited[k]): parent[k] = v (visited,parent) =",
"= adjMAT.shape (visited,parents) = ({},{}) for i in range rows: visited[i] = False",
"def DFSInit(adjMAT): (rows,cols) = adjMAT.shape (visited,parents) = ({},{}) for i in range rows:",
"visited[v] = True for k in neighbours(v): if (not visited[k]): parent[k] = v",
"def DFS(adjMAT,visited,parent,v): visited[v] = True for k in neighbours(v): if (not visited[k]): parent[k]",
"i in range rows: visited[i] = False parents[i] = -1 return (visited,parents) def",
"return (visited,parents) def DFS(adjMAT,visited,parent,v): visited[v] = True for k in neighbours(v): if (not",
"in range rows: visited[i] = False parents[i] = -1 return (visited,parents) def DFS(adjMAT,visited,parent,v):",
"rows: visited[i] = False parents[i] = -1 return (visited,parents) def DFS(adjMAT,visited,parent,v): visited[v] =",
"visited[i] = False parents[i] = -1 return (visited,parents) def DFS(adjMAT,visited,parent,v): visited[v] = True",
"({},{}) for i in range rows: visited[i] = False parents[i] = -1 return",
"= False parents[i] = -1 return (visited,parents) def DFS(adjMAT,visited,parent,v): visited[v] = True for",
"False parents[i] = -1 return (visited,parents) def DFS(adjMAT,visited,parent,v): visited[v] = True for k",
"for k in neighbours(v): if (not visited[k]): parent[k] = v (visited,parent) = DFS(adjMAT,visited,parent,k)",
"(visited,parents) = ({},{}) for i in range rows: visited[i] = False parents[i] =",
"DFSInit(adjMAT): (rows,cols) = adjMAT.shape (visited,parents) = ({},{}) for i in range rows: visited[i]"
] |
[
"@return {string} def addBinary(self, a, b): if len(a) > len(b): b = \"0\"",
"a = \"0\" * (len(b)-len(a)) + a ans = \"\" c = 0",
"= 0 for i in xrange(len(a)-1, -1, -1): val = int(a[i]) + int(b[i])",
"val = int(a[i]) + int(b[i]) + c r, c = val % 2,",
"* (len(a)-len(b)) + b else: a = \"0\" * (len(b)-len(a)) + a ans",
"a binary string). # For example, # a = \"11\" # b =",
"xrange(len(a)-1, -1, -1): val = int(a[i]) + int(b[i]) + c r, c =",
"str(r) + ans if c == 1: ans = \"1\" + ans return",
"\"0\" * (len(b)-len(a)) + a ans = \"\" c = 0 for i",
"\"11\" # b = \"1\" # Return \"100\". class Solution: # @param {string}",
"len(a) > len(b): b = \"0\" * (len(a)-len(b)) + b else: a =",
"{string} a # @param {string} b # @return {string} def addBinary(self, a, b):",
"# Return \"100\". class Solution: # @param {string} a # @param {string} b",
"+ c r, c = val % 2, int(val >= 2) ans =",
"# a = \"11\" # b = \"1\" # Return \"100\". class Solution:",
"= \"0\" * (len(b)-len(a)) + a ans = \"\" c = 0 for",
"c r, c = val % 2, int(val >= 2) ans = str(r)",
"{string} b # @return {string} def addBinary(self, a, b): if len(a) > len(b):",
"if len(a) > len(b): b = \"0\" * (len(a)-len(b)) + b else: a",
"= \"11\" # b = \"1\" # Return \"100\". class Solution: # @param",
"@param {string} b # @return {string} def addBinary(self, a, b): if len(a) >",
"int(b[i]) + c r, c = val % 2, int(val >= 2) ans",
"return their sum (also a binary string). # For example, # a =",
"(len(b)-len(a)) + a ans = \"\" c = 0 for i in xrange(len(a)-1,",
"int(a[i]) + int(b[i]) + c r, c = val % 2, int(val >=",
"len(b): b = \"0\" * (len(a)-len(b)) + b else: a = \"0\" *",
"binary string). # For example, # a = \"11\" # b = \"1\"",
"-1, -1): val = int(a[i]) + int(b[i]) + c r, c = val",
"2, int(val >= 2) ans = str(r) + ans if c == 1:",
"# b = \"1\" # Return \"100\". class Solution: # @param {string} a",
"b # @return {string} def addBinary(self, a, b): if len(a) > len(b): b",
"def addBinary(self, a, b): if len(a) > len(b): b = \"0\" * (len(a)-len(b))",
"0 for i in xrange(len(a)-1, -1, -1): val = int(a[i]) + int(b[i]) +",
"in xrange(len(a)-1, -1, -1): val = int(a[i]) + int(b[i]) + c r, c",
"strings, return their sum (also a binary string). # For example, # a",
"# Given two binary strings, return their sum (also a binary string). #",
"int(val >= 2) ans = str(r) + ans if c == 1: ans",
"two binary strings, return their sum (also a binary string). # For example,",
"string). # For example, # a = \"11\" # b = \"1\" #",
"# @param {string} b # @return {string} def addBinary(self, a, b): if len(a)",
"2) ans = str(r) + ans if c == 1: ans = \"1\"",
">= 2) ans = str(r) + ans if c == 1: ans =",
"# For example, # a = \"11\" # b = \"1\" # Return",
"b = \"0\" * (len(a)-len(b)) + b else: a = \"0\" * (len(b)-len(a))",
"= \"\" c = 0 for i in xrange(len(a)-1, -1, -1): val =",
"= \"0\" * (len(a)-len(b)) + b else: a = \"0\" * (len(b)-len(a)) +",
"Solution: # @param {string} a # @param {string} b # @return {string} def",
"b): if len(a) > len(b): b = \"0\" * (len(a)-len(b)) + b else:",
"ans = str(r) + ans if c == 1: ans = \"1\" +",
"a = \"11\" # b = \"1\" # Return \"100\". class Solution: #",
"example, # a = \"11\" # b = \"1\" # Return \"100\". class",
"= val % 2, int(val >= 2) ans = str(r) + ans if",
"\"\" c = 0 for i in xrange(len(a)-1, -1, -1): val = int(a[i])",
"i in xrange(len(a)-1, -1, -1): val = int(a[i]) + int(b[i]) + c r,",
"= \"1\" # Return \"100\". class Solution: # @param {string} a # @param",
"val % 2, int(val >= 2) ans = str(r) + ans if c",
"> len(b): b = \"0\" * (len(a)-len(b)) + b else: a = \"0\"",
"For example, # a = \"11\" # b = \"1\" # Return \"100\".",
"+ b else: a = \"0\" * (len(b)-len(a)) + a ans = \"\"",
"\"1\" # Return \"100\". class Solution: # @param {string} a # @param {string}",
"Return \"100\". class Solution: # @param {string} a # @param {string} b #",
"their sum (also a binary string). # For example, # a = \"11\"",
"r, c = val % 2, int(val >= 2) ans = str(r) +",
"a # @param {string} b # @return {string} def addBinary(self, a, b): if",
"b else: a = \"0\" * (len(b)-len(a)) + a ans = \"\" c",
"ans = \"\" c = 0 for i in xrange(len(a)-1, -1, -1): val",
"{string} def addBinary(self, a, b): if len(a) > len(b): b = \"0\" *",
"else: a = \"0\" * (len(b)-len(a)) + a ans = \"\" c =",
"* (len(b)-len(a)) + a ans = \"\" c = 0 for i in",
"sum (also a binary string). # For example, # a = \"11\" #",
"binary strings, return their sum (also a binary string). # For example, #",
"a ans = \"\" c = 0 for i in xrange(len(a)-1, -1, -1):",
"c = val % 2, int(val >= 2) ans = str(r) + ans",
"(also a binary string). # For example, # a = \"11\" # b",
"% 2, int(val >= 2) ans = str(r) + ans if c ==",
"= str(r) + ans if c == 1: ans = \"1\" + ans",
"c = 0 for i in xrange(len(a)-1, -1, -1): val = int(a[i]) +",
"addBinary(self, a, b): if len(a) > len(b): b = \"0\" * (len(a)-len(b)) +",
"+ int(b[i]) + c r, c = val % 2, int(val >= 2)",
"Given two binary strings, return their sum (also a binary string). # For",
"+ ans if c == 1: ans = \"1\" + ans return ans",
"for i in xrange(len(a)-1, -1, -1): val = int(a[i]) + int(b[i]) + c",
"+ a ans = \"\" c = 0 for i in xrange(len(a)-1, -1,",
"# @return {string} def addBinary(self, a, b): if len(a) > len(b): b =",
"\"0\" * (len(a)-len(b)) + b else: a = \"0\" * (len(b)-len(a)) + a",
"# @param {string} a # @param {string} b # @return {string} def addBinary(self,",
"class Solution: # @param {string} a # @param {string} b # @return {string}",
"@param {string} a # @param {string} b # @return {string} def addBinary(self, a,",
"-1): val = int(a[i]) + int(b[i]) + c r, c = val %",
"(len(a)-len(b)) + b else: a = \"0\" * (len(b)-len(a)) + a ans =",
"b = \"1\" # Return \"100\". class Solution: # @param {string} a #",
"\"100\". class Solution: # @param {string} a # @param {string} b # @return",
"= int(a[i]) + int(b[i]) + c r, c = val % 2, int(val",
"a, b): if len(a) > len(b): b = \"0\" * (len(a)-len(b)) + b"
] |
[
"from auxillary rod to target rod solve_hanoi(n-1,use_rod,to_rod,from_rod) def main(): print(\"Enter the Number of",
"rod {}\".format(n,from_rod,to_rod)) #solve n-1 disc from auxillary rod to target rod solve_hanoi(n-1,use_rod,to_rod,from_rod) def",
"auxillary rod to target rod solve_hanoi(n-1,use_rod,to_rod,from_rod) def main(): print(\"Enter the Number of disc\")",
"n-1 disc from source rod to auxillary/Using rod solve_hanoi(n-1,from_rod,use_rod,to_rod) #Move remaining largest disc",
"Tower of Hanoi in python def solve_hanoi(n,from_rod,to_rod,use_rod): if(n==1): print(\"Move disk 1 from rod",
"print() # Source rod is rod 'a',Target rod is rod 'b',Using/auxillary rod is",
"solve_hanoi(n,from_rod,to_rod,use_rod): if(n==1): print(\"Move disk 1 from rod {} to_rod {}\".format(from_rod,to_rod)) else: #solve top",
"by <NAME> [github/YA12SHYAM] #implementing recusion solution of Tower of Hanoi in python def",
"def main(): print(\"Enter the Number of disc\") # the number of disc is",
"to_rod {}\".format(from_rod,to_rod)) else: #solve top n-1 disc from source rod to auxillary/Using rod",
"rod print(\"Move disk {} from rod {} to rod {}\".format(n,from_rod,to_rod)) #solve n-1 disc",
"Number of disc\") # the number of disc is n n=int(input()) print() #",
"rod to target rod print(\"Move disk {} from rod {} to rod {}\".format(n,from_rod,to_rod))",
"print(\"Move disk {} from rod {} to rod {}\".format(n,from_rod,to_rod)) #solve n-1 disc from",
"def solve_hanoi(n,from_rod,to_rod,use_rod): if(n==1): print(\"Move disk 1 from rod {} to_rod {}\".format(from_rod,to_rod)) else: #solve",
"1 from rod {} to_rod {}\".format(from_rod,to_rod)) else: #solve top n-1 disc from source",
"solve_hanoi(n-1,from_rod,use_rod,to_rod) #Move remaining largest disc from Source rod to target rod print(\"Move disk",
"of disc is n n=int(input()) print() # Source rod is rod 'a',Target rod",
"rod is rod 'b',Using/auxillary rod is rod 'c' solve_hanoi(n,'a','b','c') if __name__ == \"__main__\":",
"disk {} from rod {} to rod {}\".format(n,from_rod,to_rod)) #solve n-1 disc from auxillary",
"of disc\") # the number of disc is n n=int(input()) print() # Source",
"{} to_rod {}\".format(from_rod,to_rod)) else: #solve top n-1 disc from source rod to auxillary/Using",
"disc\") # the number of disc is n n=int(input()) print() # Source rod",
"to rod {}\".format(n,from_rod,to_rod)) #solve n-1 disc from auxillary rod to target rod solve_hanoi(n-1,use_rod,to_rod,from_rod)",
"solve_hanoi(n-1,use_rod,to_rod,from_rod) def main(): print(\"Enter the Number of disc\") # the number of disc",
"rod 'a',Target rod is rod 'b',Using/auxillary rod is rod 'c' solve_hanoi(n,'a','b','c') if __name__",
"disk 1 from rod {} to_rod {}\".format(from_rod,to_rod)) else: #solve top n-1 disc from",
"rod to auxillary/Using rod solve_hanoi(n-1,from_rod,use_rod,to_rod) #Move remaining largest disc from Source rod to",
"from Source rod to target rod print(\"Move disk {} from rod {} to",
"n-1 disc from auxillary rod to target rod solve_hanoi(n-1,use_rod,to_rod,from_rod) def main(): print(\"Enter the",
"is rod 'b',Using/auxillary rod is rod 'c' solve_hanoi(n,'a','b','c') if __name__ == \"__main__\": main()",
"rod {} to rod {}\".format(n,from_rod,to_rod)) #solve n-1 disc from auxillary rod to target",
"number of disc is n n=int(input()) print() # Source rod is rod 'a',Target",
"target rod solve_hanoi(n-1,use_rod,to_rod,from_rod) def main(): print(\"Enter the Number of disc\") # the number",
"n n=int(input()) print() # Source rod is rod 'a',Target rod is rod 'b',Using/auxillary",
"{}\".format(n,from_rod,to_rod)) #solve n-1 disc from auxillary rod to target rod solve_hanoi(n-1,use_rod,to_rod,from_rod) def main():",
"disc from source rod to auxillary/Using rod solve_hanoi(n-1,from_rod,use_rod,to_rod) #Move remaining largest disc from",
"{} to rod {}\".format(n,from_rod,to_rod)) #solve n-1 disc from auxillary rod to target rod",
"#implementing recusion solution of Tower of Hanoi in python def solve_hanoi(n,from_rod,to_rod,use_rod): if(n==1): print(\"Move",
"Source rod to target rod print(\"Move disk {} from rod {} to rod",
"top n-1 disc from source rod to auxillary/Using rod solve_hanoi(n-1,from_rod,use_rod,to_rod) #Move remaining largest",
"rod solve_hanoi(n-1,use_rod,to_rod,from_rod) def main(): print(\"Enter the Number of disc\") # the number of",
"disc is n n=int(input()) print() # Source rod is rod 'a',Target rod is",
"disc from Source rod to target rod print(\"Move disk {} from rod {}",
"the Number of disc\") # the number of disc is n n=int(input()) print()",
"<gh_stars>10-100 #Contribiuted by <NAME> [github/YA12SHYAM] #implementing recusion solution of Tower of Hanoi in",
"#Move remaining largest disc from Source rod to target rod print(\"Move disk {}",
"from rod {} to rod {}\".format(n,from_rod,to_rod)) #solve n-1 disc from auxillary rod to",
"#solve n-1 disc from auxillary rod to target rod solve_hanoi(n-1,use_rod,to_rod,from_rod) def main(): print(\"Enter",
"the number of disc is n n=int(input()) print() # Source rod is rod",
"is rod 'a',Target rod is rod 'b',Using/auxillary rod is rod 'c' solve_hanoi(n,'a','b','c') if",
"'a',Target rod is rod 'b',Using/auxillary rod is rod 'c' solve_hanoi(n,'a','b','c') if __name__ ==",
"recusion solution of Tower of Hanoi in python def solve_hanoi(n,from_rod,to_rod,use_rod): if(n==1): print(\"Move disk",
"remaining largest disc from Source rod to target rod print(\"Move disk {} from",
"<NAME> [github/YA12SHYAM] #implementing recusion solution of Tower of Hanoi in python def solve_hanoi(n,from_rod,to_rod,use_rod):",
"#solve top n-1 disc from source rod to auxillary/Using rod solve_hanoi(n-1,from_rod,use_rod,to_rod) #Move remaining",
"else: #solve top n-1 disc from source rod to auxillary/Using rod solve_hanoi(n-1,from_rod,use_rod,to_rod) #Move",
"of Hanoi in python def solve_hanoi(n,from_rod,to_rod,use_rod): if(n==1): print(\"Move disk 1 from rod {}",
"Hanoi in python def solve_hanoi(n,from_rod,to_rod,use_rod): if(n==1): print(\"Move disk 1 from rod {} to_rod",
"{}\".format(from_rod,to_rod)) else: #solve top n-1 disc from source rod to auxillary/Using rod solve_hanoi(n-1,from_rod,use_rod,to_rod)",
"rod is rod 'a',Target rod is rod 'b',Using/auxillary rod is rod 'c' solve_hanoi(n,'a','b','c')",
"target rod print(\"Move disk {} from rod {} to rod {}\".format(n,from_rod,to_rod)) #solve n-1",
"is n n=int(input()) print() # Source rod is rod 'a',Target rod is rod",
"Source rod is rod 'a',Target rod is rod 'b',Using/auxillary rod is rod 'c'",
"auxillary/Using rod solve_hanoi(n-1,from_rod,use_rod,to_rod) #Move remaining largest disc from Source rod to target rod",
"from rod {} to_rod {}\".format(from_rod,to_rod)) else: #solve top n-1 disc from source rod",
"solution of Tower of Hanoi in python def solve_hanoi(n,from_rod,to_rod,use_rod): if(n==1): print(\"Move disk 1",
"n=int(input()) print() # Source rod is rod 'a',Target rod is rod 'b',Using/auxillary rod",
"main(): print(\"Enter the Number of disc\") # the number of disc is n",
"in python def solve_hanoi(n,from_rod,to_rod,use_rod): if(n==1): print(\"Move disk 1 from rod {} to_rod {}\".format(from_rod,to_rod))",
"python def solve_hanoi(n,from_rod,to_rod,use_rod): if(n==1): print(\"Move disk 1 from rod {} to_rod {}\".format(from_rod,to_rod)) else:",
"to auxillary/Using rod solve_hanoi(n-1,from_rod,use_rod,to_rod) #Move remaining largest disc from Source rod to target",
"to target rod print(\"Move disk {} from rod {} to rod {}\".format(n,from_rod,to_rod)) #solve",
"source rod to auxillary/Using rod solve_hanoi(n-1,from_rod,use_rod,to_rod) #Move remaining largest disc from Source rod",
"print(\"Move disk 1 from rod {} to_rod {}\".format(from_rod,to_rod)) else: #solve top n-1 disc",
"print(\"Enter the Number of disc\") # the number of disc is n n=int(input())",
"# Source rod is rod 'a',Target rod is rod 'b',Using/auxillary rod is rod",
"#Contribiuted by <NAME> [github/YA12SHYAM] #implementing recusion solution of Tower of Hanoi in python",
"[github/YA12SHYAM] #implementing recusion solution of Tower of Hanoi in python def solve_hanoi(n,from_rod,to_rod,use_rod): if(n==1):",
"{} from rod {} to rod {}\".format(n,from_rod,to_rod)) #solve n-1 disc from auxillary rod",
"from source rod to auxillary/Using rod solve_hanoi(n-1,from_rod,use_rod,to_rod) #Move remaining largest disc from Source",
"if(n==1): print(\"Move disk 1 from rod {} to_rod {}\".format(from_rod,to_rod)) else: #solve top n-1",
"rod {} to_rod {}\".format(from_rod,to_rod)) else: #solve top n-1 disc from source rod to",
"of Tower of Hanoi in python def solve_hanoi(n,from_rod,to_rod,use_rod): if(n==1): print(\"Move disk 1 from",
"rod to target rod solve_hanoi(n-1,use_rod,to_rod,from_rod) def main(): print(\"Enter the Number of disc\") #",
"largest disc from Source rod to target rod print(\"Move disk {} from rod",
"disc from auxillary rod to target rod solve_hanoi(n-1,use_rod,to_rod,from_rod) def main(): print(\"Enter the Number",
"rod solve_hanoi(n-1,from_rod,use_rod,to_rod) #Move remaining largest disc from Source rod to target rod print(\"Move",
"to target rod solve_hanoi(n-1,use_rod,to_rod,from_rod) def main(): print(\"Enter the Number of disc\") # the",
"# the number of disc is n n=int(input()) print() # Source rod is"
] |
[] |
[
"= SpectralCube.read(os.path.join(gbt_path, \"17B-162_items/m33_gbt_vlsr_highres_Tmb_17B162_02kms.fits\")) gbt_cube = SpectralCube.read(os.path.join(gbt_path, \"17B-162_items/m33_gbt_vlsr_highres_Tmb_17B162_1kms.fits\")) beam_fwhm = lambda diam: ((1.18 *",
"in the GBT data being cut-off by the # PB limit of the",
"SpectralCube.read(seventeenB_HI_data_02kms_path(\"M33_14B_17B_HI_contsub_width_02kms.image.pbcor.fits\")) vla_cube = SpectralCube.read(seventeenB_HI_data_1kms_path(\"M33_14B_17B_HI_contsub_width_1kms.image.pbcor.fits\")) # pb_cube = SpectralCube.read(seventeenB_HI_data_02kms_path(\"M33_14B_17B_HI_contsub_width_02kms.pb.fits\")) pb_cube = SpectralCube.read(seventeenB_HI_data_1kms_path(\"M33_14B_17B_HI_contsub_width_1kms.pb.fits\")) # PB",
"sigma, nsig_cut=3): dist = nd.distance_transform_edt(mask) gauss_dists = np.where(np.logical_and(dist < nsig_cut * sigma, dist",
"method='distrib', verbose=True) plt.grid(True) plt.xlabel(r\"ln I$_{\\rm int}$ / I$_{\\rm SD}$\") plt.tight_layout() plt.savefig(allfigs_path(f\"Imaging/ratio_hist_17B_vla_gbt_9.8arcmin_chan_{chan_range.start}_{chan_range.stop}_v3_w_weights.png\")) plt.savefig(allfigs_path(f\"Imaging/ratio_hist_17B_vla_gbt_9.8arcmin_chan_{chan_range.start}_{chan_range.stop}_v3_w_weights.pdf\")) print(\"Factor:",
"= np.arange(len(low_pts)) onecolumn_figure() plt.errorbar(chans, sc_factor_chans, yerr=sc_err_chans, alpha=0.5, label='Distrib Fit') plt.errorbar(chans, sc_factor_chans_linfit, yerr=[sc_factor_chans_linfit -",
"if the MS frequency was the channel edge... spec_check_kwargs={'rtol': 0.4}) onecolumn_figure() sc_factor, sc_err",
"uvcombine.scale_factor import find_scale_factor from cube_analysis.feather_cubes import feather_compare_cube from paths import (seventeenB_HI_data_02kms_path, seventeenB_HI_data_1kms_path, data_path,",
"* u.m) # The shortest baseline in the 14B-088 data is ~44 m.",
"gives a 1.0 factor with the GBT data. # The tests here were",
"\"17B-162_items/m33_gbt_vlsr_highres_Tmb_17B162_1kms.fits\")) beam_fwhm = lambda diam: ((1.18 * hi_freq.to(u.cm, u.spectral())) / diam.to(u.cm)) * u.rad",
"plt.tight_layout() plt.savefig(allfigs_path(\"Imaging/ratio_hist_perchan_17B_vla_gbt_9.8arcmin_v3_w_weights.png\")) plt.savefig(allfigs_path(\"Imaging/ratio_hist_perchan_17B_vla_gbt_9.8arcmin_v3_w_weights.pdf\")) plt.close() # Now refit with the channels near the systemic",
"high in zip(low_pts, high_pts): sc_f, sc_e = \\ find_scale_factor(low, high, method='linfit', verbose=False) sc_factor_chans_linfit.append(sc_f)",
"as np import astropy.units as u import matplotlib.pyplot as plt import os import",
"# channel size. I have no idea where this shift is coming #",
"`gbt_regrid.py` matches # the frequency in the individual channel MSs used in #",
"chan_out = \\ feather_compare_cube(vla_cube, gbt_cube, las, num_cores=1, lowresfwhm=gbt_eff_beam, chunk=50, verbose=False, weights=weight, relax_spectral_check=False, #",
"at M33. So the data were # gridded with a Gaussian kernel, rather",
"the SD data. # Besides, the 14B mosaic comparison gives a 1.0 factor",
"The factor increases far from the systemic # velocity, where bright HI gets",
"= [] sc_err_chans_linfit = [] for low, high in zip(low_pts, high_pts): sc_f, sc_e",
"from uvcombine.scale_factor import find_scale_factor from cube_analysis.feather_cubes import feather_compare_cube from paths import (seventeenB_HI_data_02kms_path, seventeenB_HI_data_1kms_path,",
"sc_f, sc_e = \\ find_scale_factor(low, high, method='distrib', verbose=False) sc_factor_chans.append(sc_f) sc_err_chans.append(sc_e) sc_factor_chans_linfit = []",
"find_scale_factor from cube_analysis.feather_cubes import feather_compare_cube from paths import (seventeenB_HI_data_02kms_path, seventeenB_HI_data_1kms_path, data_path, allfigs_path) from",
"/ I$_{\\rm SD}$\") plt.tight_layout() plt.savefig(allfigs_path(f\"Imaging/ratio_hist_17B_vla_gbt_9.8arcmin_chan_{chan_range.start}_{chan_range.stop}_v3_w_weights.png\")) plt.savefig(allfigs_path(f\"Imaging/ratio_hist_17B_vla_gbt_9.8arcmin_chan_{chan_range.start}_{chan_range.stop}_v3_w_weights.pdf\")) print(\"Factor: {0}+/-{1}\".format(sc_factor_chrange, sc_err_chrange)) # Factor: 1.105133+/-0.00463 #",
"# gridded with a Gaussian kernel, rather than a jinc function gbt_eff_beam =",
"as plt import os import scipy.ndimage as nd from uvcombine.scale_factor import find_scale_factor from",
"pb_plane = pb_cube[0] # We need to define a tapered weighting function to",
"= np.array(sc_err_chans_linfit) chans = np.arange(len(low_pts)) onecolumn_figure() plt.errorbar(chans, sc_factor_chans, yerr=sc_err_chans, alpha=0.5, label='Distrib Fit') plt.errorbar(chans,",
"sc_f, sc_e = \\ find_scale_factor(low, high, method='linfit', verbose=False) sc_factor_chans_linfit.append(sc_f) sc_err_chans_linfit.append(sc_e) sc_factor_chans_linfit = np.array(sc_factor_chans_linfit)",
"data where they overlap in the uv plane. No offset correction is needed.",
"return weight_arr weight = taper_weights(np.isfinite(pb_plane), 30, nsig_cut=5) gbt_path = os.path.join(data_path, \"GBT\") # gbt_cube",
"np.array(sc_factor_chans_linfit) sc_err_chans_linfit = np.array(sc_err_chans_linfit) chans = np.arange(len(low_pts)) onecolumn_figure() plt.errorbar(chans, sc_factor_chans, yerr=sc_err_chans, alpha=0.5, label='Distrib",
"Higher S/N # vla_cube = SpectralCube.read(seventeenB_HI_data_02kms_path(\"M33_14B_17B_HI_contsub_width_02kms.image.pbcor.fits\")) vla_cube = SpectralCube.read(seventeenB_HI_data_1kms_path(\"M33_14B_17B_HI_contsub_width_1kms.image.pbcor.fits\")) # pb_cube = SpectralCube.read(seventeenB_HI_data_02kms_path(\"M33_14B_17B_HI_contsub_width_02kms.pb.fits\"))",
"- sc_factor_chans_linfit], alpha=0.5, label='Linear fit') # plt.plot(chans, slope_lowess_85) plt.axhline(1, linestyle='--') plt.legend(frameon=True) plt.ylabel(r\"Scale Factor\")",
"VLA mosaic. The factor increases far from the systemic # velocity, where bright",
"SD data. # Besides, the 14B mosaic comparison gives a 1.0 factor with",
"changes over the frequency range. So just grab one plane pb_plane = pb_cube[0]",
"applied to the SD data. # Besides, the 14B mosaic comparison gives a",
"is an offset of ~0.4 km/s between the cubes # The big GBT",
"sc_factor_chans_linfit, yerr=[sc_factor_chans_linfit - sc_err_chans_linfit[:, 0], sc_err_chans_linfit[:, 1] - sc_factor_chans_linfit], alpha=0.5, label='Linear fit') #",
"baseline in the 14B-088 data is ~44 m. las = (hi_freq.to(u.cm, u.spectral()) /",
"# Besides, the 14B mosaic comparison gives a 1.0 factor with the GBT",
"np.hstack(high_pts), method='distrib', verbose=True) plt.grid(True) plt.xlabel(r\"ln I$_{\\rm int}$ / I$_{\\rm SD}$\") plt.tight_layout() plt.savefig(allfigs_path(\"Imaging/ratio_hist_17B_vla_gbt_9.8arcmin_v3_w_weights.png\")) plt.savefig(allfigs_path(\"Imaging/ratio_hist_17B_vla_gbt_9.8arcmin_v3_w_weights.pdf\"))",
"np.zeros_like(mask, dtype=float) weight_arr[gauss_dists] = \\ np.exp(- (dist[gauss_dists] - nsig_cut * sigma)**2 / (2",
"ignore emission outside # of the VLA mosaic def taper_weights(mask, sigma, nsig_cut=3): dist",
"1 factor, no factor will be applied to the SD data. # Besides,",
"= \\ np.exp(- (dist[gauss_dists] - nsig_cut * sigma)**2 / (2 * sigma**2)) weight_arr[flat_dists]",
"# vla_cube = SpectralCube.read(seventeenB_HI_data_02kms_path(\"M33_14B_17B_HI_contsub_width_02kms.image.pbcor.fits\")) vla_cube = SpectralCube.read(seventeenB_HI_data_1kms_path(\"M33_14B_17B_HI_contsub_width_1kms.image.pbcor.fits\")) # pb_cube = SpectralCube.read(seventeenB_HI_data_02kms_path(\"M33_14B_17B_HI_contsub_width_02kms.pb.fits\")) pb_cube =",
"SpectralCube.read(seventeenB_HI_data_02kms_path(\"M33_14B_17B_HI_contsub_width_02kms.pb.fits\")) pb_cube = SpectralCube.read(seventeenB_HI_data_1kms_path(\"M33_14B_17B_HI_contsub_width_1kms.pb.fits\")) # PB minimally changes over the frequency range. So",
"0.)) flat_dists = np.where(dist >= nsig_cut * sigma) weight_arr = np.zeros_like(mask, dtype=float) weight_arr[gauss_dists]",
"* u.m)).to(u.arcsec, u.dimensionless_angles()) radii, ratios, high_pts, low_pts, chan_out = \\ feather_compare_cube(vla_cube, gbt_cube, las,",
"cut-off by the # PB limit of the VLA mosaic. The factor increases",
"would expect if the MS frequency was the channel edge... spec_check_kwargs={'rtol': 0.4}) onecolumn_figure()",
"expect if the MS frequency was the channel edge... spec_check_kwargs={'rtol': 0.4}) onecolumn_figure() sc_factor,",
"Besides, the 14B mosaic comparison gives a 1.0 factor with the GBT data.",
"plt.ylabel(r\"Scale Factor\") plt.xlabel(\"Channels\") plt.grid(True) plt.tight_layout() plt.savefig(allfigs_path(\"Imaging/ratio_hist_perchan_17B_vla_gbt_9.8arcmin_v3_w_weights.png\")) plt.savefig(allfigs_path(\"Imaging/ratio_hist_perchan_17B_vla_gbt_9.8arcmin_v3_w_weights.pdf\")) plt.close() # Now refit with the",
"chans = np.arange(len(low_pts)) onecolumn_figure() plt.errorbar(chans, sc_factor_chans, yerr=sc_err_chans, alpha=0.5, label='Distrib Fit') plt.errorbar(chans, sc_factor_chans_linfit, yerr=[sc_factor_chans_linfit",
"1.0 factor with the GBT data. # The tests here were for consistency",
"~44 m. las = (hi_freq.to(u.cm, u.spectral()) / (44 * u.m)).to(u.arcsec, u.dimensionless_angles()) radii, ratios,",
"in zip(low_pts, high_pts): sc_f, sc_e = \\ find_scale_factor(low, high, method='distrib', verbose=False) sc_factor_chans.append(sc_f) sc_err_chans.append(sc_e)",
"shortest baseline in the 14B-088 data is ~44 m. las = (hi_freq.to(u.cm, u.spectral())",
"np.arange(len(low_pts)) onecolumn_figure() plt.errorbar(chans, sc_factor_chans, yerr=sc_err_chans, alpha=0.5, label='Distrib Fit') plt.errorbar(chans, sc_factor_chans_linfit, yerr=[sc_factor_chans_linfit - sc_err_chans_linfit[:,",
"sc_err_chans.append(sc_e) sc_factor_chans_linfit = [] sc_err_chans_linfit = [] for low, high in zip(low_pts, high_pts):",
"even a half-channel offset like I # would expect if the MS frequency",
"The >1 factor is due to some emission in the GBT data being",
"nsig_cut * sigma) weight_arr = np.zeros_like(mask, dtype=float) weight_arr[gauss_dists] = \\ np.exp(- (dist[gauss_dists] -",
"matplotlib.pyplot as plt import os import scipy.ndimage as nd from uvcombine.scale_factor import find_scale_factor",
"np.where(np.logical_and(dist < nsig_cut * sigma, dist > 0.)) flat_dists = np.where(dist >= nsig_cut",
"fields centered at M33. So the data were # gridded with a Gaussian",
"so this error was significantly underestimated plt.close() # Compare properties per-channel sc_factor_chans =",
"low, high in zip(low_pts, high_pts): sc_f, sc_e = \\ find_scale_factor(low, high, method='distrib', verbose=False)",
"= \\ find_scale_factor(low, high, method='linfit', verbose=False) sc_factor_chans_linfit.append(sc_f) sc_err_chans_linfit.append(sc_e) sc_factor_chans_linfit = np.array(sc_factor_chans_linfit) sc_err_chans_linfit =",
"\"GBT\") # gbt_cube = SpectralCube.read(os.path.join(gbt_path, \"17B-162_items/m33_gbt_vlsr_highres_Tmb_17B162_02kms.fits\")) gbt_cube = SpectralCube.read(os.path.join(gbt_path, \"17B-162_items/m33_gbt_vlsr_highres_Tmb_17B162_1kms.fits\")) beam_fwhm = lambda",
"SD}$\") plt.tight_layout() plt.savefig(allfigs_path(\"Imaging/ratio_hist_17B_vla_gbt_9.8arcmin_v3_w_weights.png\")) plt.savefig(allfigs_path(\"Imaging/ratio_hist_17B_vla_gbt_9.8arcmin_v3_w_weights.pdf\")) print(\"Factor: {0}+/-{1}\".format(sc_factor, sc_err)) # Factor: 1.125046+/-0.00394768 # This isn't",
"larger 14B data). # So, despite the != 1 factor, no factor will",
"u.m) # The shortest baseline in the 14B-088 data is ~44 m. las",
"like I # would expect if the MS frequency was the channel edge...",
"per-channel sc_factor_chans = [] sc_err_chans = [] for low, high in zip(low_pts, high_pts):",
"data were # gridded with a Gaussian kernel, rather than a jinc function",
"((1.18 * hi_freq.to(u.cm, u.spectral())) / diam.to(u.cm)) * u.rad # Already determined from the",
"really doesn't matter (I # manually checked). The difference is 0.36 times the",
"# We need to define a tapered weighting function to ignore emission outside",
"a tapered weighting function to ignore emission outside # of the VLA mosaic",
"in the 14B-088 data is ~44 m. las = (hi_freq.to(u.cm, u.spectral()) / (44",
"sc_factor_chans_linfit.append(sc_f) sc_err_chans_linfit.append(sc_e) sc_factor_chans_linfit = np.array(sc_factor_chans_linfit) sc_err_chans_linfit = np.array(sc_err_chans_linfit) chans = np.arange(len(low_pts)) onecolumn_figure() plt.errorbar(chans,",
"= \\ find_scale_factor(low, high, method='distrib', verbose=False) sc_factor_chans.append(sc_f) sc_err_chans.append(sc_e) sc_factor_chans_linfit = [] sc_err_chans_linfit =",
"with the 1 km/s cube. Higher S/N # vla_cube = SpectralCube.read(seventeenB_HI_data_02kms_path(\"M33_14B_17B_HI_contsub_width_02kms.image.pbcor.fits\")) vla_cube =",
"# Already determined from the 14B HI analysis. Lowered spatial resolution # due",
"means this really doesn't matter (I # manually checked). The difference is 0.36",
"gbt_eff_beam = beam_fwhm(87.5 * u.m) # The shortest baseline in the 14B-088 data",
"plt.tight_layout() plt.savefig(allfigs_path(\"Imaging/ratio_hist_17B_vla_gbt_9.8arcmin_v3_w_weights.png\")) plt.savefig(allfigs_path(\"Imaging/ratio_hist_17B_vla_gbt_9.8arcmin_v3_w_weights.pdf\")) print(\"Factor: {0}+/-{1}\".format(sc_factor, sc_err)) # Factor: 1.125046+/-0.00394768 # This isn't a",
"error was significantly underestimated plt.close() # Compare properties per-channel sc_factor_chans = [] sc_err_chans",
"# The shortest baseline in the 14B-088 data is ~44 m. las =",
"high in zip(low_pts, high_pts): sc_f, sc_e = \\ find_scale_factor(low, high, method='distrib', verbose=False) sc_factor_chans.append(sc_f)",
"import scipy.ndimage as nd from uvcombine.scale_factor import find_scale_factor from cube_analysis.feather_cubes import feather_compare_cube from",
"the # PB limit of the VLA mosaic. The factor increases far from",
"factor increases far from the systemic # velocity, where bright HI gets cut-off",
"sigma)**2 / (2 * sigma**2)) weight_arr[flat_dists] = 1. return weight_arr weight = taper_weights(np.isfinite(pb_plane),",
"no factor will be applied to the SD data. # Besides, the 14B",
"nsig_cut=3): dist = nd.distance_transform_edt(mask) gauss_dists = np.where(np.logical_and(dist < nsig_cut * sigma, dist >",
"The big GBT beam means this really doesn't matter (I # manually checked).",
"low, high in zip(low_pts, high_pts): sc_f, sc_e = \\ find_scale_factor(low, high, method='linfit', verbose=False)",
"= os.path.join(data_path, \"GBT\") # gbt_cube = SpectralCube.read(os.path.join(gbt_path, \"17B-162_items/m33_gbt_vlsr_highres_Tmb_17B162_02kms.fits\")) gbt_cube = SpectralCube.read(os.path.join(gbt_path, \"17B-162_items/m33_gbt_vlsr_highres_Tmb_17B162_1kms.fits\")) beam_fwhm",
"PB limit of the VLA mosaic. The factor increases far from the systemic",
"feather_compare_cube from paths import (seventeenB_HI_data_02kms_path, seventeenB_HI_data_1kms_path, data_path, allfigs_path) from constants import hi_freq from",
"Already determined from the 14B HI analysis. Lowered spatial resolution # due to",
"Factor: 1.125046+/-0.00394768 # This isn't a fantastic fit, so this error was significantly",
"plt.grid(True) plt.xlabel(r\"ln I$_{\\rm int}$ / I$_{\\rm SD}$\") plt.tight_layout() plt.savefig(allfigs_path(f\"Imaging/ratio_hist_17B_vla_gbt_9.8arcmin_chan_{chan_range.start}_{chan_range.stop}_v3_w_weights.png\")) plt.savefig(allfigs_path(f\"Imaging/ratio_hist_17B_vla_gbt_9.8arcmin_chan_{chan_range.start}_{chan_range.stop}_v3_w_weights.pdf\")) print(\"Factor: {0}+/-{1}\".format(sc_factor_chrange, sc_err_chrange))",
"= (hi_freq.to(u.cm, u.spectral()) / (44 * u.m)).to(u.arcsec, u.dimensionless_angles()) radii, ratios, high_pts, low_pts, chan_out",
"km/s cube. Higher S/N # vla_cube = SpectralCube.read(seventeenB_HI_data_02kms_path(\"M33_14B_17B_HI_contsub_width_02kms.image.pbcor.fits\")) vla_cube = SpectralCube.read(seventeenB_HI_data_1kms_path(\"M33_14B_17B_HI_contsub_width_1kms.image.pbcor.fits\")) # pb_cube",
"times the # channel size. I have no idea where this shift is",
"Factor\") plt.xlabel(\"Channels\") plt.grid(True) plt.tight_layout() plt.savefig(allfigs_path(\"Imaging/ratio_hist_perchan_17B_vla_gbt_9.8arcmin_v3_w_weights.png\")) plt.savefig(allfigs_path(\"Imaging/ratio_hist_perchan_17B_vla_gbt_9.8arcmin_v3_w_weights.pdf\")) plt.close() # Now refit with the channels",
"factor will be applied to the SD data. # Besides, the 14B mosaic",
"an offset of ~0.4 km/s between the cubes # The big GBT beam",
"for low, high in zip(low_pts, high_pts): sc_f, sc_e = \\ find_scale_factor(low, high, method='distrib',",
"the frequency range. So just grab one plane pb_plane = pb_cube[0] # We",
"jinc function gbt_eff_beam = beam_fwhm(87.5 * u.m) # The shortest baseline in the",
"is ~44 m. las = (hi_freq.to(u.cm, u.spectral()) / (44 * u.m)).to(u.arcsec, u.dimensionless_angles()) radii,",
"import os import scipy.ndimage as nd from uvcombine.scale_factor import find_scale_factor from cube_analysis.feather_cubes import",
"onecolumn_figure() sc_factor, sc_err = find_scale_factor(np.hstack(low_pts), np.hstack(high_pts), method='distrib', verbose=True) plt.grid(True) plt.xlabel(r\"ln I$_{\\rm int}$ /",
"= SpectralCube.read(os.path.join(gbt_path, \"17B-162_items/m33_gbt_vlsr_highres_Tmb_17B162_1kms.fits\")) beam_fwhm = lambda diam: ((1.18 * hi_freq.to(u.cm, u.spectral())) / diam.to(u.cm))",
"factor with the GBT data. # The tests here were for consistency and",
"as nd from uvcombine.scale_factor import find_scale_factor from cube_analysis.feather_cubes import feather_compare_cube from paths import",
"of ~0.4 km/s between the cubes # The big GBT beam means this",
"mosaic comparison gives a 1.0 factor with the GBT data. # The tests",
"analysis. Lowered spatial resolution # due to lack of overlap in the GBT",
"hi_freq from plotting_styles import onecolumn_figure # Compare with the 1 km/s cube. Higher",
"the freq axis used in `gbt_regrid.py` matches # the frequency in the individual",
"I$_{\\rm SD}$\") plt.tight_layout() plt.savefig(allfigs_path(\"Imaging/ratio_hist_17B_vla_gbt_9.8arcmin_v3_w_weights.png\")) plt.savefig(allfigs_path(\"Imaging/ratio_hist_17B_vla_gbt_9.8arcmin_v3_w_weights.pdf\")) print(\"Factor: {0}+/-{1}\".format(sc_factor, sc_err)) # Factor: 1.125046+/-0.00394768 # This",
"{0}+/-{1}\".format(sc_factor, sc_err)) # Factor: 1.125046+/-0.00394768 # This isn't a fantastic fit, so this",
"there is an offset of ~0.4 km/s between the cubes # The big",
"underestimated # The >1 factor is due to some emission in the GBT",
"= \\ feather_compare_cube(vla_cube, gbt_cube, las, num_cores=1, lowresfwhm=gbt_eff_beam, chunk=50, verbose=False, weights=weight, relax_spectral_check=False, # NOTE:",
"cube. Higher S/N # vla_cube = SpectralCube.read(seventeenB_HI_data_02kms_path(\"M33_14B_17B_HI_contsub_width_02kms.image.pbcor.fits\")) vla_cube = SpectralCube.read(seventeenB_HI_data_1kms_path(\"M33_14B_17B_HI_contsub_width_1kms.image.pbcor.fits\")) # pb_cube =",
"14B-088 data is ~44 m. las = (hi_freq.to(u.cm, u.spectral()) / (44 * u.m)).to(u.arcsec,",
"a fantastic fit, so this error was significantly underestimated plt.close() # Compare properties",
"difference is 0.36 times the # channel size. I have no idea where",
"find_scale_factor(low, high, method='linfit', verbose=False) sc_factor_chans_linfit.append(sc_f) sc_err_chans_linfit.append(sc_e) sc_factor_chans_linfit = np.array(sc_factor_chans_linfit) sc_err_chans_linfit = np.array(sc_err_chans_linfit) chans",
"sc_factor_chans, yerr=sc_err_chans, alpha=0.5, label='Distrib Fit') plt.errorbar(chans, sc_factor_chans_linfit, yerr=[sc_factor_chans_linfit - sc_err_chans_linfit[:, 0], sc_err_chans_linfit[:, 1]",
"freq axis used in `gbt_regrid.py` matches # the frequency in the individual channel",
"(2 * sigma**2)) weight_arr[flat_dists] = 1. return weight_arr weight = taper_weights(np.isfinite(pb_plane), 30, nsig_cut=5)",
"1.105133+/-0.00463 # Error still underestimated # The >1 factor is due to some",
"km/s between the cubes # The big GBT beam means this really doesn't",
"# Factor: 1.105133+/-0.00463 # Error still underestimated # The >1 factor is due",
"due to some emission in the GBT data being cut-off by the #",
"# Factor: 1.125046+/-0.00394768 # This isn't a fantastic fit, so this error was",
"# imaging. It's not even a half-channel offset like I # would expect",
"/ (2 * sigma**2)) weight_arr[flat_dists] = 1. return weight_arr weight = taper_weights(np.isfinite(pb_plane), 30,",
"plt.close() # Compare properties per-channel sc_factor_chans = [] sc_err_chans = [] for low,",
"is due to some emission in the GBT data being cut-off by the",
"find_scale_factor(np.hstack(low_pts), np.hstack(high_pts), method='distrib', verbose=True) plt.grid(True) plt.xlabel(r\"ln I$_{\\rm int}$ / I$_{\\rm SD}$\") plt.tight_layout() plt.savefig(allfigs_path(\"Imaging/ratio_hist_17B_vla_gbt_9.8arcmin_v3_w_weights.png\"))",
"matter (I # manually checked). The difference is 0.36 times the # channel",
"HI # structure falls within the mosaic PB chan_range = slice(80, 160) onecolumn_figure()",
"sc_factor_chrange, sc_err_chrange = \\ find_scale_factor(np.hstack(low_pts[chan_range]), np.hstack(high_pts[chan_range]), method='distrib', verbose=True) plt.grid(True) plt.xlabel(r\"ln I$_{\\rm int}$ /",
"velocity, where bright HI gets cut-off (compared to the larger 14B data). #",
"constants import hi_freq from plotting_styles import onecolumn_figure # Compare with the 1 km/s",
"plt.tight_layout() plt.savefig(allfigs_path(f\"Imaging/ratio_hist_17B_vla_gbt_9.8arcmin_chan_{chan_range.start}_{chan_range.stop}_v3_w_weights.png\")) plt.savefig(allfigs_path(f\"Imaging/ratio_hist_17B_vla_gbt_9.8arcmin_chan_{chan_range.start}_{chan_range.stop}_v3_w_weights.pdf\")) print(\"Factor: {0}+/-{1}\".format(sc_factor_chrange, sc_err_chrange)) # Factor: 1.105133+/-0.00463 # Error still underestimated",
"# structure falls within the mosaic PB chan_range = slice(80, 160) onecolumn_figure() sc_factor_chrange,",
"= 1. return weight_arr weight = taper_weights(np.isfinite(pb_plane), 30, nsig_cut=5) gbt_path = os.path.join(data_path, \"GBT\")",
"weight_arr = np.zeros_like(mask, dtype=float) weight_arr[gauss_dists] = \\ np.exp(- (dist[gauss_dists] - nsig_cut * sigma)**2",
"due to lack of overlap in the GBT fields centered at M33. So",
"weight_arr[flat_dists] = 1. return weight_arr weight = taper_weights(np.isfinite(pb_plane), 30, nsig_cut=5) gbt_path = os.path.join(data_path,",
"the GBT data being cut-off by the # PB limit of the VLA",
"the 14B mosaic comparison gives a 1.0 factor with the GBT data. #",
"nsig_cut * sigma)**2 / (2 * sigma**2)) weight_arr[flat_dists] = 1. return weight_arr weight",
"0.36 times the # channel size. I have no idea where this shift",
"dist = nd.distance_transform_edt(mask) gauss_dists = np.where(np.logical_and(dist < nsig_cut * sigma, dist > 0.))",
"plt.savefig(allfigs_path(\"Imaging/ratio_hist_perchan_17B_vla_gbt_9.8arcmin_v3_w_weights.png\")) plt.savefig(allfigs_path(\"Imaging/ratio_hist_perchan_17B_vla_gbt_9.8arcmin_v3_w_weights.pdf\")) plt.close() # Now refit with the channels near the systemic velocity,",
"os import scipy.ndimage as nd from uvcombine.scale_factor import find_scale_factor from cube_analysis.feather_cubes import feather_compare_cube",
"SpectralCube.read(seventeenB_HI_data_1kms_path(\"M33_14B_17B_HI_contsub_width_1kms.pb.fits\")) # PB minimally changes over the frequency range. So just grab one",
"verbose=True) plt.grid(True) plt.xlabel(r\"ln I$_{\\rm int}$ / I$_{\\rm SD}$\") plt.tight_layout() plt.savefig(allfigs_path(f\"Imaging/ratio_hist_17B_vla_gbt_9.8arcmin_chan_{chan_range.start}_{chan_range.stop}_v3_w_weights.png\")) plt.savefig(allfigs_path(f\"Imaging/ratio_hist_17B_vla_gbt_9.8arcmin_chan_{chan_range.start}_{chan_range.stop}_v3_w_weights.pdf\")) print(\"Factor: {0}+/-{1}\".format(sc_factor_chrange,",
"1. return weight_arr weight = taper_weights(np.isfinite(pb_plane), 30, nsig_cut=5) gbt_path = os.path.join(data_path, \"GBT\") #",
"# plt.plot(chans, slope_lowess_85) plt.axhline(1, linestyle='--') plt.legend(frameon=True) plt.ylabel(r\"Scale Factor\") plt.xlabel(\"Channels\") plt.grid(True) plt.tight_layout() plt.savefig(allfigs_path(\"Imaging/ratio_hist_perchan_17B_vla_gbt_9.8arcmin_v3_w_weights.png\")) plt.savefig(allfigs_path(\"Imaging/ratio_hist_perchan_17B_vla_gbt_9.8arcmin_v3_w_weights.pdf\"))",
"slice(80, 160) onecolumn_figure() sc_factor_chrange, sc_err_chrange = \\ find_scale_factor(np.hstack(low_pts[chan_range]), np.hstack(high_pts[chan_range]), method='distrib', verbose=True) plt.grid(True) plt.xlabel(r\"ln",
"alpha=0.5, label='Linear fit') # plt.plot(chans, slope_lowess_85) plt.axhline(1, linestyle='--') plt.legend(frameon=True) plt.ylabel(r\"Scale Factor\") plt.xlabel(\"Channels\") plt.grid(True)",
"fantastic fit, so this error was significantly underestimated plt.close() # Compare properties per-channel",
"def taper_weights(mask, sigma, nsig_cut=3): dist = nd.distance_transform_edt(mask) gauss_dists = np.where(np.logical_and(dist < nsig_cut *",
"from plotting_styles import onecolumn_figure # Compare with the 1 km/s cube. Higher S/N",
"by the # PB limit of the VLA mosaic. The factor increases far",
"* u.rad # Already determined from the 14B HI analysis. Lowered spatial resolution",
"need to define a tapered weighting function to ignore emission outside # of",
"properties per-channel sc_factor_chans = [] sc_err_chans = [] for low, high in zip(low_pts,",
"= pb_cube[0] # We need to define a tapered weighting function to ignore",
"# Compare with the 1 km/s cube. Higher S/N # vla_cube = SpectralCube.read(seventeenB_HI_data_02kms_path(\"M33_14B_17B_HI_contsub_width_02kms.image.pbcor.fits\"))",
"= beam_fwhm(87.5 * u.m) # The shortest baseline in the 14B-088 data is",
"Factor: 1.105133+/-0.00463 # Error still underestimated # The >1 factor is due to",
"# gbt_cube = SpectralCube.read(os.path.join(gbt_path, \"17B-162_items/m33_gbt_vlsr_highres_Tmb_17B162_02kms.fits\")) gbt_cube = SpectralCube.read(os.path.join(gbt_path, \"17B-162_items/m33_gbt_vlsr_highres_Tmb_17B162_1kms.fits\")) beam_fwhm = lambda diam:",
"uv plane. No offset correction is needed. ''' from spectral_cube import SpectralCube import",
"Compare with the 1 km/s cube. Higher S/N # vla_cube = SpectralCube.read(seventeenB_HI_data_02kms_path(\"M33_14B_17B_HI_contsub_width_02kms.image.pbcor.fits\")) vla_cube",
"[] sc_err_chans = [] for low, high in zip(low_pts, high_pts): sc_f, sc_e =",
"data. # The tests here were for consistency and that's what we find.",
"pb_cube = SpectralCube.read(seventeenB_HI_data_02kms_path(\"M33_14B_17B_HI_contsub_width_02kms.pb.fits\")) pb_cube = SpectralCube.read(seventeenB_HI_data_1kms_path(\"M33_14B_17B_HI_contsub_width_1kms.pb.fits\")) # PB minimally changes over the frequency",
"in # imaging. It's not even a half-channel offset like I # would",
"sc_e = \\ find_scale_factor(low, high, method='distrib', verbose=False) sc_factor_chans.append(sc_f) sc_err_chans.append(sc_e) sc_factor_chans_linfit = [] sc_err_chans_linfit",
"It's not even a half-channel offset like I # would expect if the",
"paths import (seventeenB_HI_data_02kms_path, seventeenB_HI_data_1kms_path, data_path, allfigs_path) from constants import hi_freq from plotting_styles import",
"where bright HI gets cut-off (compared to the larger 14B data). # So,",
"to the SD data. # Besides, the 14B mosaic comparison gives a 1.0",
"plt.close() # Now refit with the channels near the systemic velocity, where most",
"lowresfwhm=gbt_eff_beam, chunk=50, verbose=False, weights=weight, relax_spectral_check=False, # NOTE: there is an offset of ~0.4",
"mosaic. The factor increases far from the systemic # velocity, where bright HI",
"= \\ find_scale_factor(np.hstack(low_pts[chan_range]), np.hstack(high_pts[chan_range]), method='distrib', verbose=True) plt.grid(True) plt.xlabel(r\"ln I$_{\\rm int}$ / I$_{\\rm SD}$\")",
"yerr=sc_err_chans, alpha=0.5, label='Distrib Fit') plt.errorbar(chans, sc_factor_chans_linfit, yerr=[sc_factor_chans_linfit - sc_err_chans_linfit[:, 0], sc_err_chans_linfit[:, 1] -",
"np import astropy.units as u import matplotlib.pyplot as plt import os import scipy.ndimage",
"the data were # gridded with a Gaussian kernel, rather than a jinc",
"feather_compare_cube(vla_cube, gbt_cube, las, num_cores=1, lowresfwhm=gbt_eff_beam, chunk=50, verbose=False, weights=weight, relax_spectral_check=False, # NOTE: there is",
"method='distrib', verbose=False) sc_factor_chans.append(sc_f) sc_err_chans.append(sc_e) sc_factor_chans_linfit = [] sc_err_chans_linfit = [] for low, high",
"where this shift is coming # from since the freq axis used in",
"high_pts): sc_f, sc_e = \\ find_scale_factor(low, high, method='linfit', verbose=False) sc_factor_chans_linfit.append(sc_f) sc_err_chans_linfit.append(sc_e) sc_factor_chans_linfit =",
"= SpectralCube.read(seventeenB_HI_data_1kms_path(\"M33_14B_17B_HI_contsub_width_1kms.image.pbcor.fits\")) # pb_cube = SpectralCube.read(seventeenB_HI_data_02kms_path(\"M33_14B_17B_HI_contsub_width_02kms.pb.fits\")) pb_cube = SpectralCube.read(seventeenB_HI_data_1kms_path(\"M33_14B_17B_HI_contsub_width_1kms.pb.fits\")) # PB minimally changes",
"import (seventeenB_HI_data_02kms_path, seventeenB_HI_data_1kms_path, data_path, allfigs_path) from constants import hi_freq from plotting_styles import onecolumn_figure",
"\\ np.exp(- (dist[gauss_dists] - nsig_cut * sigma)**2 / (2 * sigma**2)) weight_arr[flat_dists] =",
"chan_range = slice(80, 160) onecolumn_figure() sc_factor_chrange, sc_err_chrange = \\ find_scale_factor(np.hstack(low_pts[chan_range]), np.hstack(high_pts[chan_range]), method='distrib', verbose=True)",
"to some emission in the GBT data being cut-off by the # PB",
"data_path, allfigs_path) from constants import hi_freq from plotting_styles import onecolumn_figure # Compare with",
"* sigma, dist > 0.)) flat_dists = np.where(dist >= nsig_cut * sigma) weight_arr",
"1] - sc_factor_chans_linfit], alpha=0.5, label='Linear fit') # plt.plot(chans, slope_lowess_85) plt.axhline(1, linestyle='--') plt.legend(frameon=True) plt.ylabel(r\"Scale",
"the frequency in the individual channel MSs used in # imaging. It's not",
"high, method='distrib', verbose=False) sc_factor_chans.append(sc_f) sc_err_chans.append(sc_e) sc_factor_chans_linfit = [] sc_err_chans_linfit = [] for low,",
"within the mosaic PB chan_range = slice(80, 160) onecolumn_figure() sc_factor_chrange, sc_err_chrange = \\",
"factor is due to some emission in the GBT data being cut-off by",
"# Error still underestimated # The >1 factor is due to some emission",
"M33. So the data were # gridded with a Gaussian kernel, rather than",
"sc_err_chans_linfit[:, 1] - sc_factor_chans_linfit], alpha=0.5, label='Linear fit') # plt.plot(chans, slope_lowess_85) plt.axhline(1, linestyle='--') plt.legend(frameon=True)",
"u.spectral())) / diam.to(u.cm)) * u.rad # Already determined from the 14B HI analysis.",
"from cube_analysis.feather_cubes import feather_compare_cube from paths import (seventeenB_HI_data_02kms_path, seventeenB_HI_data_1kms_path, data_path, allfigs_path) from constants",
"import astropy.units as u import matplotlib.pyplot as plt import os import scipy.ndimage as",
"a Gaussian kernel, rather than a jinc function gbt_eff_beam = beam_fwhm(87.5 * u.m)",
"nsig_cut=5) gbt_path = os.path.join(data_path, \"GBT\") # gbt_cube = SpectralCube.read(os.path.join(gbt_path, \"17B-162_items/m33_gbt_vlsr_highres_Tmb_17B162_02kms.fits\")) gbt_cube = SpectralCube.read(os.path.join(gbt_path,",
"Fit') plt.errorbar(chans, sc_factor_chans_linfit, yerr=[sc_factor_chans_linfit - sc_err_chans_linfit[:, 0], sc_err_chans_linfit[:, 1] - sc_factor_chans_linfit], alpha=0.5, label='Linear",
"high_pts, low_pts, chan_out = \\ feather_compare_cube(vla_cube, gbt_cube, las, num_cores=1, lowresfwhm=gbt_eff_beam, chunk=50, verbose=False, weights=weight,",
"plt.savefig(allfigs_path(f\"Imaging/ratio_hist_17B_vla_gbt_9.8arcmin_chan_{chan_range.start}_{chan_range.stop}_v3_w_weights.png\")) plt.savefig(allfigs_path(f\"Imaging/ratio_hist_17B_vla_gbt_9.8arcmin_chan_{chan_range.start}_{chan_range.stop}_v3_w_weights.pdf\")) print(\"Factor: {0}+/-{1}\".format(sc_factor_chrange, sc_err_chrange)) # Factor: 1.105133+/-0.00463 # Error still underestimated #",
"import matplotlib.pyplot as plt import os import scipy.ndimage as nd from uvcombine.scale_factor import",
"las = (hi_freq.to(u.cm, u.spectral()) / (44 * u.m)).to(u.arcsec, u.dimensionless_angles()) radii, ratios, high_pts, low_pts,",
"rather than a jinc function gbt_eff_beam = beam_fwhm(87.5 * u.m) # The shortest",
"= [] sc_err_chans = [] for low, high in zip(low_pts, high_pts): sc_f, sc_e",
"imaging. It's not even a half-channel offset like I # would expect if",
"plt.legend(frameon=True) plt.ylabel(r\"Scale Factor\") plt.xlabel(\"Channels\") plt.grid(True) plt.tight_layout() plt.savefig(allfigs_path(\"Imaging/ratio_hist_perchan_17B_vla_gbt_9.8arcmin_v3_w_weights.png\")) plt.savefig(allfigs_path(\"Imaging/ratio_hist_perchan_17B_vla_gbt_9.8arcmin_v3_w_weights.pdf\")) plt.close() # Now refit with",
"HI analysis. Lowered spatial resolution # due to lack of overlap in the",
"is 0.36 times the # channel size. I have no idea where this",
"~0.4 km/s between the cubes # The big GBT beam means this really",
"print(\"Factor: {0}+/-{1}\".format(sc_factor, sc_err)) # Factor: 1.125046+/-0.00394768 # This isn't a fantastic fit, so",
"in the uv plane. No offset correction is needed. ''' from spectral_cube import",
"function gbt_eff_beam = beam_fwhm(87.5 * u.m) # The shortest baseline in the 14B-088",
"import hi_freq from plotting_styles import onecolumn_figure # Compare with the 1 km/s cube.",
"the larger 14B data). # So, despite the != 1 factor, no factor",
"* sigma) weight_arr = np.zeros_like(mask, dtype=float) weight_arr[gauss_dists] = \\ np.exp(- (dist[gauss_dists] - nsig_cut",
"0.4}) onecolumn_figure() sc_factor, sc_err = find_scale_factor(np.hstack(low_pts), np.hstack(high_pts), method='distrib', verbose=True) plt.grid(True) plt.xlabel(r\"ln I$_{\\rm int}$",
"linestyle='--') plt.legend(frameon=True) plt.ylabel(r\"Scale Factor\") plt.xlabel(\"Channels\") plt.grid(True) plt.tight_layout() plt.savefig(allfigs_path(\"Imaging/ratio_hist_perchan_17B_vla_gbt_9.8arcmin_v3_w_weights.png\")) plt.savefig(allfigs_path(\"Imaging/ratio_hist_perchan_17B_vla_gbt_9.8arcmin_v3_w_weights.pdf\")) plt.close() # Now refit",
"(dist[gauss_dists] - nsig_cut * sigma)**2 / (2 * sigma**2)) weight_arr[flat_dists] = 1. return",
"big GBT beam means this really doesn't matter (I # manually checked). The",
"plt.grid(True) plt.xlabel(r\"ln I$_{\\rm int}$ / I$_{\\rm SD}$\") plt.tight_layout() plt.savefig(allfigs_path(\"Imaging/ratio_hist_17B_vla_gbt_9.8arcmin_v3_w_weights.png\")) plt.savefig(allfigs_path(\"Imaging/ratio_hist_17B_vla_gbt_9.8arcmin_v3_w_weights.pdf\")) print(\"Factor: {0}+/-{1}\".format(sc_factor, sc_err))",
"= lambda diam: ((1.18 * hi_freq.to(u.cm, u.spectral())) / diam.to(u.cm)) * u.rad # Already",
"were # gridded with a Gaussian kernel, rather than a jinc function gbt_eff_beam",
"nsig_cut * sigma, dist > 0.)) flat_dists = np.where(dist >= nsig_cut * sigma)",
"vla_cube = SpectralCube.read(seventeenB_HI_data_1kms_path(\"M33_14B_17B_HI_contsub_width_1kms.image.pbcor.fits\")) # pb_cube = SpectralCube.read(seventeenB_HI_data_02kms_path(\"M33_14B_17B_HI_contsub_width_02kms.pb.fits\")) pb_cube = SpectralCube.read(seventeenB_HI_data_1kms_path(\"M33_14B_17B_HI_contsub_width_1kms.pb.fits\")) # PB minimally",
"Lowered spatial resolution # due to lack of overlap in the GBT fields",
"of the HI # structure falls within the mosaic PB chan_range = slice(80,",
"significantly underestimated plt.close() # Compare properties per-channel sc_factor_chans = [] sc_err_chans = []",
"data being cut-off by the # PB limit of the VLA mosaic. The",
"= np.where(np.logical_and(dist < nsig_cut * sigma, dist > 0.)) flat_dists = np.where(dist >=",
"structure falls within the mosaic PB chan_range = slice(80, 160) onecolumn_figure() sc_factor_chrange, sc_err_chrange",
"14B HI analysis. Lowered spatial resolution # due to lack of overlap in",
"is coming # from since the freq axis used in `gbt_regrid.py` matches #",
"this error was significantly underestimated plt.close() # Compare properties per-channel sc_factor_chans = []",
"14B data). # So, despite the != 1 factor, no factor will be",
"So, despite the != 1 factor, no factor will be applied to the",
"offset correction is needed. ''' from spectral_cube import SpectralCube import numpy as np",
"overlap in the uv plane. No offset correction is needed. ''' from spectral_cube",
"data. # Besides, the 14B mosaic comparison gives a 1.0 factor with the",
"the channels near the systemic velocity, where most of the HI # structure",
"with the channels near the systemic velocity, where most of the HI #",
"= taper_weights(np.isfinite(pb_plane), 30, nsig_cut=5) gbt_path = os.path.join(data_path, \"GBT\") # gbt_cube = SpectralCube.read(os.path.join(gbt_path, \"17B-162_items/m33_gbt_vlsr_highres_Tmb_17B162_02kms.fits\"))",
"high_pts): sc_f, sc_e = \\ find_scale_factor(low, high, method='distrib', verbose=False) sc_factor_chans.append(sc_f) sc_err_chans.append(sc_e) sc_factor_chans_linfit =",
"between the cubes # The big GBT beam means this really doesn't matter",
"spectral_cube import SpectralCube import numpy as np import astropy.units as u import matplotlib.pyplot",
"emission outside # of the VLA mosaic def taper_weights(mask, sigma, nsig_cut=3): dist =",
"import SpectralCube import numpy as np import astropy.units as u import matplotlib.pyplot as",
"# the frequency in the individual channel MSs used in # imaging. It's",
"a half-channel offset like I # would expect if the MS frequency was",
"verbose=True) plt.grid(True) plt.xlabel(r\"ln I$_{\\rm int}$ / I$_{\\rm SD}$\") plt.tight_layout() plt.savefig(allfigs_path(\"Imaging/ratio_hist_17B_vla_gbt_9.8arcmin_v3_w_weights.png\")) plt.savefig(allfigs_path(\"Imaging/ratio_hist_17B_vla_gbt_9.8arcmin_v3_w_weights.pdf\")) print(\"Factor: {0}+/-{1}\".format(sc_factor,",
"/ (44 * u.m)).to(u.arcsec, u.dimensionless_angles()) radii, ratios, high_pts, low_pts, chan_out = \\ feather_compare_cube(vla_cube,",
"\\ feather_compare_cube(vla_cube, gbt_cube, las, num_cores=1, lowresfwhm=gbt_eff_beam, chunk=50, verbose=False, weights=weight, relax_spectral_check=False, # NOTE: there",
"method='distrib', verbose=True) plt.grid(True) plt.xlabel(r\"ln I$_{\\rm int}$ / I$_{\\rm SD}$\") plt.tight_layout() plt.savefig(allfigs_path(\"Imaging/ratio_hist_17B_vla_gbt_9.8arcmin_v3_w_weights.png\")) plt.savefig(allfigs_path(\"Imaging/ratio_hist_17B_vla_gbt_9.8arcmin_v3_w_weights.pdf\")) print(\"Factor:",
"relax_spectral_check=False, # NOTE: there is an offset of ~0.4 km/s between the cubes",
"spatial resolution # due to lack of overlap in the GBT fields centered",
"I$_{\\rm int}$ / I$_{\\rm SD}$\") plt.tight_layout() plt.savefig(allfigs_path(f\"Imaging/ratio_hist_17B_vla_gbt_9.8arcmin_chan_{chan_range.start}_{chan_range.stop}_v3_w_weights.png\")) plt.savefig(allfigs_path(f\"Imaging/ratio_hist_17B_vla_gbt_9.8arcmin_chan_{chan_range.start}_{chan_range.stop}_v3_w_weights.pdf\")) print(\"Factor: {0}+/-{1}\".format(sc_factor_chrange, sc_err_chrange)) # Factor:",
"of the VLA mosaic. The factor increases far from the systemic # velocity,",
"fit') # plt.plot(chans, slope_lowess_85) plt.axhline(1, linestyle='--') plt.legend(frameon=True) plt.ylabel(r\"Scale Factor\") plt.xlabel(\"Channels\") plt.grid(True) plt.tight_layout() plt.savefig(allfigs_path(\"Imaging/ratio_hist_perchan_17B_vla_gbt_9.8arcmin_v3_w_weights.png\"))",
"np.where(dist >= nsig_cut * sigma) weight_arr = np.zeros_like(mask, dtype=float) weight_arr[gauss_dists] = \\ np.exp(-",
"Now refit with the channels near the systemic velocity, where most of the",
"int}$ / I$_{\\rm SD}$\") plt.tight_layout() plt.savefig(allfigs_path(\"Imaging/ratio_hist_17B_vla_gbt_9.8arcmin_v3_w_weights.png\")) plt.savefig(allfigs_path(\"Imaging/ratio_hist_17B_vla_gbt_9.8arcmin_v3_w_weights.pdf\")) print(\"Factor: {0}+/-{1}\".format(sc_factor, sc_err)) # Factor: 1.125046+/-0.00394768",
"systemic # velocity, where bright HI gets cut-off (compared to the larger 14B",
"the uv plane. No offset correction is needed. ''' from spectral_cube import SpectralCube",
"SpectralCube.read(seventeenB_HI_data_1kms_path(\"M33_14B_17B_HI_contsub_width_1kms.image.pbcor.fits\")) # pb_cube = SpectralCube.read(seventeenB_HI_data_02kms_path(\"M33_14B_17B_HI_contsub_width_02kms.pb.fits\")) pb_cube = SpectralCube.read(seventeenB_HI_data_1kms_path(\"M33_14B_17B_HI_contsub_width_1kms.pb.fits\")) # PB minimally changes over",
"nd.distance_transform_edt(mask) gauss_dists = np.where(np.logical_and(dist < nsig_cut * sigma, dist > 0.)) flat_dists =",
"So just grab one plane pb_plane = pb_cube[0] # We need to define",
"the mosaic PB chan_range = slice(80, 160) onecolumn_figure() sc_factor_chrange, sc_err_chrange = \\ find_scale_factor(np.hstack(low_pts[chan_range]),",
"seventeenB_HI_data_1kms_path, data_path, allfigs_path) from constants import hi_freq from plotting_styles import onecolumn_figure # Compare",
"matches # the frequency in the individual channel MSs used in # imaging.",
"sigma, dist > 0.)) flat_dists = np.where(dist >= nsig_cut * sigma) weight_arr =",
"velocity, where most of the HI # structure falls within the mosaic PB",
"GBT fields centered at M33. So the data were # gridded with a",
"data). # So, despite the != 1 factor, no factor will be applied",
"Gaussian kernel, rather than a jinc function gbt_eff_beam = beam_fwhm(87.5 * u.m) #",
"# This isn't a fantastic fit, so this error was significantly underestimated plt.close()",
"dist > 0.)) flat_dists = np.where(dist >= nsig_cut * sigma) weight_arr = np.zeros_like(mask,",
"the GBT fields centered at M33. So the data were # gridded with",
"checked). The difference is 0.36 times the # channel size. I have no",
"GBT beam means this really doesn't matter (I # manually checked). The difference",
"low_pts, chan_out = \\ feather_compare_cube(vla_cube, gbt_cube, las, num_cores=1, lowresfwhm=gbt_eff_beam, chunk=50, verbose=False, weights=weight, relax_spectral_check=False,",
"near the systemic velocity, where most of the HI # structure falls within",
"np.array(sc_err_chans_linfit) chans = np.arange(len(low_pts)) onecolumn_figure() plt.errorbar(chans, sc_factor_chans, yerr=sc_err_chans, alpha=0.5, label='Distrib Fit') plt.errorbar(chans, sc_factor_chans_linfit,",
">1 factor is due to some emission in the GBT data being cut-off",
"size. I have no idea where this shift is coming # from since",
"the cubes # The big GBT beam means this really doesn't matter (I",
"where most of the HI # structure falls within the mosaic PB chan_range",
"centered at M33. So the data were # gridded with a Gaussian kernel,",
"since the freq axis used in `gbt_regrid.py` matches # the frequency in the",
"gbt_cube, las, num_cores=1, lowresfwhm=gbt_eff_beam, chunk=50, verbose=False, weights=weight, relax_spectral_check=False, # NOTE: there is an",
"comparison gives a 1.0 factor with the GBT data. # The tests here",
"weighting function to ignore emission outside # of the VLA mosaic def taper_weights(mask,",
"in the GBT fields centered at M33. So the data were # gridded",
"# So, despite the != 1 factor, no factor will be applied to",
"frequency range. So just grab one plane pb_plane = pb_cube[0] # We need",
"num_cores=1, lowresfwhm=gbt_eff_beam, chunk=50, verbose=False, weights=weight, relax_spectral_check=False, # NOTE: there is an offset of",
"radii, ratios, high_pts, low_pts, chan_out = \\ feather_compare_cube(vla_cube, gbt_cube, las, num_cores=1, lowresfwhm=gbt_eff_beam, chunk=50,",
"\\ find_scale_factor(low, high, method='linfit', verbose=False) sc_factor_chans_linfit.append(sc_f) sc_err_chans_linfit.append(sc_e) sc_factor_chans_linfit = np.array(sc_factor_chans_linfit) sc_err_chans_linfit = np.array(sc_err_chans_linfit)",
"# The tests here were for consistency and that's what we find. plt.close()",
"vla_cube = SpectralCube.read(seventeenB_HI_data_02kms_path(\"M33_14B_17B_HI_contsub_width_02kms.image.pbcor.fits\")) vla_cube = SpectralCube.read(seventeenB_HI_data_1kms_path(\"M33_14B_17B_HI_contsub_width_1kms.image.pbcor.fits\")) # pb_cube = SpectralCube.read(seventeenB_HI_data_02kms_path(\"M33_14B_17B_HI_contsub_width_02kms.pb.fits\")) pb_cube = SpectralCube.read(seventeenB_HI_data_1kms_path(\"M33_14B_17B_HI_contsub_width_1kms.pb.fits\"))",
"sc_err = find_scale_factor(np.hstack(low_pts), np.hstack(high_pts), method='distrib', verbose=True) plt.grid(True) plt.xlabel(r\"ln I$_{\\rm int}$ / I$_{\\rm SD}$\")",
"SpectralCube import numpy as np import astropy.units as u import matplotlib.pyplot as plt",
"sc_err)) # Factor: 1.125046+/-0.00394768 # This isn't a fantastic fit, so this error",
"emission in the GBT data being cut-off by the # PB limit of",
"with the GBT data. # The tests here were for consistency and that's",
"I # would expect if the MS frequency was the channel edge... spec_check_kwargs={'rtol':",
"VLA mosaic def taper_weights(mask, sigma, nsig_cut=3): dist = nd.distance_transform_edt(mask) gauss_dists = np.where(np.logical_and(dist <",
"= np.zeros_like(mask, dtype=float) weight_arr[gauss_dists] = \\ np.exp(- (dist[gauss_dists] - nsig_cut * sigma)**2 /",
"slope_lowess_85) plt.axhline(1, linestyle='--') plt.legend(frameon=True) plt.ylabel(r\"Scale Factor\") plt.xlabel(\"Channels\") plt.grid(True) plt.tight_layout() plt.savefig(allfigs_path(\"Imaging/ratio_hist_perchan_17B_vla_gbt_9.8arcmin_v3_w_weights.png\")) plt.savefig(allfigs_path(\"Imaging/ratio_hist_perchan_17B_vla_gbt_9.8arcmin_v3_w_weights.pdf\")) plt.close() #",
"{0}+/-{1}\".format(sc_factor_chrange, sc_err_chrange)) # Factor: 1.105133+/-0.00463 # Error still underestimated # The >1 factor",
"* sigma)**2 / (2 * sigma**2)) weight_arr[flat_dists] = 1. return weight_arr weight =",
"plt.savefig(allfigs_path(\"Imaging/ratio_hist_17B_vla_gbt_9.8arcmin_v3_w_weights.png\")) plt.savefig(allfigs_path(\"Imaging/ratio_hist_17B_vla_gbt_9.8arcmin_v3_w_weights.pdf\")) print(\"Factor: {0}+/-{1}\".format(sc_factor, sc_err)) # Factor: 1.125046+/-0.00394768 # This isn't a fantastic",
"is needed. ''' from spectral_cube import SpectralCube import numpy as np import astropy.units",
"of the VLA mosaic def taper_weights(mask, sigma, nsig_cut=3): dist = nd.distance_transform_edt(mask) gauss_dists =",
"lack of overlap in the GBT fields centered at M33. So the data",
"NOTE: there is an offset of ~0.4 km/s between the cubes # The",
"beam_fwhm(87.5 * u.m) # The shortest baseline in the 14B-088 data is ~44",
"lambda diam: ((1.18 * hi_freq.to(u.cm, u.spectral())) / diam.to(u.cm)) * u.rad # Already determined",
"< nsig_cut * sigma, dist > 0.)) flat_dists = np.where(dist >= nsig_cut *",
"isn't a fantastic fit, so this error was significantly underestimated plt.close() # Compare",
"verbose=False) sc_factor_chans.append(sc_f) sc_err_chans.append(sc_e) sc_factor_chans_linfit = [] sc_err_chans_linfit = [] for low, high in",
"from paths import (seventeenB_HI_data_02kms_path, seventeenB_HI_data_1kms_path, data_path, allfigs_path) from constants import hi_freq from plotting_styles",
"(compared to the larger 14B data). # So, despite the != 1 factor,",
"systemic velocity, where most of the HI # structure falls within the mosaic",
"beam_fwhm = lambda diam: ((1.18 * hi_freq.to(u.cm, u.spectral())) / diam.to(u.cm)) * u.rad #",
"yerr=[sc_factor_chans_linfit - sc_err_chans_linfit[:, 0], sc_err_chans_linfit[:, 1] - sc_factor_chans_linfit], alpha=0.5, label='Linear fit') # plt.plot(chans,",
"= nd.distance_transform_edt(mask) gauss_dists = np.where(np.logical_and(dist < nsig_cut * sigma, dist > 0.)) flat_dists",
"ratios, high_pts, low_pts, chan_out = \\ feather_compare_cube(vla_cube, gbt_cube, las, num_cores=1, lowresfwhm=gbt_eff_beam, chunk=50, verbose=False,",
"onecolumn_figure # Compare with the 1 km/s cube. Higher S/N # vla_cube =",
"a 1.0 factor with the GBT data. # The tests here were for",
"the VLA mosaic. The factor increases far from the systemic # velocity, where",
"used in `gbt_regrid.py` matches # the frequency in the individual channel MSs used",
"the 14B-088 data is ~44 m. las = (hi_freq.to(u.cm, u.spectral()) / (44 *",
"zip(low_pts, high_pts): sc_f, sc_e = \\ find_scale_factor(low, high, method='linfit', verbose=False) sc_factor_chans_linfit.append(sc_f) sc_err_chans_linfit.append(sc_e) sc_factor_chans_linfit",
"most of the HI # structure falls within the mosaic PB chan_range =",
"verbose=False, weights=weight, relax_spectral_check=False, # NOTE: there is an offset of ~0.4 km/s between",
"idea where this shift is coming # from since the freq axis used",
"import onecolumn_figure # Compare with the 1 km/s cube. Higher S/N # vla_cube",
"to lack of overlap in the GBT fields centered at M33. So the",
"14B mosaic comparison gives a 1.0 factor with the GBT data. # The",
"be applied to the SD data. # Besides, the 14B mosaic comparison gives",
"function to ignore emission outside # of the VLA mosaic def taper_weights(mask, sigma,",
"sc_factor_chans_linfit], alpha=0.5, label='Linear fit') # plt.plot(chans, slope_lowess_85) plt.axhline(1, linestyle='--') plt.legend(frameon=True) plt.ylabel(r\"Scale Factor\") plt.xlabel(\"Channels\")",
"So the data were # gridded with a Gaussian kernel, rather than a",
"this really doesn't matter (I # manually checked). The difference is 0.36 times",
"plt.savefig(allfigs_path(\"Imaging/ratio_hist_17B_vla_gbt_9.8arcmin_v3_w_weights.pdf\")) print(\"Factor: {0}+/-{1}\".format(sc_factor, sc_err)) # Factor: 1.125046+/-0.00394768 # This isn't a fantastic fit,",
"plt.plot(chans, slope_lowess_85) plt.axhline(1, linestyle='--') plt.legend(frameon=True) plt.ylabel(r\"Scale Factor\") plt.xlabel(\"Channels\") plt.grid(True) plt.tight_layout() plt.savefig(allfigs_path(\"Imaging/ratio_hist_perchan_17B_vla_gbt_9.8arcmin_v3_w_weights.png\")) plt.savefig(allfigs_path(\"Imaging/ratio_hist_perchan_17B_vla_gbt_9.8arcmin_v3_w_weights.pdf\")) plt.close()",
"> 0.)) flat_dists = np.where(dist >= nsig_cut * sigma) weight_arr = np.zeros_like(mask, dtype=float)",
"increases far from the systemic # velocity, where bright HI gets cut-off (compared",
"zip(low_pts, high_pts): sc_f, sc_e = \\ find_scale_factor(low, high, method='distrib', verbose=False) sc_factor_chans.append(sc_f) sc_err_chans.append(sc_e) sc_factor_chans_linfit",
"pb_cube = SpectralCube.read(seventeenB_HI_data_1kms_path(\"M33_14B_17B_HI_contsub_width_1kms.pb.fits\")) # PB minimally changes over the frequency range. So just",
"\\ find_scale_factor(low, high, method='distrib', verbose=False) sc_factor_chans.append(sc_f) sc_err_chans.append(sc_e) sc_factor_chans_linfit = [] sc_err_chans_linfit = []",
"minimally changes over the frequency range. So just grab one plane pb_plane =",
"channel size. I have no idea where this shift is coming # from",
"find_scale_factor(np.hstack(low_pts[chan_range]), np.hstack(high_pts[chan_range]), method='distrib', verbose=True) plt.grid(True) plt.xlabel(r\"ln I$_{\\rm int}$ / I$_{\\rm SD}$\") plt.tight_layout() plt.savefig(allfigs_path(f\"Imaging/ratio_hist_17B_vla_gbt_9.8arcmin_chan_{chan_range.start}_{chan_range.stop}_v3_w_weights.png\"))",
"despite the != 1 factor, no factor will be applied to the SD",
"outside # of the VLA mosaic def taper_weights(mask, sigma, nsig_cut=3): dist = nd.distance_transform_edt(mask)",
"MS frequency was the channel edge... spec_check_kwargs={'rtol': 0.4}) onecolumn_figure() sc_factor, sc_err = find_scale_factor(np.hstack(low_pts),",
"from since the freq axis used in `gbt_regrid.py` matches # the frequency in",
"# The big GBT beam means this really doesn't matter (I # manually",
"plane pb_plane = pb_cube[0] # We need to define a tapered weighting function",
"will be applied to the SD data. # Besides, the 14B mosaic comparison",
"to ignore emission outside # of the VLA mosaic def taper_weights(mask, sigma, nsig_cut=3):",
"far from the systemic # velocity, where bright HI gets cut-off (compared to",
"np.exp(- (dist[gauss_dists] - nsig_cut * sigma)**2 / (2 * sigma**2)) weight_arr[flat_dists] = 1.",
"- nsig_cut * sigma)**2 / (2 * sigma**2)) weight_arr[flat_dists] = 1. return weight_arr",
"u.m)).to(u.arcsec, u.dimensionless_angles()) radii, ratios, high_pts, low_pts, chan_out = \\ feather_compare_cube(vla_cube, gbt_cube, las, num_cores=1,",
"S/N # vla_cube = SpectralCube.read(seventeenB_HI_data_02kms_path(\"M33_14B_17B_HI_contsub_width_02kms.image.pbcor.fits\")) vla_cube = SpectralCube.read(seventeenB_HI_data_1kms_path(\"M33_14B_17B_HI_contsub_width_1kms.image.pbcor.fits\")) # pb_cube = SpectralCube.read(seventeenB_HI_data_02kms_path(\"M33_14B_17B_HI_contsub_width_02kms.pb.fits\")) pb_cube",
"being cut-off by the # PB limit of the VLA mosaic. The factor",
"las, num_cores=1, lowresfwhm=gbt_eff_beam, chunk=50, verbose=False, weights=weight, relax_spectral_check=False, # NOTE: there is an offset",
"import feather_compare_cube from paths import (seventeenB_HI_data_02kms_path, seventeenB_HI_data_1kms_path, data_path, allfigs_path) from constants import hi_freq",
"chunk=50, verbose=False, weights=weight, relax_spectral_check=False, # NOTE: there is an offset of ~0.4 km/s",
"= [] for low, high in zip(low_pts, high_pts): sc_f, sc_e = \\ find_scale_factor(low,",
"the MS frequency was the channel edge... spec_check_kwargs={'rtol': 0.4}) onecolumn_figure() sc_factor, sc_err =",
"sc_err_chans_linfit.append(sc_e) sc_factor_chans_linfit = np.array(sc_factor_chans_linfit) sc_err_chans_linfit = np.array(sc_err_chans_linfit) chans = np.arange(len(low_pts)) onecolumn_figure() plt.errorbar(chans, sc_factor_chans,",
"the # channel size. I have no idea where this shift is coming",
"underestimated plt.close() # Compare properties per-channel sc_factor_chans = [] sc_err_chans = [] for",
"SpectralCube.read(os.path.join(gbt_path, \"17B-162_items/m33_gbt_vlsr_highres_Tmb_17B162_02kms.fits\")) gbt_cube = SpectralCube.read(os.path.join(gbt_path, \"17B-162_items/m33_gbt_vlsr_highres_Tmb_17B162_1kms.fits\")) beam_fwhm = lambda diam: ((1.18 * hi_freq.to(u.cm,",
"was the channel edge... spec_check_kwargs={'rtol': 0.4}) onecolumn_figure() sc_factor, sc_err = find_scale_factor(np.hstack(low_pts), np.hstack(high_pts), method='distrib',",
"this shift is coming # from since the freq axis used in `gbt_regrid.py`",
"to the larger 14B data). # So, despite the != 1 factor, no",
"grab one plane pb_plane = pb_cube[0] # We need to define a tapered",
"Error still underestimated # The >1 factor is due to some emission in",
"gbt_cube = SpectralCube.read(os.path.join(gbt_path, \"17B-162_items/m33_gbt_vlsr_highres_Tmb_17B162_1kms.fits\")) beam_fwhm = lambda diam: ((1.18 * hi_freq.to(u.cm, u.spectral())) /",
"kernel, rather than a jinc function gbt_eff_beam = beam_fwhm(87.5 * u.m) # The",
"plane. No offset correction is needed. ''' from spectral_cube import SpectralCube import numpy",
"(hi_freq.to(u.cm, u.spectral()) / (44 * u.m)).to(u.arcsec, u.dimensionless_angles()) radii, ratios, high_pts, low_pts, chan_out =",
"gridded with a Gaussian kernel, rather than a jinc function gbt_eff_beam = beam_fwhm(87.5",
"# of the VLA mosaic def taper_weights(mask, sigma, nsig_cut=3): dist = nd.distance_transform_edt(mask) gauss_dists",
"label='Linear fit') # plt.plot(chans, slope_lowess_85) plt.axhline(1, linestyle='--') plt.legend(frameon=True) plt.ylabel(r\"Scale Factor\") plt.xlabel(\"Channels\") plt.grid(True) plt.tight_layout()",
"from spectral_cube import SpectralCube import numpy as np import astropy.units as u import",
"range. So just grab one plane pb_plane = pb_cube[0] # We need to",
"* sigma**2)) weight_arr[flat_dists] = 1. return weight_arr weight = taper_weights(np.isfinite(pb_plane), 30, nsig_cut=5) gbt_path",
"weight_arr weight = taper_weights(np.isfinite(pb_plane), 30, nsig_cut=5) gbt_path = os.path.join(data_path, \"GBT\") # gbt_cube =",
"the individual channel MSs used in # imaging. It's not even a half-channel",
"gbt_path = os.path.join(data_path, \"GBT\") # gbt_cube = SpectralCube.read(os.path.join(gbt_path, \"17B-162_items/m33_gbt_vlsr_highres_Tmb_17B162_02kms.fits\")) gbt_cube = SpectralCube.read(os.path.join(gbt_path, \"17B-162_items/m33_gbt_vlsr_highres_Tmb_17B162_1kms.fits\"))",
"plt.grid(True) plt.tight_layout() plt.savefig(allfigs_path(\"Imaging/ratio_hist_perchan_17B_vla_gbt_9.8arcmin_v3_w_weights.png\")) plt.savefig(allfigs_path(\"Imaging/ratio_hist_perchan_17B_vla_gbt_9.8arcmin_v3_w_weights.pdf\")) plt.close() # Now refit with the channels near the",
"one plane pb_plane = pb_cube[0] # We need to define a tapered weighting",
"the channel edge... spec_check_kwargs={'rtol': 0.4}) onecolumn_figure() sc_factor, sc_err = find_scale_factor(np.hstack(low_pts), np.hstack(high_pts), method='distrib', verbose=True)",
"# Compare properties per-channel sc_factor_chans = [] sc_err_chans = [] for low, high",
"as u import matplotlib.pyplot as plt import os import scipy.ndimage as nd from",
"method='linfit', verbose=False) sc_factor_chans_linfit.append(sc_f) sc_err_chans_linfit.append(sc_e) sc_factor_chans_linfit = np.array(sc_factor_chans_linfit) sc_err_chans_linfit = np.array(sc_err_chans_linfit) chans = np.arange(len(low_pts))",
"diam: ((1.18 * hi_freq.to(u.cm, u.spectral())) / diam.to(u.cm)) * u.rad # Already determined from",
"sc_err_chans_linfit[:, 0], sc_err_chans_linfit[:, 1] - sc_factor_chans_linfit], alpha=0.5, label='Linear fit') # plt.plot(chans, slope_lowess_85) plt.axhline(1,",
"spec_check_kwargs={'rtol': 0.4}) onecolumn_figure() sc_factor, sc_err = find_scale_factor(np.hstack(low_pts), np.hstack(high_pts), method='distrib', verbose=True) plt.grid(True) plt.xlabel(r\"ln I$_{\\rm",
"SpectralCube.read(os.path.join(gbt_path, \"17B-162_items/m33_gbt_vlsr_highres_Tmb_17B162_1kms.fits\")) beam_fwhm = lambda diam: ((1.18 * hi_freq.to(u.cm, u.spectral())) / diam.to(u.cm)) *",
"print(\"Factor: {0}+/-{1}\".format(sc_factor_chrange, sc_err_chrange)) # Factor: 1.105133+/-0.00463 # Error still underestimated # The >1",
"edge... spec_check_kwargs={'rtol': 0.4}) onecolumn_figure() sc_factor, sc_err = find_scale_factor(np.hstack(low_pts), np.hstack(high_pts), method='distrib', verbose=True) plt.grid(True) plt.xlabel(r\"ln",
"PB minimally changes over the frequency range. So just grab one plane pb_plane",
"\"17B-162_items/m33_gbt_vlsr_highres_Tmb_17B162_02kms.fits\")) gbt_cube = SpectralCube.read(os.path.join(gbt_path, \"17B-162_items/m33_gbt_vlsr_highres_Tmb_17B162_1kms.fits\")) beam_fwhm = lambda diam: ((1.18 * hi_freq.to(u.cm, u.spectral()))",
"plt.xlabel(\"Channels\") plt.grid(True) plt.tight_layout() plt.savefig(allfigs_path(\"Imaging/ratio_hist_perchan_17B_vla_gbt_9.8arcmin_v3_w_weights.png\")) plt.savefig(allfigs_path(\"Imaging/ratio_hist_perchan_17B_vla_gbt_9.8arcmin_v3_w_weights.pdf\")) plt.close() # Now refit with the channels near",
"import numpy as np import astropy.units as u import matplotlib.pyplot as plt import",
"beam means this really doesn't matter (I # manually checked). The difference is",
"mosaic def taper_weights(mask, sigma, nsig_cut=3): dist = nd.distance_transform_edt(mask) gauss_dists = np.where(np.logical_and(dist < nsig_cut",
"overlap in the GBT fields centered at M33. So the data were #",
"!= 1 factor, no factor will be applied to the SD data. #",
"doesn't matter (I # manually checked). The difference is 0.36 times the #",
"weights=weight, relax_spectral_check=False, # NOTE: there is an offset of ~0.4 km/s between the",
"some emission in the GBT data being cut-off by the # PB limit",
"numpy as np import astropy.units as u import matplotlib.pyplot as plt import os",
"from the systemic # velocity, where bright HI gets cut-off (compared to the",
"m. las = (hi_freq.to(u.cm, u.spectral()) / (44 * u.m)).to(u.arcsec, u.dimensionless_angles()) radii, ratios, high_pts,",
"astropy.units as u import matplotlib.pyplot as plt import os import scipy.ndimage as nd",
"sc_err_chans_linfit = np.array(sc_err_chans_linfit) chans = np.arange(len(low_pts)) onecolumn_figure() plt.errorbar(chans, sc_factor_chans, yerr=sc_err_chans, alpha=0.5, label='Distrib Fit')",
"channels near the systemic velocity, where most of the HI # structure falls",
"still underestimated # The >1 factor is due to some emission in the",
"over the frequency range. So just grab one plane pb_plane = pb_cube[0] #",
"PB chan_range = slice(80, 160) onecolumn_figure() sc_factor_chrange, sc_err_chrange = \\ find_scale_factor(np.hstack(low_pts[chan_range]), np.hstack(high_pts[chan_range]), method='distrib',",
"# Now refit with the channels near the systemic velocity, where most of",
"data is ~44 m. las = (hi_freq.to(u.cm, u.spectral()) / (44 * u.m)).to(u.arcsec, u.dimensionless_angles())",
"taper_weights(mask, sigma, nsig_cut=3): dist = nd.distance_transform_edt(mask) gauss_dists = np.where(np.logical_and(dist < nsig_cut * sigma,",
"the HI # structure falls within the mosaic PB chan_range = slice(80, 160)",
"[] sc_err_chans_linfit = [] for low, high in zip(low_pts, high_pts): sc_f, sc_e =",
"= SpectralCube.read(seventeenB_HI_data_02kms_path(\"M33_14B_17B_HI_contsub_width_02kms.pb.fits\")) pb_cube = SpectralCube.read(seventeenB_HI_data_1kms_path(\"M33_14B_17B_HI_contsub_width_1kms.pb.fits\")) # PB minimally changes over the frequency range.",
"the data where they overlap in the uv plane. No offset correction is",
"than a jinc function gbt_eff_beam = beam_fwhm(87.5 * u.m) # The shortest baseline",
"plt.savefig(allfigs_path(\"Imaging/ratio_hist_perchan_17B_vla_gbt_9.8arcmin_v3_w_weights.pdf\")) plt.close() # Now refit with the channels near the systemic velocity, where",
"allfigs_path) from constants import hi_freq from plotting_styles import onecolumn_figure # Compare with the",
"sigma) weight_arr = np.zeros_like(mask, dtype=float) weight_arr[gauss_dists] = \\ np.exp(- (dist[gauss_dists] - nsig_cut *",
"taper_weights(np.isfinite(pb_plane), 30, nsig_cut=5) gbt_path = os.path.join(data_path, \"GBT\") # gbt_cube = SpectralCube.read(os.path.join(gbt_path, \"17B-162_items/m33_gbt_vlsr_highres_Tmb_17B162_02kms.fits\")) gbt_cube",
"gets cut-off (compared to the larger 14B data). # So, despite the !=",
"onecolumn_figure() plt.errorbar(chans, sc_factor_chans, yerr=sc_err_chans, alpha=0.5, label='Distrib Fit') plt.errorbar(chans, sc_factor_chans_linfit, yerr=[sc_factor_chans_linfit - sc_err_chans_linfit[:, 0],",
"verbose=False) sc_factor_chans_linfit.append(sc_f) sc_err_chans_linfit.append(sc_e) sc_factor_chans_linfit = np.array(sc_factor_chans_linfit) sc_err_chans_linfit = np.array(sc_err_chans_linfit) chans = np.arange(len(low_pts)) onecolumn_figure()",
"sc_err_chrange = \\ find_scale_factor(np.hstack(low_pts[chan_range]), np.hstack(high_pts[chan_range]), method='distrib', verbose=True) plt.grid(True) plt.xlabel(r\"ln I$_{\\rm int}$ / I$_{\\rm",
"frequency was the channel edge... spec_check_kwargs={'rtol': 0.4}) onecolumn_figure() sc_factor, sc_err = find_scale_factor(np.hstack(low_pts), np.hstack(high_pts),",
"fit, so this error was significantly underestimated plt.close() # Compare properties per-channel sc_factor_chans",
"shift is coming # from since the freq axis used in `gbt_regrid.py` matches",
"dtype=float) weight_arr[gauss_dists] = \\ np.exp(- (dist[gauss_dists] - nsig_cut * sigma)**2 / (2 *",
"pb_cube[0] # We need to define a tapered weighting function to ignore emission",
"no idea where this shift is coming # from since the freq axis",
"axis used in `gbt_regrid.py` matches # the frequency in the individual channel MSs",
"refit with the channels near the systemic velocity, where most of the HI",
"find_scale_factor(low, high, method='distrib', verbose=False) sc_factor_chans.append(sc_f) sc_err_chans.append(sc_e) sc_factor_chans_linfit = [] sc_err_chans_linfit = [] for",
"alpha=0.5, label='Distrib Fit') plt.errorbar(chans, sc_factor_chans_linfit, yerr=[sc_factor_chans_linfit - sc_err_chans_linfit[:, 0], sc_err_chans_linfit[:, 1] - sc_factor_chans_linfit],",
"1.125046+/-0.00394768 # This isn't a fantastic fit, so this error was significantly underestimated",
"\\ find_scale_factor(np.hstack(low_pts[chan_range]), np.hstack(high_pts[chan_range]), method='distrib', verbose=True) plt.grid(True) plt.xlabel(r\"ln I$_{\\rm int}$ / I$_{\\rm SD}$\") plt.tight_layout()",
"weight = taper_weights(np.isfinite(pb_plane), 30, nsig_cut=5) gbt_path = os.path.join(data_path, \"GBT\") # gbt_cube = SpectralCube.read(os.path.join(gbt_path,",
"No offset correction is needed. ''' from spectral_cube import SpectralCube import numpy as",
"from constants import hi_freq from plotting_styles import onecolumn_figure # Compare with the 1",
"just grab one plane pb_plane = pb_cube[0] # We need to define a",
"was significantly underestimated plt.close() # Compare properties per-channel sc_factor_chans = [] sc_err_chans =",
"/ I$_{\\rm SD}$\") plt.tight_layout() plt.savefig(allfigs_path(\"Imaging/ratio_hist_17B_vla_gbt_9.8arcmin_v3_w_weights.png\")) plt.savefig(allfigs_path(\"Imaging/ratio_hist_17B_vla_gbt_9.8arcmin_v3_w_weights.pdf\")) print(\"Factor: {0}+/-{1}\".format(sc_factor, sc_err)) # Factor: 1.125046+/-0.00394768 #",
"resolution # due to lack of overlap in the GBT fields centered at",
"in `gbt_regrid.py` matches # the frequency in the individual channel MSs used in",
"in zip(low_pts, high_pts): sc_f, sc_e = \\ find_scale_factor(low, high, method='linfit', verbose=False) sc_factor_chans_linfit.append(sc_f) sc_err_chans_linfit.append(sc_e)",
"0], sc_err_chans_linfit[:, 1] - sc_factor_chans_linfit], alpha=0.5, label='Linear fit') # plt.plot(chans, slope_lowess_85) plt.axhline(1, linestyle='--')",
"/ diam.to(u.cm)) * u.rad # Already determined from the 14B HI analysis. Lowered",
"sc_factor, sc_err = find_scale_factor(np.hstack(low_pts), np.hstack(high_pts), method='distrib', verbose=True) plt.grid(True) plt.xlabel(r\"ln I$_{\\rm int}$ / I$_{\\rm",
"sc_err_chans = [] for low, high in zip(low_pts, high_pts): sc_f, sc_e = \\",
"from the 14B HI analysis. Lowered spatial resolution # due to lack of",
"used in # imaging. It's not even a half-channel offset like I #",
"for low, high in zip(low_pts, high_pts): sc_f, sc_e = \\ find_scale_factor(low, high, method='linfit',",
"# manually checked). The difference is 0.36 times the # channel size. I",
"plt.errorbar(chans, sc_factor_chans, yerr=sc_err_chans, alpha=0.5, label='Distrib Fit') plt.errorbar(chans, sc_factor_chans_linfit, yerr=[sc_factor_chans_linfit - sc_err_chans_linfit[:, 0], sc_err_chans_linfit[:,",
"not even a half-channel offset like I # would expect if the MS",
"correction is needed. ''' from spectral_cube import SpectralCube import numpy as np import",
"half-channel offset like I # would expect if the MS frequency was the",
"diam.to(u.cm)) * u.rad # Already determined from the 14B HI analysis. Lowered spatial",
"have no idea where this shift is coming # from since the freq",
"Compare properties per-channel sc_factor_chans = [] sc_err_chans = [] for low, high in",
"# PB limit of the VLA mosaic. The factor increases far from the",
"# velocity, where bright HI gets cut-off (compared to the larger 14B data).",
"weight_arr[gauss_dists] = \\ np.exp(- (dist[gauss_dists] - nsig_cut * sigma)**2 / (2 * sigma**2))",
"the VLA mosaic def taper_weights(mask, sigma, nsig_cut=3): dist = nd.distance_transform_edt(mask) gauss_dists = np.where(np.logical_and(dist",
"= slice(80, 160) onecolumn_figure() sc_factor_chrange, sc_err_chrange = \\ find_scale_factor(np.hstack(low_pts[chan_range]), np.hstack(high_pts[chan_range]), method='distrib', verbose=True) plt.grid(True)",
"falls within the mosaic PB chan_range = slice(80, 160) onecolumn_figure() sc_factor_chrange, sc_err_chrange =",
"scipy.ndimage as nd from uvcombine.scale_factor import find_scale_factor from cube_analysis.feather_cubes import feather_compare_cube from paths",
"where they overlap in the uv plane. No offset correction is needed. '''",
"the 14B HI analysis. Lowered spatial resolution # due to lack of overlap",
"import find_scale_factor from cube_analysis.feather_cubes import feather_compare_cube from paths import (seventeenB_HI_data_02kms_path, seventeenB_HI_data_1kms_path, data_path, allfigs_path)",
"plt.savefig(allfigs_path(f\"Imaging/ratio_hist_17B_vla_gbt_9.8arcmin_chan_{chan_range.start}_{chan_range.stop}_v3_w_weights.pdf\")) print(\"Factor: {0}+/-{1}\".format(sc_factor_chrange, sc_err_chrange)) # Factor: 1.105133+/-0.00463 # Error still underestimated # The",
"# would expect if the MS frequency was the channel edge... spec_check_kwargs={'rtol': 0.4})",
"sc_err_chans_linfit = [] for low, high in zip(low_pts, high_pts): sc_f, sc_e = \\",
"sc_e = \\ find_scale_factor(low, high, method='linfit', verbose=False) sc_factor_chans_linfit.append(sc_f) sc_err_chans_linfit.append(sc_e) sc_factor_chans_linfit = np.array(sc_factor_chans_linfit) sc_err_chans_linfit",
"cube_analysis.feather_cubes import feather_compare_cube from paths import (seventeenB_HI_data_02kms_path, seventeenB_HI_data_1kms_path, data_path, allfigs_path) from constants import",
"hi_freq.to(u.cm, u.spectral())) / diam.to(u.cm)) * u.rad # Already determined from the 14B HI",
"sc_factor_chans_linfit = np.array(sc_factor_chans_linfit) sc_err_chans_linfit = np.array(sc_err_chans_linfit) chans = np.arange(len(low_pts)) onecolumn_figure() plt.errorbar(chans, sc_factor_chans, yerr=sc_err_chans,",
"= SpectralCube.read(seventeenB_HI_data_1kms_path(\"M33_14B_17B_HI_contsub_width_1kms.pb.fits\")) # PB minimally changes over the frequency range. So just grab",
"the GBT data. # The tests here were for consistency and that's what",
"# from since the freq axis used in `gbt_regrid.py` matches # the frequency",
"determined from the 14B HI analysis. Lowered spatial resolution # due to lack",
"high, method='linfit', verbose=False) sc_factor_chans_linfit.append(sc_f) sc_err_chans_linfit.append(sc_e) sc_factor_chans_linfit = np.array(sc_factor_chans_linfit) sc_err_chans_linfit = np.array(sc_err_chans_linfit) chans =",
"MSs used in # imaging. It's not even a half-channel offset like I",
"manually checked). The difference is 0.36 times the # channel size. I have",
"offset of ~0.4 km/s between the cubes # The big GBT beam means",
"1 km/s cube. Higher S/N # vla_cube = SpectralCube.read(seventeenB_HI_data_02kms_path(\"M33_14B_17B_HI_contsub_width_02kms.image.pbcor.fits\")) vla_cube = SpectralCube.read(seventeenB_HI_data_1kms_path(\"M33_14B_17B_HI_contsub_width_1kms.image.pbcor.fits\")) #",
"This isn't a fantastic fit, so this error was significantly underestimated plt.close() #",
"The difference is 0.36 times the # channel size. I have no idea",
"sc_err_chrange)) # Factor: 1.105133+/-0.00463 # Error still underestimated # The >1 factor is",
"SD}$\") plt.tight_layout() plt.savefig(allfigs_path(f\"Imaging/ratio_hist_17B_vla_gbt_9.8arcmin_chan_{chan_range.start}_{chan_range.stop}_v3_w_weights.png\")) plt.savefig(allfigs_path(f\"Imaging/ratio_hist_17B_vla_gbt_9.8arcmin_chan_{chan_range.start}_{chan_range.stop}_v3_w_weights.pdf\")) print(\"Factor: {0}+/-{1}\".format(sc_factor_chrange, sc_err_chrange)) # Factor: 1.105133+/-0.00463 # Error still",
"I$_{\\rm SD}$\") plt.tight_layout() plt.savefig(allfigs_path(f\"Imaging/ratio_hist_17B_vla_gbt_9.8arcmin_chan_{chan_range.start}_{chan_range.stop}_v3_w_weights.png\")) plt.savefig(allfigs_path(f\"Imaging/ratio_hist_17B_vla_gbt_9.8arcmin_chan_{chan_range.start}_{chan_range.stop}_v3_w_weights.pdf\")) print(\"Factor: {0}+/-{1}\".format(sc_factor_chrange, sc_err_chrange)) # Factor: 1.105133+/-0.00463 # Error",
"= SpectralCube.read(seventeenB_HI_data_02kms_path(\"M33_14B_17B_HI_contsub_width_02kms.image.pbcor.fits\")) vla_cube = SpectralCube.read(seventeenB_HI_data_1kms_path(\"M33_14B_17B_HI_contsub_width_1kms.image.pbcor.fits\")) # pb_cube = SpectralCube.read(seventeenB_HI_data_02kms_path(\"M33_14B_17B_HI_contsub_width_02kms.pb.fits\")) pb_cube = SpectralCube.read(seventeenB_HI_data_1kms_path(\"M33_14B_17B_HI_contsub_width_1kms.pb.fits\")) #",
"Compare the data where they overlap in the uv plane. No offset correction",
"u.spectral()) / (44 * u.m)).to(u.arcsec, u.dimensionless_angles()) radii, ratios, high_pts, low_pts, chan_out = \\",
"u.rad # Already determined from the 14B HI analysis. Lowered spatial resolution #",
"nd from uvcombine.scale_factor import find_scale_factor from cube_analysis.feather_cubes import feather_compare_cube from paths import (seventeenB_HI_data_02kms_path,",
"We need to define a tapered weighting function to ignore emission outside #",
"# PB minimally changes over the frequency range. So just grab one plane",
"needed. ''' from spectral_cube import SpectralCube import numpy as np import astropy.units as",
"u import matplotlib.pyplot as plt import os import scipy.ndimage as nd from uvcombine.scale_factor",
"os.path.join(data_path, \"GBT\") # gbt_cube = SpectralCube.read(os.path.join(gbt_path, \"17B-162_items/m33_gbt_vlsr_highres_Tmb_17B162_02kms.fits\")) gbt_cube = SpectralCube.read(os.path.join(gbt_path, \"17B-162_items/m33_gbt_vlsr_highres_Tmb_17B162_1kms.fits\")) beam_fwhm =",
"(44 * u.m)).to(u.arcsec, u.dimensionless_angles()) radii, ratios, high_pts, low_pts, chan_out = \\ feather_compare_cube(vla_cube, gbt_cube,",
"plt.errorbar(chans, sc_factor_chans_linfit, yerr=[sc_factor_chans_linfit - sc_err_chans_linfit[:, 0], sc_err_chans_linfit[:, 1] - sc_factor_chans_linfit], alpha=0.5, label='Linear fit')",
"the systemic # velocity, where bright HI gets cut-off (compared to the larger",
"= np.array(sc_factor_chans_linfit) sc_err_chans_linfit = np.array(sc_err_chans_linfit) chans = np.arange(len(low_pts)) onecolumn_figure() plt.errorbar(chans, sc_factor_chans, yerr=sc_err_chans, alpha=0.5,",
"''' from spectral_cube import SpectralCube import numpy as np import astropy.units as u",
"[] for low, high in zip(low_pts, high_pts): sc_f, sc_e = \\ find_scale_factor(low, high,",
"flat_dists = np.where(dist >= nsig_cut * sigma) weight_arr = np.zeros_like(mask, dtype=float) weight_arr[gauss_dists] =",
"individual channel MSs used in # imaging. It's not even a half-channel offset",
"30, nsig_cut=5) gbt_path = os.path.join(data_path, \"GBT\") # gbt_cube = SpectralCube.read(os.path.join(gbt_path, \"17B-162_items/m33_gbt_vlsr_highres_Tmb_17B162_02kms.fits\")) gbt_cube =",
"# NOTE: there is an offset of ~0.4 km/s between the cubes #",
"int}$ / I$_{\\rm SD}$\") plt.tight_layout() plt.savefig(allfigs_path(f\"Imaging/ratio_hist_17B_vla_gbt_9.8arcmin_chan_{chan_range.start}_{chan_range.stop}_v3_w_weights.png\")) plt.savefig(allfigs_path(f\"Imaging/ratio_hist_17B_vla_gbt_9.8arcmin_chan_{chan_range.start}_{chan_range.stop}_v3_w_weights.pdf\")) print(\"Factor: {0}+/-{1}\".format(sc_factor_chrange, sc_err_chrange)) # Factor: 1.105133+/-0.00463",
"sc_factor_chans.append(sc_f) sc_err_chans.append(sc_e) sc_factor_chans_linfit = [] sc_err_chans_linfit = [] for low, high in zip(low_pts,",
"GBT data. # The tests here were for consistency and that's what we",
"= find_scale_factor(np.hstack(low_pts), np.hstack(high_pts), method='distrib', verbose=True) plt.grid(True) plt.xlabel(r\"ln I$_{\\rm int}$ / I$_{\\rm SD}$\") plt.tight_layout()",
"160) onecolumn_figure() sc_factor_chrange, sc_err_chrange = \\ find_scale_factor(np.hstack(low_pts[chan_range]), np.hstack(high_pts[chan_range]), method='distrib', verbose=True) plt.grid(True) plt.xlabel(r\"ln I$_{\\rm",
"cut-off (compared to the larger 14B data). # So, despite the != 1",
"coming # from since the freq axis used in `gbt_regrid.py` matches # the",
"I have no idea where this shift is coming # from since the",
"gbt_cube = SpectralCube.read(os.path.join(gbt_path, \"17B-162_items/m33_gbt_vlsr_highres_Tmb_17B162_02kms.fits\")) gbt_cube = SpectralCube.read(os.path.join(gbt_path, \"17B-162_items/m33_gbt_vlsr_highres_Tmb_17B162_1kms.fits\")) beam_fwhm = lambda diam: ((1.18",
"channel MSs used in # imaging. It's not even a half-channel offset like",
"with a Gaussian kernel, rather than a jinc function gbt_eff_beam = beam_fwhm(87.5 *",
"sigma**2)) weight_arr[flat_dists] = 1. return weight_arr weight = taper_weights(np.isfinite(pb_plane), 30, nsig_cut=5) gbt_path =",
"the systemic velocity, where most of the HI # structure falls within the",
"= np.where(dist >= nsig_cut * sigma) weight_arr = np.zeros_like(mask, dtype=float) weight_arr[gauss_dists] = \\",
">= nsig_cut * sigma) weight_arr = np.zeros_like(mask, dtype=float) weight_arr[gauss_dists] = \\ np.exp(- (dist[gauss_dists]",
"the 1 km/s cube. Higher S/N # vla_cube = SpectralCube.read(seventeenB_HI_data_02kms_path(\"M33_14B_17B_HI_contsub_width_02kms.image.pbcor.fits\")) vla_cube = SpectralCube.read(seventeenB_HI_data_1kms_path(\"M33_14B_17B_HI_contsub_width_1kms.image.pbcor.fits\"))",
"onecolumn_figure() sc_factor_chrange, sc_err_chrange = \\ find_scale_factor(np.hstack(low_pts[chan_range]), np.hstack(high_pts[chan_range]), method='distrib', verbose=True) plt.grid(True) plt.xlabel(r\"ln I$_{\\rm int}$",
"a jinc function gbt_eff_beam = beam_fwhm(87.5 * u.m) # The shortest baseline in",
"in the individual channel MSs used in # imaging. It's not even a",
"factor, no factor will be applied to the SD data. # Besides, the",
"# The >1 factor is due to some emission in the GBT data",
"GBT data being cut-off by the # PB limit of the VLA mosaic.",
"# pb_cube = SpectralCube.read(seventeenB_HI_data_02kms_path(\"M33_14B_17B_HI_contsub_width_02kms.pb.fits\")) pb_cube = SpectralCube.read(seventeenB_HI_data_1kms_path(\"M33_14B_17B_HI_contsub_width_1kms.pb.fits\")) # PB minimally changes over the",
"# due to lack of overlap in the GBT fields centered at M33.",
"channel edge... spec_check_kwargs={'rtol': 0.4}) onecolumn_figure() sc_factor, sc_err = find_scale_factor(np.hstack(low_pts), np.hstack(high_pts), method='distrib', verbose=True) plt.grid(True)",
"- sc_err_chans_linfit[:, 0], sc_err_chans_linfit[:, 1] - sc_factor_chans_linfit], alpha=0.5, label='Linear fit') # plt.plot(chans, slope_lowess_85)",
"sc_factor_chans_linfit = [] sc_err_chans_linfit = [] for low, high in zip(low_pts, high_pts): sc_f,",
"frequency in the individual channel MSs used in # imaging. It's not even",
"plotting_styles import onecolumn_figure # Compare with the 1 km/s cube. Higher S/N #",
"plt import os import scipy.ndimage as nd from uvcombine.scale_factor import find_scale_factor from cube_analysis.feather_cubes",
"cubes # The big GBT beam means this really doesn't matter (I #",
"tapered weighting function to ignore emission outside # of the VLA mosaic def",
"(I # manually checked). The difference is 0.36 times the # channel size.",
"HI gets cut-off (compared to the larger 14B data). # So, despite the",
"define a tapered weighting function to ignore emission outside # of the VLA",
"(seventeenB_HI_data_02kms_path, seventeenB_HI_data_1kms_path, data_path, allfigs_path) from constants import hi_freq from plotting_styles import onecolumn_figure #",
"of overlap in the GBT fields centered at M33. So the data were",
"label='Distrib Fit') plt.errorbar(chans, sc_factor_chans_linfit, yerr=[sc_factor_chans_linfit - sc_err_chans_linfit[:, 0], sc_err_chans_linfit[:, 1] - sc_factor_chans_linfit], alpha=0.5,",
"plt.axhline(1, linestyle='--') plt.legend(frameon=True) plt.ylabel(r\"Scale Factor\") plt.xlabel(\"Channels\") plt.grid(True) plt.tight_layout() plt.savefig(allfigs_path(\"Imaging/ratio_hist_perchan_17B_vla_gbt_9.8arcmin_v3_w_weights.png\")) plt.savefig(allfigs_path(\"Imaging/ratio_hist_perchan_17B_vla_gbt_9.8arcmin_v3_w_weights.pdf\")) plt.close() # Now",
"* hi_freq.to(u.cm, u.spectral())) / diam.to(u.cm)) * u.rad # Already determined from the 14B",
"The shortest baseline in the 14B-088 data is ~44 m. las = (hi_freq.to(u.cm,",
"u.dimensionless_angles()) radii, ratios, high_pts, low_pts, chan_out = \\ feather_compare_cube(vla_cube, gbt_cube, las, num_cores=1, lowresfwhm=gbt_eff_beam,",
"plt.xlabel(r\"ln I$_{\\rm int}$ / I$_{\\rm SD}$\") plt.tight_layout() plt.savefig(allfigs_path(f\"Imaging/ratio_hist_17B_vla_gbt_9.8arcmin_chan_{chan_range.start}_{chan_range.stop}_v3_w_weights.png\")) plt.savefig(allfigs_path(f\"Imaging/ratio_hist_17B_vla_gbt_9.8arcmin_chan_{chan_range.start}_{chan_range.stop}_v3_w_weights.pdf\")) print(\"Factor: {0}+/-{1}\".format(sc_factor_chrange, sc_err_chrange)) #",
"plt.xlabel(r\"ln I$_{\\rm int}$ / I$_{\\rm SD}$\") plt.tight_layout() plt.savefig(allfigs_path(\"Imaging/ratio_hist_17B_vla_gbt_9.8arcmin_v3_w_weights.png\")) plt.savefig(allfigs_path(\"Imaging/ratio_hist_17B_vla_gbt_9.8arcmin_v3_w_weights.pdf\")) print(\"Factor: {0}+/-{1}\".format(sc_factor, sc_err)) #",
"gauss_dists = np.where(np.logical_and(dist < nsig_cut * sigma, dist > 0.)) flat_dists = np.where(dist",
"sc_factor_chans = [] sc_err_chans = [] for low, high in zip(low_pts, high_pts): sc_f,",
"I$_{\\rm int}$ / I$_{\\rm SD}$\") plt.tight_layout() plt.savefig(allfigs_path(\"Imaging/ratio_hist_17B_vla_gbt_9.8arcmin_v3_w_weights.png\")) plt.savefig(allfigs_path(\"Imaging/ratio_hist_17B_vla_gbt_9.8arcmin_v3_w_weights.pdf\")) print(\"Factor: {0}+/-{1}\".format(sc_factor, sc_err)) # Factor:",
"bright HI gets cut-off (compared to the larger 14B data). # So, despite",
"limit of the VLA mosaic. The factor increases far from the systemic #",
"the != 1 factor, no factor will be applied to the SD data.",
"mosaic PB chan_range = slice(80, 160) onecolumn_figure() sc_factor_chrange, sc_err_chrange = \\ find_scale_factor(np.hstack(low_pts[chan_range]), np.hstack(high_pts[chan_range]),",
"np.hstack(high_pts[chan_range]), method='distrib', verbose=True) plt.grid(True) plt.xlabel(r\"ln I$_{\\rm int}$ / I$_{\\rm SD}$\") plt.tight_layout() plt.savefig(allfigs_path(f\"Imaging/ratio_hist_17B_vla_gbt_9.8arcmin_chan_{chan_range.start}_{chan_range.stop}_v3_w_weights.png\")) plt.savefig(allfigs_path(f\"Imaging/ratio_hist_17B_vla_gbt_9.8arcmin_chan_{chan_range.start}_{chan_range.stop}_v3_w_weights.pdf\"))",
"offset like I # would expect if the MS frequency was the channel",
"''' Compare the data where they overlap in the uv plane. No offset",
"to define a tapered weighting function to ignore emission outside # of the",
"they overlap in the uv plane. No offset correction is needed. ''' from"
] |
[
"bytearray(original_shellcode): xor=byt^encoder_byte xor=\"%02x\" %xor xor1=\"\\\\x\" + xor xor2=\"0x\" + xor +\",\" encoded_shellcode_format1.append(xor1) encoded_shellcode_format2.append(xor2)",
"byte\" encoded_shellcode_format1=[] encoded_shellcode_format2=[] for byt in bytearray(original_shellcode): xor=byt^encoder_byte xor=\"%02x\" %xor xor1=\"\\\\x\" + xor",
"+ xor xor2=\"0x\" + xor +\",\" encoded_shellcode_format1.append(xor1) encoded_shellcode_format2.append(xor2) print(\"Format 1:\\n\") print''.join(encoded_shellcode_format1) print(\"\\n\\n\\n\") print(\"Format",
"+\",\" encoded_shellcode_format1.append(xor1) encoded_shellcode_format2.append(xor2) print(\"Format 1:\\n\") print''.join(encoded_shellcode_format1) print(\"\\n\\n\\n\") print(\"Format 2:\\n\") print''.join(encoded_shellcode_format2) print(\"\\n\") print(\"Length:\" +str(len(bytearray(original_shellcode))))",
"xor=\"%02x\" %xor xor1=\"\\\\x\" + xor xor2=\"0x\" + xor +\",\" encoded_shellcode_format1.append(xor1) encoded_shellcode_format2.append(xor2) print(\"Format 1:\\n\")",
"xor2=\"0x\" + xor +\",\" encoded_shellcode_format1.append(xor1) encoded_shellcode_format2.append(xor2) print(\"Format 1:\\n\") print''.join(encoded_shellcode_format1) print(\"\\n\\n\\n\") print(\"Format 2:\\n\") print''.join(encoded_shellcode_format2)",
"xor=byt^encoder_byte xor=\"%02x\" %xor xor1=\"\\\\x\" + xor xor2=\"0x\" + xor +\",\" encoded_shellcode_format1.append(xor1) encoded_shellcode_format2.append(xor2) print(\"Format",
"encoded_shellcode_format1=[] encoded_shellcode_format2=[] for byt in bytearray(original_shellcode): xor=byt^encoder_byte xor=\"%02x\" %xor xor1=\"\\\\x\" + xor xor2=\"0x\"",
"encoder_byte=\"Enter the encoder byte\" encoded_shellcode_format1=[] encoded_shellcode_format2=[] for byt in bytearray(original_shellcode): xor=byt^encoder_byte xor=\"%02x\" %xor",
"in bytearray(original_shellcode): xor=byt^encoder_byte xor=\"%02x\" %xor xor1=\"\\\\x\" + xor xor2=\"0x\" + xor +\",\" encoded_shellcode_format1.append(xor1)",
"encoded_shellcode_format2=[] for byt in bytearray(original_shellcode): xor=byt^encoder_byte xor=\"%02x\" %xor xor1=\"\\\\x\" + xor xor2=\"0x\" +",
"#! /bin/python original_shellcode=(\"Enter the shellcode\") encoder_byte=\"Enter the encoder byte\" encoded_shellcode_format1=[] encoded_shellcode_format2=[] for byt",
"the encoder byte\" encoded_shellcode_format1=[] encoded_shellcode_format2=[] for byt in bytearray(original_shellcode): xor=byt^encoder_byte xor=\"%02x\" %xor xor1=\"\\\\x\"",
"/bin/python original_shellcode=(\"Enter the shellcode\") encoder_byte=\"Enter the encoder byte\" encoded_shellcode_format1=[] encoded_shellcode_format2=[] for byt in",
"+ xor +\",\" encoded_shellcode_format1.append(xor1) encoded_shellcode_format2.append(xor2) print(\"Format 1:\\n\") print''.join(encoded_shellcode_format1) print(\"\\n\\n\\n\") print(\"Format 2:\\n\") print''.join(encoded_shellcode_format2) print(\"\\n\")",
"shellcode\") encoder_byte=\"Enter the encoder byte\" encoded_shellcode_format1=[] encoded_shellcode_format2=[] for byt in bytearray(original_shellcode): xor=byt^encoder_byte xor=\"%02x\"",
"encoder byte\" encoded_shellcode_format1=[] encoded_shellcode_format2=[] for byt in bytearray(original_shellcode): xor=byt^encoder_byte xor=\"%02x\" %xor xor1=\"\\\\x\" +",
"xor xor2=\"0x\" + xor +\",\" encoded_shellcode_format1.append(xor1) encoded_shellcode_format2.append(xor2) print(\"Format 1:\\n\") print''.join(encoded_shellcode_format1) print(\"\\n\\n\\n\") print(\"Format 2:\\n\")",
"for byt in bytearray(original_shellcode): xor=byt^encoder_byte xor=\"%02x\" %xor xor1=\"\\\\x\" + xor xor2=\"0x\" + xor",
"the shellcode\") encoder_byte=\"Enter the encoder byte\" encoded_shellcode_format1=[] encoded_shellcode_format2=[] for byt in bytearray(original_shellcode): xor=byt^encoder_byte",
"<filename>Shellcodes/Encoder-Scripts/xor_encoder.py #! /bin/python original_shellcode=(\"Enter the shellcode\") encoder_byte=\"Enter the encoder byte\" encoded_shellcode_format1=[] encoded_shellcode_format2=[] for",
"xor1=\"\\\\x\" + xor xor2=\"0x\" + xor +\",\" encoded_shellcode_format1.append(xor1) encoded_shellcode_format2.append(xor2) print(\"Format 1:\\n\") print''.join(encoded_shellcode_format1) print(\"\\n\\n\\n\")",
"%xor xor1=\"\\\\x\" + xor xor2=\"0x\" + xor +\",\" encoded_shellcode_format1.append(xor1) encoded_shellcode_format2.append(xor2) print(\"Format 1:\\n\") print''.join(encoded_shellcode_format1)",
"xor +\",\" encoded_shellcode_format1.append(xor1) encoded_shellcode_format2.append(xor2) print(\"Format 1:\\n\") print''.join(encoded_shellcode_format1) print(\"\\n\\n\\n\") print(\"Format 2:\\n\") print''.join(encoded_shellcode_format2) print(\"\\n\") print(\"Length:\"",
"original_shellcode=(\"Enter the shellcode\") encoder_byte=\"Enter the encoder byte\" encoded_shellcode_format1=[] encoded_shellcode_format2=[] for byt in bytearray(original_shellcode):",
"byt in bytearray(original_shellcode): xor=byt^encoder_byte xor=\"%02x\" %xor xor1=\"\\\\x\" + xor xor2=\"0x\" + xor +\",\""
] |
[
"def __init__(self): self.a=self.aa() def aa(self): return 'aaa' class B(A): def __init__(self): super().__init__() def",
"from tqdm import tqdm from random import randint class A(object): def __init__(self): self.a=self.aa()",
"self.a=self.aa() def aa(self): return 'aaa' class B(A): def __init__(self): super().__init__() def aa(self): return",
"from random import randint class A(object): def __init__(self): self.a=self.aa() def aa(self): return 'aaa'",
"tqdm from random import randint class A(object): def __init__(self): self.a=self.aa() def aa(self): return",
"<filename>a.py from tqdm import tqdm from random import randint class A(object): def __init__(self):",
"class A(object): def __init__(self): self.a=self.aa() def aa(self): return 'aaa' class B(A): def __init__(self):",
"tqdm import tqdm from random import randint class A(object): def __init__(self): self.a=self.aa() def",
"A(object): def __init__(self): self.a=self.aa() def aa(self): return 'aaa' class B(A): def __init__(self): super().__init__()",
"randint class A(object): def __init__(self): self.a=self.aa() def aa(self): return 'aaa' class B(A): def",
"return 'aaa' class B(A): def __init__(self): super().__init__() def aa(self): return 'aaaaaa' a=A() print(a.a)",
"__init__(self): self.a=self.aa() def aa(self): return 'aaa' class B(A): def __init__(self): super().__init__() def aa(self):",
"aa(self): return 'aaa' class B(A): def __init__(self): super().__init__() def aa(self): return 'aaaaaa' a=A()",
"import randint class A(object): def __init__(self): self.a=self.aa() def aa(self): return 'aaa' class B(A):",
"random import randint class A(object): def __init__(self): self.a=self.aa() def aa(self): return 'aaa' class",
"import tqdm from random import randint class A(object): def __init__(self): self.a=self.aa() def aa(self):",
"def aa(self): return 'aaa' class B(A): def __init__(self): super().__init__() def aa(self): return 'aaaaaa'"
] |
[
"null=True, validators=[django.core.validators.MinValueValidator(-1000000000), django.core.validators.MaxValueValidator(1000000000)], verbose_name='Problem 2 response'), ), migrations.AlterField( model_name='examattempt', name='guess3', field=models.IntegerField(blank=True, null=True, validators=[django.core.validators.MinValueValidator(-1000000000),",
"preserve_default=False, ), migrations.AlterField( model_name='practiceexam', name='answer2', field=models.CharField(default='', max_length=64, validators=[django.core.validators.RegexValidator(re.compile('^\\\\d+(?:,\\\\d+)*\\\\Z'), code='invalid', message='Enter only digits separated",
"field=models.IntegerField(blank=True, null=True, validators=[django.core.validators.MinValueValidator(-1000000000), django.core.validators.MaxValueValidator(1000000000)], verbose_name='Problem 4 response'), ), migrations.AlterField( model_name='examattempt', name='guess5', field=models.IntegerField(blank=True, null=True,",
"name='answer2', field=models.CharField(default='', max_length=64, validators=[django.core.validators.RegexValidator(re.compile('^\\\\d+(?:,\\\\d+)*\\\\Z'), code='invalid', message='Enter only digits separated by commas.')]), preserve_default=False, ),",
"dependencies = [ ('exams', '0019_auto_20210805_1334'), ] operations = [ migrations.AlterField( model_name='examattempt', name='guess1', field=models.IntegerField(blank=True,",
"field=models.IntegerField(blank=True, null=True, validators=[django.core.validators.MinValueValidator(-1000000000), django.core.validators.MaxValueValidator(1000000000)], verbose_name='Problem 5 response'), ), migrations.AlterField( model_name='practiceexam', name='answer1', field=models.CharField(default='', max_length=64,",
"model_name='practiceexam', name='answer1', field=models.CharField(default='', max_length=64, validators=[django.core.validators.RegexValidator(re.compile('^\\\\d+(?:,\\\\d+)*\\\\Z'), code='invalid', message='Enter only digits separated by commas.')]), preserve_default=False,",
"message='Enter only digits separated by commas.')]), preserve_default=False, ), migrations.AlterField( model_name='practiceexam', name='answer3', field=models.CharField(default='', max_length=64,",
"name='answer5', field=models.CharField(default='', max_length=64, validators=[django.core.validators.RegexValidator(re.compile('^\\\\d+(?:,\\\\d+)*\\\\Z'), code='invalid', message='Enter only digits separated by commas.')]), preserve_default=False, ),",
"model_name='examattempt', name='guess1', field=models.IntegerField(blank=True, null=True, validators=[django.core.validators.MinValueValidator(-1000000000), django.core.validators.MaxValueValidator(1000000000)], verbose_name='Problem 1 response'), ), migrations.AlterField( model_name='examattempt', name='guess2',",
"), migrations.AlterField( model_name='practiceexam', name='answer1', field=models.CharField(default='', max_length=64, validators=[django.core.validators.RegexValidator(re.compile('^\\\\d+(?:,\\\\d+)*\\\\Z'), code='invalid', message='Enter only digits separated by",
"migrations.AlterField( model_name='practiceexam', name='answer4', field=models.CharField(default='', max_length=64, validators=[django.core.validators.RegexValidator(re.compile('^\\\\d+(?:,\\\\d+)*\\\\Z'), code='invalid', message='Enter only digits separated by commas.')]),",
"[ migrations.AlterField( model_name='examattempt', name='guess1', field=models.IntegerField(blank=True, null=True, validators=[django.core.validators.MinValueValidator(-1000000000), django.core.validators.MaxValueValidator(1000000000)], verbose_name='Problem 1 response'), ), migrations.AlterField(",
"null=True, validators=[django.core.validators.MinValueValidator(-1000000000), django.core.validators.MaxValueValidator(1000000000)], verbose_name='Problem 3 response'), ), migrations.AlterField( model_name='examattempt', name='guess4', field=models.IntegerField(blank=True, null=True, validators=[django.core.validators.MinValueValidator(-1000000000),",
"only digits separated by commas.')]), preserve_default=False, ), migrations.AlterField( model_name='practiceexam', name='answer5', field=models.CharField(default='', max_length=64, validators=[django.core.validators.RegexValidator(re.compile('^\\\\d+(?:,\\\\d+)*\\\\Z'),",
"('exams', '0019_auto_20210805_1334'), ] operations = [ migrations.AlterField( model_name='examattempt', name='guess1', field=models.IntegerField(blank=True, null=True, validators=[django.core.validators.MinValueValidator(-1000000000), django.core.validators.MaxValueValidator(1000000000)],",
"code='invalid', message='Enter only digits separated by commas.')]), preserve_default=False, ), migrations.AlterField( model_name='practiceexam', name='answer4', field=models.CharField(default='',",
"migrations.AlterField( model_name='examattempt', name='guess2', field=models.IntegerField(blank=True, null=True, validators=[django.core.validators.MinValueValidator(-1000000000), django.core.validators.MaxValueValidator(1000000000)], verbose_name='Problem 2 response'), ), migrations.AlterField( model_name='examattempt',",
"django.core.validators.MaxValueValidator(1000000000)], verbose_name='Problem 5 response'), ), migrations.AlterField( model_name='practiceexam', name='answer1', field=models.CharField(default='', max_length=64, validators=[django.core.validators.RegexValidator(re.compile('^\\\\d+(?:,\\\\d+)*\\\\Z'), code='invalid', message='Enter",
"validators=[django.core.validators.RegexValidator(re.compile('^\\\\d+(?:,\\\\d+)*\\\\Z'), code='invalid', message='Enter only digits separated by commas.')]), preserve_default=False, ), migrations.AlterField( model_name='practiceexam', name='answer4',",
"by Django 3.2.5 on 2021-08-05 18:01 import django.core.validators from django.db import migrations, models",
"validators=[django.core.validators.MinValueValidator(-1000000000), django.core.validators.MaxValueValidator(1000000000)], verbose_name='Problem 2 response'), ), migrations.AlterField( model_name='examattempt', name='guess3', field=models.IntegerField(blank=True, null=True, validators=[django.core.validators.MinValueValidator(-1000000000), django.core.validators.MaxValueValidator(1000000000)],",
"code='invalid', message='Enter only digits separated by commas.')]), preserve_default=False, ), migrations.AlterField( model_name='practiceexam', name='answer5', field=models.CharField(default='',",
"max_length=64, validators=[django.core.validators.RegexValidator(re.compile('^\\\\d+(?:,\\\\d+)*\\\\Z'), code='invalid', message='Enter only digits separated by commas.')]), preserve_default=False, ), migrations.AlterField( model_name='practiceexam',",
"name='answer3', field=models.CharField(default='', max_length=64, validators=[django.core.validators.RegexValidator(re.compile('^\\\\d+(?:,\\\\d+)*\\\\Z'), code='invalid', message='Enter only digits separated by commas.')]), preserve_default=False, ),",
"model_name='examattempt', name='guess5', field=models.IntegerField(blank=True, null=True, validators=[django.core.validators.MinValueValidator(-1000000000), django.core.validators.MaxValueValidator(1000000000)], verbose_name='Problem 5 response'), ), migrations.AlterField( model_name='practiceexam', name='answer1',",
"verbose_name='Problem 2 response'), ), migrations.AlterField( model_name='examattempt', name='guess3', field=models.IntegerField(blank=True, null=True, validators=[django.core.validators.MinValueValidator(-1000000000), django.core.validators.MaxValueValidator(1000000000)], verbose_name='Problem 3",
"2021-08-05 18:01 import django.core.validators from django.db import migrations, models import re class Migration(migrations.Migration):",
"migrations.AlterField( model_name='examattempt', name='guess4', field=models.IntegerField(blank=True, null=True, validators=[django.core.validators.MinValueValidator(-1000000000), django.core.validators.MaxValueValidator(1000000000)], verbose_name='Problem 4 response'), ), migrations.AlterField( model_name='examattempt',",
"preserve_default=False, ), migrations.AlterField( model_name='practiceexam', name='answer4', field=models.CharField(default='', max_length=64, validators=[django.core.validators.RegexValidator(re.compile('^\\\\d+(?:,\\\\d+)*\\\\Z'), code='invalid', message='Enter only digits separated",
"validators=[django.core.validators.RegexValidator(re.compile('^\\\\d+(?:,\\\\d+)*\\\\Z'), code='invalid', message='Enter only digits separated by commas.')]), preserve_default=False, ), migrations.AlterField( model_name='practiceexam', name='answer5',",
"2 response'), ), migrations.AlterField( model_name='examattempt', name='guess3', field=models.IntegerField(blank=True, null=True, validators=[django.core.validators.MinValueValidator(-1000000000), django.core.validators.MaxValueValidator(1000000000)], verbose_name='Problem 3 response'),",
"null=True, validators=[django.core.validators.MinValueValidator(-1000000000), django.core.validators.MaxValueValidator(1000000000)], verbose_name='Problem 4 response'), ), migrations.AlterField( model_name='examattempt', name='guess5', field=models.IntegerField(blank=True, null=True, validators=[django.core.validators.MinValueValidator(-1000000000),",
"Django 3.2.5 on 2021-08-05 18:01 import django.core.validators from django.db import migrations, models import",
"field=models.CharField(default='', max_length=64, validators=[django.core.validators.RegexValidator(re.compile('^\\\\d+(?:,\\\\d+)*\\\\Z'), code='invalid', message='Enter only digits separated by commas.')]), preserve_default=False, ), migrations.AlterField(",
"field=models.IntegerField(blank=True, null=True, validators=[django.core.validators.MinValueValidator(-1000000000), django.core.validators.MaxValueValidator(1000000000)], verbose_name='Problem 2 response'), ), migrations.AlterField( model_name='examattempt', name='guess3', field=models.IntegerField(blank=True, null=True,",
"verbose_name='Problem 3 response'), ), migrations.AlterField( model_name='examattempt', name='guess4', field=models.IntegerField(blank=True, null=True, validators=[django.core.validators.MinValueValidator(-1000000000), django.core.validators.MaxValueValidator(1000000000)], verbose_name='Problem 4",
"preserve_default=False, ), migrations.AlterField( model_name='practiceexam', name='answer3', field=models.CharField(default='', max_length=64, validators=[django.core.validators.RegexValidator(re.compile('^\\\\d+(?:,\\\\d+)*\\\\Z'), code='invalid', message='Enter only digits separated",
"model_name='practiceexam', name='answer5', field=models.CharField(default='', max_length=64, validators=[django.core.validators.RegexValidator(re.compile('^\\\\d+(?:,\\\\d+)*\\\\Z'), code='invalid', message='Enter only digits separated by commas.')]), preserve_default=False,",
"django.db import migrations, models import re class Migration(migrations.Migration): dependencies = [ ('exams', '0019_auto_20210805_1334'),",
"commas.')]), preserve_default=False, ), migrations.AlterField( model_name='practiceexam', name='answer4', field=models.CharField(default='', max_length=64, validators=[django.core.validators.RegexValidator(re.compile('^\\\\d+(?:,\\\\d+)*\\\\Z'), code='invalid', message='Enter only digits",
"), migrations.AlterField( model_name='practiceexam', name='answer5', field=models.CharField(default='', max_length=64, validators=[django.core.validators.RegexValidator(re.compile('^\\\\d+(?:,\\\\d+)*\\\\Z'), code='invalid', message='Enter only digits separated by",
"name='guess3', field=models.IntegerField(blank=True, null=True, validators=[django.core.validators.MinValueValidator(-1000000000), django.core.validators.MaxValueValidator(1000000000)], verbose_name='Problem 3 response'), ), migrations.AlterField( model_name='examattempt', name='guess4', field=models.IntegerField(blank=True,",
"model_name='examattempt', name='guess2', field=models.IntegerField(blank=True, null=True, validators=[django.core.validators.MinValueValidator(-1000000000), django.core.validators.MaxValueValidator(1000000000)], verbose_name='Problem 2 response'), ), migrations.AlterField( model_name='examattempt', name='guess3',",
"model_name='practiceexam', name='answer2', field=models.CharField(default='', max_length=64, validators=[django.core.validators.RegexValidator(re.compile('^\\\\d+(?:,\\\\d+)*\\\\Z'), code='invalid', message='Enter only digits separated by commas.')]), preserve_default=False,",
"null=True, validators=[django.core.validators.MinValueValidator(-1000000000), django.core.validators.MaxValueValidator(1000000000)], verbose_name='Problem 5 response'), ), migrations.AlterField( model_name='practiceexam', name='answer1', field=models.CharField(default='', max_length=64, validators=[django.core.validators.RegexValidator(re.compile('^\\\\d+(?:,\\\\d+)*\\\\Z'),",
"class Migration(migrations.Migration): dependencies = [ ('exams', '0019_auto_20210805_1334'), ] operations = [ migrations.AlterField( model_name='examattempt',",
"separated by commas.')]), preserve_default=False, ), migrations.AlterField( model_name='practiceexam', name='answer4', field=models.CharField(default='', max_length=64, validators=[django.core.validators.RegexValidator(re.compile('^\\\\d+(?:,\\\\d+)*\\\\Z'), code='invalid', message='Enter",
"response'), ), migrations.AlterField( model_name='examattempt', name='guess4', field=models.IntegerField(blank=True, null=True, validators=[django.core.validators.MinValueValidator(-1000000000), django.core.validators.MaxValueValidator(1000000000)], verbose_name='Problem 4 response'), ),",
"migrations.AlterField( model_name='practiceexam', name='answer5', field=models.CharField(default='', max_length=64, validators=[django.core.validators.RegexValidator(re.compile('^\\\\d+(?:,\\\\d+)*\\\\Z'), code='invalid', message='Enter only digits separated by commas.')]),",
"import migrations, models import re class Migration(migrations.Migration): dependencies = [ ('exams', '0019_auto_20210805_1334'), ]",
"migrations.AlterField( model_name='examattempt', name='guess1', field=models.IntegerField(blank=True, null=True, validators=[django.core.validators.MinValueValidator(-1000000000), django.core.validators.MaxValueValidator(1000000000)], verbose_name='Problem 1 response'), ), migrations.AlterField( model_name='examattempt',",
"only digits separated by commas.')]), preserve_default=False, ), migrations.AlterField( model_name='practiceexam', name='answer3', field=models.CharField(default='', max_length=64, validators=[django.core.validators.RegexValidator(re.compile('^\\\\d+(?:,\\\\d+)*\\\\Z'),",
"message='Enter only digits separated by commas.')]), preserve_default=False, ), migrations.AlterField( model_name='practiceexam', name='answer5', field=models.CharField(default='', max_length=64,",
"name='guess2', field=models.IntegerField(blank=True, null=True, validators=[django.core.validators.MinValueValidator(-1000000000), django.core.validators.MaxValueValidator(1000000000)], verbose_name='Problem 2 response'), ), migrations.AlterField( model_name='examattempt', name='guess3', field=models.IntegerField(blank=True,",
"migrations.AlterField( model_name='practiceexam', name='answer2', field=models.CharField(default='', max_length=64, validators=[django.core.validators.RegexValidator(re.compile('^\\\\d+(?:,\\\\d+)*\\\\Z'), code='invalid', message='Enter only digits separated by commas.')]),",
"18:01 import django.core.validators from django.db import migrations, models import re class Migration(migrations.Migration): dependencies",
"= [ ('exams', '0019_auto_20210805_1334'), ] operations = [ migrations.AlterField( model_name='examattempt', name='guess1', field=models.IntegerField(blank=True, null=True,",
"name='guess1', field=models.IntegerField(blank=True, null=True, validators=[django.core.validators.MinValueValidator(-1000000000), django.core.validators.MaxValueValidator(1000000000)], verbose_name='Problem 1 response'), ), migrations.AlterField( model_name='examattempt', name='guess2', field=models.IntegerField(blank=True,",
"commas.')]), preserve_default=False, ), migrations.AlterField( model_name='practiceexam', name='answer3', field=models.CharField(default='', max_length=64, validators=[django.core.validators.RegexValidator(re.compile('^\\\\d+(?:,\\\\d+)*\\\\Z'), code='invalid', message='Enter only digits",
"[ ('exams', '0019_auto_20210805_1334'), ] operations = [ migrations.AlterField( model_name='examattempt', name='guess1', field=models.IntegerField(blank=True, null=True, validators=[django.core.validators.MinValueValidator(-1000000000),",
"models import re class Migration(migrations.Migration): dependencies = [ ('exams', '0019_auto_20210805_1334'), ] operations =",
"operations = [ migrations.AlterField( model_name='examattempt', name='guess1', field=models.IntegerField(blank=True, null=True, validators=[django.core.validators.MinValueValidator(-1000000000), django.core.validators.MaxValueValidator(1000000000)], verbose_name='Problem 1 response'),",
"), migrations.AlterField( model_name='examattempt', name='guess5', field=models.IntegerField(blank=True, null=True, validators=[django.core.validators.MinValueValidator(-1000000000), django.core.validators.MaxValueValidator(1000000000)], verbose_name='Problem 5 response'), ), migrations.AlterField(",
"] operations = [ migrations.AlterField( model_name='examattempt', name='guess1', field=models.IntegerField(blank=True, null=True, validators=[django.core.validators.MinValueValidator(-1000000000), django.core.validators.MaxValueValidator(1000000000)], verbose_name='Problem 1",
"model_name='practiceexam', name='answer4', field=models.CharField(default='', max_length=64, validators=[django.core.validators.RegexValidator(re.compile('^\\\\d+(?:,\\\\d+)*\\\\Z'), code='invalid', message='Enter only digits separated by commas.')]), preserve_default=False,",
"migrations.AlterField( model_name='practiceexam', name='answer3', field=models.CharField(default='', max_length=64, validators=[django.core.validators.RegexValidator(re.compile('^\\\\d+(?:,\\\\d+)*\\\\Z'), code='invalid', message='Enter only digits separated by commas.')]),",
"name='answer4', field=models.CharField(default='', max_length=64, validators=[django.core.validators.RegexValidator(re.compile('^\\\\d+(?:,\\\\d+)*\\\\Z'), code='invalid', message='Enter only digits separated by commas.')]), preserve_default=False, ),",
"= [ migrations.AlterField( model_name='examattempt', name='guess1', field=models.IntegerField(blank=True, null=True, validators=[django.core.validators.MinValueValidator(-1000000000), django.core.validators.MaxValueValidator(1000000000)], verbose_name='Problem 1 response'), ),",
"on 2021-08-05 18:01 import django.core.validators from django.db import migrations, models import re class",
"model_name='examattempt', name='guess4', field=models.IntegerField(blank=True, null=True, validators=[django.core.validators.MinValueValidator(-1000000000), django.core.validators.MaxValueValidator(1000000000)], verbose_name='Problem 4 response'), ), migrations.AlterField( model_name='examattempt', name='guess5',",
"# Generated by Django 3.2.5 on 2021-08-05 18:01 import django.core.validators from django.db import",
"response'), ), migrations.AlterField( model_name='examattempt', name='guess3', field=models.IntegerField(blank=True, null=True, validators=[django.core.validators.MinValueValidator(-1000000000), django.core.validators.MaxValueValidator(1000000000)], verbose_name='Problem 3 response'), ),",
"validators=[django.core.validators.MinValueValidator(-1000000000), django.core.validators.MaxValueValidator(1000000000)], verbose_name='Problem 4 response'), ), migrations.AlterField( model_name='examattempt', name='guess5', field=models.IntegerField(blank=True, null=True, validators=[django.core.validators.MinValueValidator(-1000000000), django.core.validators.MaxValueValidator(1000000000)],",
"separated by commas.')]), preserve_default=False, ), migrations.AlterField( model_name='practiceexam', name='answer5', field=models.CharField(default='', max_length=64, validators=[django.core.validators.RegexValidator(re.compile('^\\\\d+(?:,\\\\d+)*\\\\Z'), code='invalid', message='Enter",
"validators=[django.core.validators.RegexValidator(re.compile('^\\\\d+(?:,\\\\d+)*\\\\Z'), code='invalid', message='Enter only digits separated by commas.')]), preserve_default=False, ), migrations.AlterField( model_name='practiceexam', name='answer3',",
"digits separated by commas.')]), preserve_default=False, ), migrations.AlterField( model_name='practiceexam', name='answer3', field=models.CharField(default='', max_length=64, validators=[django.core.validators.RegexValidator(re.compile('^\\\\d+(?:,\\\\d+)*\\\\Z'), code='invalid',",
"commas.')]), preserve_default=False, ), migrations.AlterField( model_name='practiceexam', name='answer2', field=models.CharField(default='', max_length=64, validators=[django.core.validators.RegexValidator(re.compile('^\\\\d+(?:,\\\\d+)*\\\\Z'), code='invalid', message='Enter only digits",
"code='invalid', message='Enter only digits separated by commas.')]), preserve_default=False, ), migrations.AlterField( model_name='practiceexam', name='answer3', field=models.CharField(default='',",
"message='Enter only digits separated by commas.')]), preserve_default=False, ), migrations.AlterField( model_name='practiceexam', name='answer4', field=models.CharField(default='', max_length=64,",
"field=models.IntegerField(blank=True, null=True, validators=[django.core.validators.MinValueValidator(-1000000000), django.core.validators.MaxValueValidator(1000000000)], verbose_name='Problem 1 response'), ), migrations.AlterField( model_name='examattempt', name='guess2', field=models.IntegerField(blank=True, null=True,",
"django.core.validators.MaxValueValidator(1000000000)], verbose_name='Problem 1 response'), ), migrations.AlterField( model_name='examattempt', name='guess2', field=models.IntegerField(blank=True, null=True, validators=[django.core.validators.MinValueValidator(-1000000000), django.core.validators.MaxValueValidator(1000000000)], verbose_name='Problem",
"), migrations.AlterField( model_name='examattempt', name='guess3', field=models.IntegerField(blank=True, null=True, validators=[django.core.validators.MinValueValidator(-1000000000), django.core.validators.MaxValueValidator(1000000000)], verbose_name='Problem 3 response'), ), migrations.AlterField(",
"by commas.')]), preserve_default=False, ), migrations.AlterField( model_name='practiceexam', name='answer4', field=models.CharField(default='', max_length=64, validators=[django.core.validators.RegexValidator(re.compile('^\\\\d+(?:,\\\\d+)*\\\\Z'), code='invalid', message='Enter only",
"name='guess4', field=models.IntegerField(blank=True, null=True, validators=[django.core.validators.MinValueValidator(-1000000000), django.core.validators.MaxValueValidator(1000000000)], verbose_name='Problem 4 response'), ), migrations.AlterField( model_name='examattempt', name='guess5', field=models.IntegerField(blank=True,",
"migrations.AlterField( model_name='examattempt', name='guess5', field=models.IntegerField(blank=True, null=True, validators=[django.core.validators.MinValueValidator(-1000000000), django.core.validators.MaxValueValidator(1000000000)], verbose_name='Problem 5 response'), ), migrations.AlterField( model_name='practiceexam',",
"django.core.validators.MaxValueValidator(1000000000)], verbose_name='Problem 2 response'), ), migrations.AlterField( model_name='examattempt', name='guess3', field=models.IntegerField(blank=True, null=True, validators=[django.core.validators.MinValueValidator(-1000000000), django.core.validators.MaxValueValidator(1000000000)], verbose_name='Problem",
"5 response'), ), migrations.AlterField( model_name='practiceexam', name='answer1', field=models.CharField(default='', max_length=64, validators=[django.core.validators.RegexValidator(re.compile('^\\\\d+(?:,\\\\d+)*\\\\Z'), code='invalid', message='Enter only digits",
"), migrations.AlterField( model_name='examattempt', name='guess2', field=models.IntegerField(blank=True, null=True, validators=[django.core.validators.MinValueValidator(-1000000000), django.core.validators.MaxValueValidator(1000000000)], verbose_name='Problem 2 response'), ), migrations.AlterField(",
"migrations.AlterField( model_name='examattempt', name='guess3', field=models.IntegerField(blank=True, null=True, validators=[django.core.validators.MinValueValidator(-1000000000), django.core.validators.MaxValueValidator(1000000000)], verbose_name='Problem 3 response'), ), migrations.AlterField( model_name='examattempt',",
"django.core.validators.MaxValueValidator(1000000000)], verbose_name='Problem 4 response'), ), migrations.AlterField( model_name='examattempt', name='guess5', field=models.IntegerField(blank=True, null=True, validators=[django.core.validators.MinValueValidator(-1000000000), django.core.validators.MaxValueValidator(1000000000)], verbose_name='Problem",
"Migration(migrations.Migration): dependencies = [ ('exams', '0019_auto_20210805_1334'), ] operations = [ migrations.AlterField( model_name='examattempt', name='guess1',",
"validators=[django.core.validators.RegexValidator(re.compile('^\\\\d+(?:,\\\\d+)*\\\\Z'), code='invalid', message='Enter only digits separated by commas.')]), preserve_default=False, ), migrations.AlterField( model_name='practiceexam', name='answer2',",
"), migrations.AlterField( model_name='practiceexam', name='answer4', field=models.CharField(default='', max_length=64, validators=[django.core.validators.RegexValidator(re.compile('^\\\\d+(?:,\\\\d+)*\\\\Z'), code='invalid', message='Enter only digits separated by",
"migrations.AlterField( model_name='practiceexam', name='answer1', field=models.CharField(default='', max_length=64, validators=[django.core.validators.RegexValidator(re.compile('^\\\\d+(?:,\\\\d+)*\\\\Z'), code='invalid', message='Enter only digits separated by commas.')]),",
"field=models.IntegerField(blank=True, null=True, validators=[django.core.validators.MinValueValidator(-1000000000), django.core.validators.MaxValueValidator(1000000000)], verbose_name='Problem 3 response'), ), migrations.AlterField( model_name='examattempt', name='guess4', field=models.IntegerField(blank=True, null=True,",
"re class Migration(migrations.Migration): dependencies = [ ('exams', '0019_auto_20210805_1334'), ] operations = [ migrations.AlterField(",
"verbose_name='Problem 4 response'), ), migrations.AlterField( model_name='examattempt', name='guess5', field=models.IntegerField(blank=True, null=True, validators=[django.core.validators.MinValueValidator(-1000000000), django.core.validators.MaxValueValidator(1000000000)], verbose_name='Problem 5",
"message='Enter only digits separated by commas.')]), preserve_default=False, ), migrations.AlterField( model_name='practiceexam', name='answer2', field=models.CharField(default='', max_length=64,",
"by commas.')]), preserve_default=False, ), migrations.AlterField( model_name='practiceexam', name='answer5', field=models.CharField(default='', max_length=64, validators=[django.core.validators.RegexValidator(re.compile('^\\\\d+(?:,\\\\d+)*\\\\Z'), code='invalid', message='Enter only",
"field=models.CharField(default='', max_length=64, validators=[django.core.validators.RegexValidator(re.compile('^\\\\d+(?:,\\\\d+)*\\\\Z'), code='invalid', message='Enter only digits separated by commas.')]), preserve_default=False, ), ]",
"verbose_name='Problem 5 response'), ), migrations.AlterField( model_name='practiceexam', name='answer1', field=models.CharField(default='', max_length=64, validators=[django.core.validators.RegexValidator(re.compile('^\\\\d+(?:,\\\\d+)*\\\\Z'), code='invalid', message='Enter only",
"only digits separated by commas.')]), preserve_default=False, ), migrations.AlterField( model_name='practiceexam', name='answer2', field=models.CharField(default='', max_length=64, validators=[django.core.validators.RegexValidator(re.compile('^\\\\d+(?:,\\\\d+)*\\\\Z'),",
"model_name='practiceexam', name='answer3', field=models.CharField(default='', max_length=64, validators=[django.core.validators.RegexValidator(re.compile('^\\\\d+(?:,\\\\d+)*\\\\Z'), code='invalid', message='Enter only digits separated by commas.')]), preserve_default=False,",
"from django.db import migrations, models import re class Migration(migrations.Migration): dependencies = [ ('exams',",
"Generated by Django 3.2.5 on 2021-08-05 18:01 import django.core.validators from django.db import migrations,",
"name='guess5', field=models.IntegerField(blank=True, null=True, validators=[django.core.validators.MinValueValidator(-1000000000), django.core.validators.MaxValueValidator(1000000000)], verbose_name='Problem 5 response'), ), migrations.AlterField( model_name='practiceexam', name='answer1', field=models.CharField(default='',",
"response'), ), migrations.AlterField( model_name='practiceexam', name='answer1', field=models.CharField(default='', max_length=64, validators=[django.core.validators.RegexValidator(re.compile('^\\\\d+(?:,\\\\d+)*\\\\Z'), code='invalid', message='Enter only digits separated",
"), migrations.AlterField( model_name='practiceexam', name='answer3', field=models.CharField(default='', max_length=64, validators=[django.core.validators.RegexValidator(re.compile('^\\\\d+(?:,\\\\d+)*\\\\Z'), code='invalid', message='Enter only digits separated by",
"django.core.validators.MaxValueValidator(1000000000)], verbose_name='Problem 3 response'), ), migrations.AlterField( model_name='examattempt', name='guess4', field=models.IntegerField(blank=True, null=True, validators=[django.core.validators.MinValueValidator(-1000000000), django.core.validators.MaxValueValidator(1000000000)], verbose_name='Problem",
"verbose_name='Problem 1 response'), ), migrations.AlterField( model_name='examattempt', name='guess2', field=models.IntegerField(blank=True, null=True, validators=[django.core.validators.MinValueValidator(-1000000000), django.core.validators.MaxValueValidator(1000000000)], verbose_name='Problem 2",
"), migrations.AlterField( model_name='practiceexam', name='answer2', field=models.CharField(default='', max_length=64, validators=[django.core.validators.RegexValidator(re.compile('^\\\\d+(?:,\\\\d+)*\\\\Z'), code='invalid', message='Enter only digits separated by",
"only digits separated by commas.')]), preserve_default=False, ), migrations.AlterField( model_name='practiceexam', name='answer4', field=models.CharField(default='', max_length=64, validators=[django.core.validators.RegexValidator(re.compile('^\\\\d+(?:,\\\\d+)*\\\\Z'),",
"name='answer1', field=models.CharField(default='', max_length=64, validators=[django.core.validators.RegexValidator(re.compile('^\\\\d+(?:,\\\\d+)*\\\\Z'), code='invalid', message='Enter only digits separated by commas.')]), preserve_default=False, ),",
"3 response'), ), migrations.AlterField( model_name='examattempt', name='guess4', field=models.IntegerField(blank=True, null=True, validators=[django.core.validators.MinValueValidator(-1000000000), django.core.validators.MaxValueValidator(1000000000)], verbose_name='Problem 4 response'),",
"response'), ), migrations.AlterField( model_name='examattempt', name='guess2', field=models.IntegerField(blank=True, null=True, validators=[django.core.validators.MinValueValidator(-1000000000), django.core.validators.MaxValueValidator(1000000000)], verbose_name='Problem 2 response'), ),",
"migrations, models import re class Migration(migrations.Migration): dependencies = [ ('exams', '0019_auto_20210805_1334'), ] operations",
"), migrations.AlterField( model_name='examattempt', name='guess4', field=models.IntegerField(blank=True, null=True, validators=[django.core.validators.MinValueValidator(-1000000000), django.core.validators.MaxValueValidator(1000000000)], verbose_name='Problem 4 response'), ), migrations.AlterField(",
"import django.core.validators from django.db import migrations, models import re class Migration(migrations.Migration): dependencies =",
"null=True, validators=[django.core.validators.MinValueValidator(-1000000000), django.core.validators.MaxValueValidator(1000000000)], verbose_name='Problem 1 response'), ), migrations.AlterField( model_name='examattempt', name='guess2', field=models.IntegerField(blank=True, null=True, validators=[django.core.validators.MinValueValidator(-1000000000),",
"separated by commas.')]), preserve_default=False, ), migrations.AlterField( model_name='practiceexam', name='answer2', field=models.CharField(default='', max_length=64, validators=[django.core.validators.RegexValidator(re.compile('^\\\\d+(?:,\\\\d+)*\\\\Z'), code='invalid', message='Enter",
"by commas.')]), preserve_default=False, ), migrations.AlterField( model_name='practiceexam', name='answer2', field=models.CharField(default='', max_length=64, validators=[django.core.validators.RegexValidator(re.compile('^\\\\d+(?:,\\\\d+)*\\\\Z'), code='invalid', message='Enter only",
"validators=[django.core.validators.MinValueValidator(-1000000000), django.core.validators.MaxValueValidator(1000000000)], verbose_name='Problem 1 response'), ), migrations.AlterField( model_name='examattempt', name='guess2', field=models.IntegerField(blank=True, null=True, validators=[django.core.validators.MinValueValidator(-1000000000), django.core.validators.MaxValueValidator(1000000000)],",
"digits separated by commas.')]), preserve_default=False, ), migrations.AlterField( model_name='practiceexam', name='answer5', field=models.CharField(default='', max_length=64, validators=[django.core.validators.RegexValidator(re.compile('^\\\\d+(?:,\\\\d+)*\\\\Z'), code='invalid',",
"separated by commas.')]), preserve_default=False, ), migrations.AlterField( model_name='practiceexam', name='answer3', field=models.CharField(default='', max_length=64, validators=[django.core.validators.RegexValidator(re.compile('^\\\\d+(?:,\\\\d+)*\\\\Z'), code='invalid', message='Enter",
"django.core.validators from django.db import migrations, models import re class Migration(migrations.Migration): dependencies = [",
"1 response'), ), migrations.AlterField( model_name='examattempt', name='guess2', field=models.IntegerField(blank=True, null=True, validators=[django.core.validators.MinValueValidator(-1000000000), django.core.validators.MaxValueValidator(1000000000)], verbose_name='Problem 2 response'),",
"preserve_default=False, ), migrations.AlterField( model_name='practiceexam', name='answer5', field=models.CharField(default='', max_length=64, validators=[django.core.validators.RegexValidator(re.compile('^\\\\d+(?:,\\\\d+)*\\\\Z'), code='invalid', message='Enter only digits separated",
"validators=[django.core.validators.MinValueValidator(-1000000000), django.core.validators.MaxValueValidator(1000000000)], verbose_name='Problem 3 response'), ), migrations.AlterField( model_name='examattempt', name='guess4', field=models.IntegerField(blank=True, null=True, validators=[django.core.validators.MinValueValidator(-1000000000), django.core.validators.MaxValueValidator(1000000000)],",
"digits separated by commas.')]), preserve_default=False, ), migrations.AlterField( model_name='practiceexam', name='answer2', field=models.CharField(default='', max_length=64, validators=[django.core.validators.RegexValidator(re.compile('^\\\\d+(?:,\\\\d+)*\\\\Z'), code='invalid',",
"validators=[django.core.validators.MinValueValidator(-1000000000), django.core.validators.MaxValueValidator(1000000000)], verbose_name='Problem 5 response'), ), migrations.AlterField( model_name='practiceexam', name='answer1', field=models.CharField(default='', max_length=64, validators=[django.core.validators.RegexValidator(re.compile('^\\\\d+(?:,\\\\d+)*\\\\Z'), code='invalid',",
"digits separated by commas.')]), preserve_default=False, ), migrations.AlterField( model_name='practiceexam', name='answer4', field=models.CharField(default='', max_length=64, validators=[django.core.validators.RegexValidator(re.compile('^\\\\d+(?:,\\\\d+)*\\\\Z'), code='invalid',",
"'0019_auto_20210805_1334'), ] operations = [ migrations.AlterField( model_name='examattempt', name='guess1', field=models.IntegerField(blank=True, null=True, validators=[django.core.validators.MinValueValidator(-1000000000), django.core.validators.MaxValueValidator(1000000000)], verbose_name='Problem",
"3.2.5 on 2021-08-05 18:01 import django.core.validators from django.db import migrations, models import re",
"import re class Migration(migrations.Migration): dependencies = [ ('exams', '0019_auto_20210805_1334'), ] operations = [",
"commas.')]), preserve_default=False, ), migrations.AlterField( model_name='practiceexam', name='answer5', field=models.CharField(default='', max_length=64, validators=[django.core.validators.RegexValidator(re.compile('^\\\\d+(?:,\\\\d+)*\\\\Z'), code='invalid', message='Enter only digits",
"model_name='examattempt', name='guess3', field=models.IntegerField(blank=True, null=True, validators=[django.core.validators.MinValueValidator(-1000000000), django.core.validators.MaxValueValidator(1000000000)], verbose_name='Problem 3 response'), ), migrations.AlterField( model_name='examattempt', name='guess4',",
"response'), ), migrations.AlterField( model_name='examattempt', name='guess5', field=models.IntegerField(blank=True, null=True, validators=[django.core.validators.MinValueValidator(-1000000000), django.core.validators.MaxValueValidator(1000000000)], verbose_name='Problem 5 response'), ),",
"4 response'), ), migrations.AlterField( model_name='examattempt', name='guess5', field=models.IntegerField(blank=True, null=True, validators=[django.core.validators.MinValueValidator(-1000000000), django.core.validators.MaxValueValidator(1000000000)], verbose_name='Problem 5 response'),",
"code='invalid', message='Enter only digits separated by commas.')]), preserve_default=False, ), migrations.AlterField( model_name='practiceexam', name='answer2', field=models.CharField(default='',",
"by commas.')]), preserve_default=False, ), migrations.AlterField( model_name='practiceexam', name='answer3', field=models.CharField(default='', max_length=64, validators=[django.core.validators.RegexValidator(re.compile('^\\\\d+(?:,\\\\d+)*\\\\Z'), code='invalid', message='Enter only"
] |
[
"def loadNnData(sourcePath, keyword: str = None) -> torch.Tensor: if sourcePath.endswith('.npy'): data = torch.from_numpy(np.load(sourcePath))",
"== 1: R = 0. C = array[0] return R, C # Line",
"coordinates from which R and C were computed. See function titled 'FitSphere2Points' for",
"= array[3] - array[0] D14 = D14 / np.linalg.norm(D14) chk1 = np.clip(np.abs(np.dot(D12, D13)),",
"else: # 3 or 4 points # Remove duplicate vertices, if there are",
"return R, C, P def timer(func): \"\"\"Decorator that reports the function execution time.",
"b)) # Circle radius R = np.sqrt(np.sum(np.square(x[0] - C))) # Rotate centroid back",
"np.full(3, np.nan) return R, C # Centroid of the sphere A = 2",
"= np.linalg.norm(p - C) > (R + eps) if chk: if len(B) ==",
"scipy.linalg.expm(np.array([ [0., -r[2], r[1]], [r[2], 0., -r[0]], [-r[1], r[0], 0.] ])) ##print(\"Rmat\", Rmat)",
"point coordinates, where M<=4. - R : radius of the sphere. R=Inf when",
"- np.full(2, x[0])) b = np.sum( (np.square(x[1:]) - np.square(np.full(2, x[0]))), axis=1) C =",
"array[2] - array[0] D13 = D13 / np.linalg.norm(D13) D14 = array[3] - array[0]",
"torch.from_numpy(np.load(sourcePath)[keyword]) if data.max() == 255: data[data == 255] = 1 return data def",
"1])) if np.linalg.norm(r) != 0: # Euler rotation vector r = np.arccos(n[2]) *",
"= np.take(Xb, np.where(D/R < 1e-3)[0], axis=0) Xb = np.sort(Xb, axis=0) # print(Xb) return",
"< np.sum(p) <= 1 and tolerance < np.sum(q) <= 1 return jensenshannon(p, q,",
"R) idx = np.argsort(D, axis=0) Xb = Xi[idx[:40]] D = np.sort(D, axis=0)[:4] #",
"of point coordinates, where M<=4. - R : radius of the sphere. R=Inf",
"time from functools import wraps import numpy as np import scipy from scipy.spatial",
"reports the function execution time. \"\"\" @wraps(func) def wrapper(*args, **kwargs): start = time.time()",
"index = np.unique(array, axis=0, return_index=True) array_nd = uniq[index.argsort()] if not np.array_equal(array, array_nd): print(\"found",
"C = np.mean(array, axis=0) return R, C else: # 3 or 4 points",
"axis=0)[:4] # print(Xb) # print(D) #print(np.where(D/R < 1e-3)[0]) Xb = np.take(Xb, np.where(D/R <",
"centroid of the sphere. C=nan(1,3) when the sphere is undefined, as specified above.",
"idx = idx[:-1] # n -= 1 hull_array = np.array_split(hull_array, dM) Xb =",
"threshold_otsu(edge) maskOfWhite = edge > thrd edge[maskOfWhite] = 255 edge[~maskOfWhite] = 0 #",
"C = np.full(3, np.nan) return R, C # Make plane formed by the",
"Circumsphere: \"\"\"Copied from GitHub at https://github.com/shrx/mbsc.git, not my original. \"\"\" @classmethod def fit(cls,",
"= np.transpose(np.dot(Rmat, np.transpose(array))) ##print(\"Xr\", Xr) # Circle centroid x = Xr[:, :2] A",
"p is on or inside the bounding sphere. If not, it must be",
"##print(\"Xr\", Xr) # Circle centroid x = Xr[:, :2] A = 2 *",
"edge[maskOfWhite] = 255 edge[~maskOfWhite] = 0 # 提取 labeledImg = measure.label(edge, connectivity=2) regionProps",
"code author: <NAME> (<EMAIL>) Date: Dec.2014\"\"\" # Get the convex hull of the",
"np.sqrt(np.sum(np.square(x[0] - C))) # Rotate centroid back into the original frame of reference",
"original. \"\"\" @classmethod def fit(cls, array): \"\"\"Compute exact minimum bounding sphere of a",
"Check if p is on or inside the bounding sphere. If not, it",
"array[0] D13 = D13 / np.linalg.norm(D13) chk = np.clip(np.abs(np.dot(D12, D13)), 0., 1.) if",
"- R) idx = np.argsort(D, axis=0) Xb = Xi[idx[:40]] D = np.sort(D, axis=0)[:4]",
"uniq[index.argsort()] if not np.array_equal(array, array_nd): print(\"found duplicate\") print(array_nd) R, C = cls.fit_base(array_nd) return",
"return res return wrapper class Entropy: def __init__(self) -> None: pass @staticmethod def",
"vector specifying the centroid of the sphere. - Xb : subset of X,",
"array[0] D12 = D12 / np.linalg.norm(D12) D13 = array[2] - array[0] D13 =",
"putIntoCube(image, size=48, **kwargs): longToWidthRatio = max(image.shape) / min(image.shape) image = transform.resize( image, (size,",
"= M % dM # n = np.ceil(M/dM) # idx = dM *",
"point coordinates from which R and C were computed. See function titled 'FitSphere2Points'",
"* dM: # idx[n-2] = idx[n-2] + idx[n-1] # idx = idx[:-1] #",
"size // longToWidthRatio), **kwargs) cube = np.zeros((64, 64), dtype=np.uint8) initRowInd, initColInd = (",
"radius of the sphere. R=Inf when the sphere is undefined, as specified above.",
"D13 / np.linalg.norm(D13) chk = np.clip(np.abs(np.dot(D12, D13)), 0., 1.) if np.arccos(chk)/np.pi*180 < tol:",
"duplicate\") print(array_nd) R, C = cls.fit_base(array_nd) return R, C tol = 0.01 #",
"N == 3: # Check for collinearity D12 = array[1] - array[0] D12",
"np.where(D/R < 1e-3)[0], axis=0) Xb = np.sort(Xb, axis=0) # print(Xb) return R, C,",
"b)) # Radius of the sphere R = np.sqrt(np.sum(np.square(array[0] - C), axis=0)) return",
"return R, C # Centroid of the sphere A = 2 * (array[1:]",
"np.cross(n, np.array([0, 0, 1])) if np.linalg.norm(r) != 0: # Euler rotation vector r",
"the the points are co-planar n1 = np.linalg.norm(np.cross(D12, D13)) n2 = np.linalg.norm(np.cross(D12, D14))",
"as specified above. Matlab code author: <NAME> (<EMAIL>) Date: Dec.2014\"\"\" N = len(array)",
"hull_array[i]]), []) # 40 points closest to the sphere D = np.abs(np.sqrt(np.sum((Xi -",
"any uniq, index = np.unique(array, axis=0, return_index=True) array_nd = uniq[index.argsort()] if not np.array_equal(array,",
"np.arccos(chk1)/np.pi*180 < tol or np.arccos(chk2)/np.pi*180 < tol: R = np.inf C = np.full(3,",
"Xi = cls.B_min_sphere( np.vstack([Xb, hull_array[i]]), []) # 40 points closest to the sphere",
"the sphere is undefined, as specified above. - C : 1-by-3 vector specifying",
"transform from scipy import ndimage as ndi import torch def loadNnData(sourcePath, keyword: str",
"range(len(hull_array)): R, C, Xi = cls.B_min_sphere( np.vstack([Xb, hull_array[i]]), []) # 40 points closest",
"= 0. C = array[0] return R, C # Line segment elif N",
"for i in range(len(hull_array)): R, C, Xi = cls.B_min_sphere( np.vstack([Xb, hull_array[i]]), []) #",
"dM) Xb = np.empty([0, 3]) for i in range(len(hull_array)): R, C, Xi =",
": subset of X, listing K-by-3 list of point coordinates from which R",
"= array[2] - array[0] D13 = D13 / np.linalg.norm(D13) D14 = array[3] -",
"radius of the sphere. - C : 1-by-3 vector specifying the centroid of",
"my original. \"\"\" @classmethod def fit(cls, array): \"\"\"Compute exact minimum bounding sphere of",
"idx[n-2] = idx[n-2] + idx[n-1] # idx = idx[:-1] # n -= 1",
"idx[n-2] + idx[n-1] # idx = idx[:-1] # n -= 1 hull_array =",
"= measure.regionprops(labeledImg) regionProps.sort(key=lambda prop: prop.area, reverse=True) targetImage = regionProps[0].filled_image return targetImage @staticmethod def",
"except: #raise Exception else: M = len(hull_array) dM = min([M // 4, 300])",
"ConvexHull(array) hull_array = array[hull.vertices] hull_array = np.unique(hull_array, axis=0) # print(len(hull_array)) # Randomly permute",
"image, (size, size // longToWidthRatio), **kwargs) cube = np.zeros((64, 64), dtype=np.uint8) initRowInd, initColInd",
"0., 1.) if np.arccos(chk)/np.pi*180 < tol: R = np.inf C = np.full(3, np.nan)",
"axis=1) idx = np.argsort(D - R**2) D = D[idx] Xb = hull_array[idx[:5]] D",
"on spheres with inf radius). - X : M-by-3 array of point coordinates,",
"threshold (in degrees) if N == 3: # Check for collinearity D12 =",
"D13 / np.linalg.norm(D13) D14 = array[3] - array[0] D14 = D14 / np.linalg.norm(D14)",
"- X : M-by-3 array of point coordinates, where M<=4. - R :",
"listing K-by-3 list of point coordinates from which R and C were computed.",
"D12 = array[1] - array[0] D12 = D12 / np.linalg.norm(D12) D13 = array[2]",
"or len(P) == 0: R, C = cls.fit_base(B) # fit sphere to boundary",
"point cloud (or a triangular surface mesh) using Welzl's algorithm. - X :",
"/ np.linalg.norm(D12) D13 = array[2] - array[0] D13 = D13 / np.linalg.norm(D13) chk",
"# Empty set elif N == 0: R = np.nan C = np.full(3,",
"= cls.fit_base(hull_array) return R, C, hull_array elif len(hull_array) < 1000: # try: R,",
"import wraps import numpy as np import scipy from scipy.spatial import ConvexHull from",
"= np.sum( (np.square(array[1:]) - np.square(np.full(len(array)-1, array[0]))), axis=1) C = np.transpose(np.linalg.solve(A, b)) # Radius",
"(size, size // longToWidthRatio), **kwargs) cube = np.zeros((64, 64), dtype=np.uint8) initRowInd, initColInd =",
"bounding sphere of a 3D point cloud (or a triangular surface mesh) using",
"numpy as np import scipy from scipy.spatial import ConvexHull from scipy.spatial.distance import jensenshannon",
"cube class Circumsphere: \"\"\"Copied from GitHub at https://github.com/shrx/mbsc.git, not my original. \"\"\" @classmethod",
"image = transform.resize( image, (size, size // longToWidthRatio), **kwargs) cube = np.zeros((64, 64),",
"computed. See function titled 'FitSphere2Points' for more info. REREFERENCES: [1] Welzl, E. (1991),",
"C = cls.fit_base(B) # fit sphere to boundary points return R, C, P",
"axis=0)) R, C, _ = cls.B_min_sphere(P_new, B) P = np.insert(P_new.copy(), 0, p, axis=0)",
"[]) # 40 points closest to the sphere D = np.abs(np.sqrt(np.sum((Xi - C)**2,",
"If not, it must be # part of the new boundary. R, C,",
"maskOfWhite = edge > thrd edge[maskOfWhite] = 255 edge[~maskOfWhite] = 0 # 提取",
"R, C, P def timer(func): \"\"\"Decorator that reports the function execution time. \"\"\"",
"np.inf C = np.full(3, np.nan) return R, C # Make plane formed by",
"in Computer Science, Vol. 555, pp. 359-370 Matlab code author: <NAME> (<EMAIL>) Date:",
"B) if np.isnan(R) or np.isinf(R) or R < eps: chk = True else:",
"base=2): assert tolerance < np.sum(p) <= 1 and tolerance < np.sum(q) <= 1",
"from which R and C were computed. See function titled 'FitSphere2Points' for more",
"centroid of the sphere. - Xb : subset of X, listing K-by-3 list",
"len(B) == 4 or len(P) == 0: R, C = cls.fit_base(B) # fit",
"@staticmethod def putIntoCube(image, size=48, **kwargs): longToWidthRatio = max(image.shape) / min(image.shape) image = transform.resize(",
"parallel with the xy-plane n = np.cross(D13, D12) n = n / np.linalg.norm(n)",
"# except: #raise Exception else: M = len(hull_array) dM = min([M // 4,",
"4 points in 3D space. Note that point configurations with 3 collinear or",
"data = torch.from_numpy(np.load(sourcePath)) elif sourcePath.endswith('.npz'): data = torch.from_numpy(np.load(sourcePath)[keyword]) if data.max() == 255: data[data",
"r[0], 0.] ])) ##print(\"Rmat\", Rmat) #Xr = np.transpose(Rmat*np.transpose(array)) Xr = np.transpose(np.dot(Rmat, np.transpose(array))) ##print(\"Xr\",",
"< 1e-3)[0]) Xb = np.take(Xb, np.where(D/R < 1e-3)[0], axis=0) Xb = np.sort(Xb, axis=0)",
"= np.sort(D, axis=0)[:4] # print(Xb) # print(D) #print(np.where(D/R < 1e-3)[0]) Xb = np.take(Xb,",
"D13 = array[2] - array[0] D13 = D13 / np.linalg.norm(D13) chk = np.clip(np.abs(np.dot(D12,",
"array[2] - array[0] D13 = D13 / np.linalg.norm(D13) chk = np.clip(np.abs(np.dot(D12, D13)), 0.,",
"array[0] return R, C # Line segment elif N == 2: R =",
"'FitSphere2Points' for more info. REREFERENCES: [1] Welzl, E. (1991), 'Smallest enclosing disks (balls",
"M<=4. - R : radius of the sphere. R=Inf when the sphere is",
"list P_new = P[:-1].copy() p = P[-1].copy() # Check if p is on",
"== 0: B = np.array([p]) else: B = np.array(np.insert(B, 0, p, axis=0)) R,",
"C = np.full(3, np.nan) return R, C # Check if the the points",
"= D13 / np.linalg.norm(D13) D14 = array[3] - array[0] D14 = D14 /",
"else: chk = np.linalg.norm(p - C) > (R + eps) if chk: if",
"try: R, C, _ = cls.B_min_sphere(hull_array, []) # Coordiantes of the points used",
"= regionProps[0].filled_image return targetImage @staticmethod def putIntoCube(image, size=48, **kwargs): longToWidthRatio = max(image.shape) /",
"/ np.linalg.norm(D13) D14 = array[3] - array[0] D14 = D14 / np.linalg.norm(D14) chk1",
"np.empty([0, 3]) for i in range(len(hull_array)): R, C, Xi = cls.B_min_sphere( np.vstack([Xb, hull_array[i]]),",
"axis=0) C = np.transpose(np.dot(np.transpose(Rmat), C)) return R, C # If we got to",
"torch.tensor, dim: int): return torch.max(tensor, dim=dim).values class TVSHelper: @staticmethod def getOutline(imgFile=\"img.jpg\"): img =",
"thrd = threshold_otsu(edge) maskOfWhite = edge > thrd edge[maskOfWhite] = 255 edge[~maskOfWhite] =",
"configurations with 3 collinear or 4 coplanar points do not have well-defined solutions",
"return targetImage @staticmethod def putIntoCube(image, size=48, **kwargs): longToWidthRatio = max(image.shape) / min(image.shape) image",
"1.) if np.arccos(chk1)/np.pi*180 < tol or np.arccos(chk2)/np.pi*180 < tol: R = np.inf C",
"# or co-planar points. else: # Check if the the points are co-linear",
"np.linalg.norm(D13) chk = np.clip(np.abs(np.dot(D12, D13)), 0., 1.) if np.arccos(chk)/np.pi*180 < tol: R =",
"C, Xb @classmethod def fit_base(cls, array): \"\"\"Fit a sphere to a set of",
"idx[:-1] # n -= 1 hull_array = np.array_split(hull_array, dM) Xb = np.empty([0, 3])",
"functools import wraps import numpy as np import scipy from scipy.spatial import ConvexHull",
"# if res > 0: # idx[-1] = res # # if res",
"specified above. Matlab code author: <NAME> (<EMAIL>) Date: Dec.2014\"\"\" N = len(array) if",
"# part of the new boundary. R, C, P_new = cls.B_min_sphere(P_new, B) if",
"# Remove the last (i.e., end) point, p, from the list P_new =",
"return data def project(tensor: torch.tensor, dim: int): return torch.max(tensor, dim=dim).values class TVSHelper: @staticmethod",
"points used to compute parameters of the # minimum bounding sphere D =",
"from GitHub at https://github.com/shrx/mbsc.git, not my original. \"\"\" @classmethod def fit(cls, array): \"\"\"Compute",
"# if res <= 0.25 * dM: # idx[n-2] = idx[n-2] + idx[n-1]",
"1e-3)[0], axis=0) Xb = np.sort(Xb, axis=0) # print(Xb) return R, C, Xb @classmethod",
"a 3D point cloud (or a triangular surface mesh) using Welzl's algorithm. -",
"(array[1:] - np.full(len(array)-1, array[0])) b = np.sum( (np.square(array[1:]) - np.square(np.full(len(array)-1, array[0]))), axis=1) C",
"prop.area, reverse=True) targetImage = regionProps[0].filled_image return targetImage @staticmethod def putIntoCube(image, size=48, **kwargs): longToWidthRatio",
"np.linalg.norm(np.cross(D12, D14)) chk = np.clip(np.abs(np.dot(n1, n2)), 0., 1.) if np.arccos(chk)/np.pi*180 < tol: R",
"we have 4 unique, though possibly co-linear # or co-planar points. else: #",
"- np.array(image.shape))//2 cube[initRowInd:initRowInd+image.shape[0], initColInd:initColInd+image.shape[1]] = image return cube class Circumsphere: \"\"\"Copied from GitHub",
"to a set of 2, 3, or at most 4 points in 3D",
"print(len(hull_array)) # Randomly permute the point set hull_array = np.random.permutation(hull_array) if len(hull_array) <=",
"to the sphere D = np.abs(np.sqrt(np.sum((Xi - C)**2, axis=1)) - R) idx =",
"np.arccos(chk2)/np.pi*180 < tol: R = np.inf C = np.full(3, np.nan) return R, C",
"axis=1)) - R) idx = np.argsort(D, axis=0) Xb = Xi[idx[:40]] D = np.sort(D,",
"axis=0) return R, C else: # 3 or 4 points # Remove duplicate",
"skimage.filters import threshold_otsu from skimage import measure, transform from scipy import ndimage as",
"points # Remove duplicate vertices, if there are any uniq, index = np.unique(array,",
"- C))) # Rotate centroid back into the original frame of reference C",
"R, C tol = 0.01 # collinearity/co-planarity threshold (in degrees) if N ==",
"xy-plane n = np.cross(D13, D12) n = n / np.linalg.norm(n) ##print(\"n\", n) r",
"class TVSHelper: @staticmethod def getOutline(imgFile=\"img.jpg\"): img = io.imread(imgFile, as_gray=True) # 检测到边缘并进行滤波 edge =",
"from the list P_new = P[:-1].copy() p = P[-1].copy() # Check if p",
"sphere. If not, it must be # part of the new boundary. R,",
"img_as_ubyte(rgb2gray(edge)) edge = ndi.median_filter(edge, 3) # 二值化 thrd = threshold_otsu(edge) maskOfWhite = edge",
"pp. 359-370 Matlab code author: <NAME> (<EMAIL>) Date: Dec.2014\"\"\" # Get the convex",
"or np.arccos(chk2)/np.pi*180 < tol: R = np.inf C = np.full(3, np.nan) return R,",
"<= 1 and tolerance < np.sum(q) <= 1 return jensenshannon(p, q, base=base) if",
"have well-defined solutions (i.e., they lie on spheres with inf radius). - X",
"R and C were computed. See function titled 'FitSphere2Points' for more info. REREFERENCES:",
"0., 1.) chk2 = np.clip(np.abs(np.dot(D12, D14)), 0., 1.) if np.arccos(chk1)/np.pi*180 < tol or",
"np.nan) return R, C # Make plane formed by the points parallel with",
"**kwargs) cube = np.zeros((64, 64), dtype=np.uint8) initRowInd, initColInd = ( np.array(cube.shape) - np.array(image.shape))//2",
"np.transpose(np.linalg.solve(A, b)) # Circle radius R = np.sqrt(np.sum(np.square(x[0] - C))) # Rotate centroid",
"Get the convex hull of the point set hull = ConvexHull(array) hull_array =",
"tol = 0.01 # collinearity/co-planarity threshold (in degrees) if N == 3: #",
"possibly co-linear # or co-planar points. else: # Check if the the points",
"Entropy: def __init__(self) -> None: pass @staticmethod def JSDivergence(p, q, tolerance=0.98, base=2): assert",
"= time.time() timeCost = end - start hour, timeCost = divmod(timeCost, 3600) minute,",
"-> torch.Tensor: if sourcePath.endswith('.npy'): data = torch.from_numpy(np.load(sourcePath)) elif sourcePath.endswith('.npz'): data = torch.from_numpy(np.load(sourcePath)[keyword]) if",
"= 0.01 # collinearity/co-planarity threshold (in degrees) if N == 3: # Check",
"Matlab code author: <NAME> (<EMAIL>) Date: Dec.2014\"\"\" N = len(array) if N >",
"(np.square(array[1:]) - np.square(np.full(len(array)-1, array[0]))), axis=1) C = np.transpose(np.linalg.solve(A, b)) # Radius of the",
"\"\"\"Fit a sphere to a set of 2, 3, or at most 4",
"array): \"\"\"Fit a sphere to a set of 2, 3, or at most",
"transform.resize( image, (size, size // longToWidthRatio), **kwargs) cube = np.zeros((64, 64), dtype=np.uint8) initRowInd,",
"# Circle centroid x = Xr[:, :2] A = 2 * (x[1:] -",
"555, pp. 359-370 Matlab code author: <NAME> (<EMAIL>) Date: Dec.2014\"\"\" # Get the",
"points return R, C, P # Remove the last (i.e., end) point, p,",
"we got to this point then we have 4 unique, though possibly co-linear",
"# print(D) #print(np.where(D/R < 1e-3)[0]) Xb = np.take(Xb, np.where(D/R < 1e-3)[0], axis=0) Xb",
"divmod(timeCost, 3600) minute, second = divmod(timeCost, 60) hour, minute, second = int(hour), int(minute),",
"# try: R, C, _ = cls.B_min_sphere(hull_array, []) # Coordiantes of the points",
"Rmat = scipy.linalg.expm(np.array([ [0., -r[2], r[1]], [r[2], 0., -r[0]], [-r[1], r[0], 0.] ]))",
"= n / np.linalg.norm(n) ##print(\"n\", n) r = np.cross(n, np.array([0, 0, 1])) if",
"import scipy from scipy.spatial import ConvexHull from scipy.spatial.distance import jensenshannon from skimage import",
"= array[2] - array[0] D13 = D13 / np.linalg.norm(D13) chk = np.clip(np.abs(np.dot(D12, D13)),",
"array of point coordinates, with N<=4') return # Empty set elif N ==",
"@classmethod def fit_base(cls, array): \"\"\"Fit a sphere to a set of 2, 3,",
"there are any uniq, index = np.unique(array, axis=0, return_index=True) array_nd = uniq[index.argsort()] if",
"Remove duplicate vertices, if there are any uniq, index = np.unique(array, axis=0, return_index=True)",
"return R, C @classmethod def B_min_sphere(cls, P, B): eps = 1E-6 if len(B)",
"the sphere D = np.abs(np.sqrt(np.sum((Xi - C)**2, axis=1)) - R) idx = np.argsort(D,",
"= array[1] - array[0] D12 = D12 / np.linalg.norm(D12) D13 = array[2] -",
"(np.square(x[1:]) - np.square(np.full(2, x[0]))), axis=1) C = np.transpose(np.linalg.solve(A, b)) # Circle radius R",
"C, hull_array elif len(hull_array) < 1000: # try: R, C, _ = cls.B_min_sphere(hull_array,",
"= measure.label(edge, connectivity=2) regionProps = measure.regionprops(labeledImg) regionProps.sort(key=lambda prop: prop.area, reverse=True) targetImage = regionProps[0].filled_image",
"(i.e., they lie on spheres with inf radius). - X : M-by-3 array",
"time.time() res = func(*args, **kwargs) end = time.time() timeCost = end - start",
"Xb[D < 1E-6] idx = np.argsort(Xb[:, 0]) Xb = Xb[idx] return R, C,",
"C)**2, axis=1)) - R) idx = np.argsort(D, axis=0) Xb = Xi[idx[:40]] D =",
"r[1]], [r[2], 0., -r[0]], [-r[1], r[0], 0.] ])) ##print(\"Rmat\", Rmat) #Xr = np.transpose(Rmat*np.transpose(array))",
"C # A single point elif N == 1: R = 0. C",
"* (x[1:] - np.full(2, x[0])) b = np.sum( (np.square(x[1:]) - np.square(np.full(2, x[0]))), axis=1)",
"is undefined, as specified above. Matlab code author: <NAME> (<EMAIL>) Date: Dec.2014\"\"\" N",
"N<=4') return # Empty set elif N == 0: R = np.nan C",
"n = np.ceil(M/dM) # idx = dM * np.ones((1, n)) # if res",
"(in degrees) if N == 3: # Check for collinearity D12 = array[1]",
"edge = ndi.median_filter(edge, 3) # 二值化 thrd = threshold_otsu(edge) maskOfWhite = edge >",
"if res > 0: # idx[-1] = res # # if res <=",
"prop: prop.area, reverse=True) targetImage = regionProps[0].filled_image return targetImage @staticmethod def putIntoCube(image, size=48, **kwargs):",
"Xb : subset of X, listing K-by-3 list of point coordinates from which",
": 1-by-3 vector specifying the centroid of the sphere. C=nan(1,3) when the sphere",
"np.clip(np.abs(np.dot(D12, D13)), 0., 1.) if np.arccos(chk)/np.pi*180 < tol: R = np.inf C =",
"are any uniq, index = np.unique(array, axis=0, return_index=True) array_nd = uniq[index.argsort()] if not",
"dM: # idx[n-2] = idx[n-2] + idx[n-1] # idx = idx[:-1] # n",
"R, C, P_new = cls.B_min_sphere(P_new, B) if np.isnan(R) or np.isinf(R) or R <",
"`{func.__name__}` runs for {hour}h {minute}min {second}s\") return res return wrapper class Entropy: def",
"are co-linear D12 = array[1] - array[0] D12 = D12 / np.linalg.norm(D12) D13",
"def JSDivergence(p, q, tolerance=0.98, base=2): assert tolerance < np.sum(p) <= 1 and tolerance",
"func(*args, **kwargs) end = time.time() timeCost = end - start hour, timeCost =",
"== 2: R = np.linalg.norm(array[1] - array[0]) / 2 C = np.mean(array, axis=0)",
"= np.zeros((64, 64), dtype=np.uint8) initRowInd, initColInd = ( np.array(cube.shape) - np.array(image.shape))//2 cube[initRowInd:initRowInd+image.shape[0], initColInd:initColInd+image.shape[1]]",
"E. (1991), 'Smallest enclosing disks (balls and ellipsoids)', Lecture Notes in Computer Science,",
"0. C = array[0] return R, C # Line segment elif N ==",
"torch.Tensor: if sourcePath.endswith('.npy'): data = torch.from_numpy(np.load(sourcePath)) elif sourcePath.endswith('.npz'): data = torch.from_numpy(np.load(sourcePath)[keyword]) if data.max()",
"elif N == 1: R = 0. C = array[0] return R, C",
"<gh_stars>1-10 import time from functools import wraps import numpy as np import scipy",
"0., -r[0]], [-r[1], r[0], 0.] ])) ##print(\"Rmat\", Rmat) #Xr = np.transpose(Rmat*np.transpose(array)) Xr =",
"or 4 coplanar points do not have well-defined solutions (i.e., they lie on",
"radius R = np.sqrt(np.sum(np.square(x[0] - C))) # Rotate centroid back into the original",
"minimum bounding sphere of a 3D point cloud (or a triangular surface mesh)",
"检测到边缘并进行滤波 edge = filters.sobel(img) edge = img_as_ubyte(rgb2gray(edge)) edge = ndi.median_filter(edge, 3) # 二值化",
"# idx[n-2] = idx[n-2] + idx[n-1] # idx = idx[:-1] # n -=",
"cls.fit_base(array_nd) return R, C tol = 0.01 # collinearity/co-planarity threshold (in degrees) if",
"> thrd edge[maskOfWhite] = 255 edge[~maskOfWhite] = 0 # 提取 labeledImg = measure.label(edge,",
"C, _ = cls.B_min_sphere(hull_array, []) # Coordiantes of the points used to compute",
"4: R, C = cls.fit_base(hull_array) return R, C, hull_array elif len(hull_array) < 1000:",
"= np.array_split(hull_array, dM) Xb = np.empty([0, 3]) for i in range(len(hull_array)): R, C,",
"= cls.B_min_sphere(P_new, B) if np.isnan(R) or np.isinf(R) or R < eps: chk =",
"import ndimage as ndi import torch def loadNnData(sourcePath, keyword: str = None) ->",
"X : M-by-3 list of point co-ordinates or a triangular surface mesh specified",
"vector r = np.arccos(n[2]) * r / np.linalg.norm(r) ##print(\"r\", r) Rmat = scipy.linalg.expm(np.array([",
"img = io.imread(imgFile, as_gray=True) # 检测到边缘并进行滤波 edge = filters.sobel(img) edge = img_as_ubyte(rgb2gray(edge)) edge",
"else: # Check if the the points are co-linear D12 = array[1] -",
"= np.cross(D13, D12) n = n / np.linalg.norm(n) ##print(\"n\", n) r = np.cross(n,",
"initColInd = ( np.array(cube.shape) - np.array(image.shape))//2 cube[initRowInd:initRowInd+image.shape[0], initColInd:initColInd+image.shape[1]] = image return cube class",
"inf radius). - X : M-by-3 array of point coordinates, where M<=4. -",
"R, C, Xb # except: #raise Exception else: M = len(hull_array) dM =",
"b = np.sum( (np.square(array[1:]) - np.square(np.full(len(array)-1, array[0]))), axis=1) C = np.transpose(np.linalg.solve(A, b)) #",
"else: B = np.array(np.insert(B, 0, p, axis=0)) R, C, _ = cls.B_min_sphere(P_new, B)",
"round(second, 1) print( f\"Function `{func.__name__}` runs for {hour}h {minute}min {second}s\") return res return",
"wrapper class Entropy: def __init__(self) -> None: pass @staticmethod def JSDivergence(p, q, tolerance=0.98,",
"np.clip(np.abs(np.dot(D12, D13)), 0., 1.) chk2 = np.clip(np.abs(np.dot(D12, D14)), 0., 1.) if np.arccos(chk1)/np.pi*180 <",
"C were computed. See function titled 'FitSphere2Points' for more info. REREFERENCES: [1] Welzl,",
"/ 2 C = np.mean(array, axis=0) return R, C else: # 3 or",
"p, axis=0) return R, C, P def timer(func): \"\"\"Decorator that reports the function",
"the sphere. - Xb : subset of X, listing K-by-3 list of point",
"specified as a TriRep object. - R : radius of the sphere. -",
"B) P = np.insert(P_new.copy(), 0, p, axis=0) return R, C, P def timer(func):",
"sphere is undefined, as specified above. - C : 1-by-3 vector specifying the",
"for collinearity D12 = array[1] - array[0] D12 = D12 / np.linalg.norm(D12) D13",
"N > 4: print('Input must a N-by-3 array of point coordinates, with N<=4')",
"If we got to this point then we have 4 unique, though possibly",
"co-ordinates or a triangular surface mesh specified as a TriRep object. - R",
"object. - R : radius of the sphere. - C : 1-by-3 vector",
"np.argsort(D - R**2) D = D[idx] Xb = hull_array[idx[:5]] D = D[:5] Xb",
"0.25 * dM: # idx[n-2] = idx[n-2] + idx[n-1] # idx = idx[:-1]",
"# Radius of the sphere R = np.sqrt(np.sum(np.square(array[0] - C), axis=0)) return R,",
"code author: <NAME> (<EMAIL>) Date: Dec.2014\"\"\" N = len(array) if N > 4:",
"= dM * np.ones((1, n)) # if res > 0: # idx[-1] =",
"4, 300]) # unnecessary ? # res = M % dM # n",
"= True else: chk = np.linalg.norm(p - C) > (R + eps) if",
"R = np.sqrt(np.sum(np.square(x[0] - C))) # Rotate centroid back into the original frame",
"= np.transpose(np.dot(np.transpose(Rmat), C)) return R, C # If we got to this point",
"if chk: if len(B) == 0: B = np.array([p]) else: B = np.array(np.insert(B,",
"if np.isnan(R) or np.isinf(R) or R < eps: chk = True else: chk",
"= np.argsort(Xb[:, 0]) Xb = Xb[idx] return R, C, Xb # except: #raise",
"print(array_nd) R, C = cls.fit_base(array_nd) return R, C tol = 0.01 # collinearity/co-planarity",
"array_nd = uniq[index.argsort()] if not np.array_equal(array, array_nd): print(\"found duplicate\") print(array_nd) R, C =",
"= P[-1].copy() # Check if p is on or inside the bounding sphere.",
"axis=1) C = np.transpose(np.linalg.solve(A, b)) # Radius of the sphere R = np.sqrt(np.sum(np.square(array[0]",
"- C)**2, axis=1)) - R) idx = np.argsort(D, axis=0) Xb = Xi[idx[:40]] D",
"axis=0, return_index=True) array_nd = uniq[index.argsort()] if not np.array_equal(array, array_nd): print(\"found duplicate\") print(array_nd) R,",
"subset of X, listing K-by-3 list of point coordinates from which R and",
"degrees) if N == 3: # Check for collinearity D12 = array[1] -",
"that point configurations with 3 collinear or 4 coplanar points do not have",
"np.sum( (np.square(x[1:]) - np.square(np.full(2, x[0]))), axis=1) C = np.transpose(np.linalg.solve(A, b)) # Circle radius",
"D13 = D13 / np.linalg.norm(D13) D14 = array[3] - array[0] D14 = D14",
"space. Note that point configurations with 3 collinear or 4 coplanar points do",
"from skimage import measure, transform from scipy import ndimage as ndi import torch",
"= np.full(3, np.nan) return R, C # Make plane formed by the points",
"titled 'FitSphere2Points' for more info. REREFERENCES: [1] Welzl, E. (1991), 'Smallest enclosing disks",
"got to this point then we have 4 unique, though possibly co-linear #",
"# Centroid of the sphere A = 2 * (array[1:] - np.full(len(array)-1, array[0]))",
"P # Remove the last (i.e., end) point, p, from the list P_new",
"np.insert(P_new.copy(), 0, p, axis=0) return R, C, P def timer(func): \"\"\"Decorator that reports",
"Rmat) #Xr = np.transpose(Rmat*np.transpose(array)) Xr = np.transpose(np.dot(Rmat, np.transpose(array))) ##print(\"Xr\", Xr) # Circle centroid",
"idx = np.argsort(Xb[:, 0]) Xb = Xb[idx] return R, C, Xb # except:",
"# Check if p is on or inside the bounding sphere. If not,",
"Lecture Notes in Computer Science, Vol. 555, pp. 359-370 Matlab code author: <NAME>",
"elif N == 0: R = np.nan C = np.full(3, np.nan) return R,",
"the the points are co-linear D12 = array[1] - array[0] D12 = D12",
"'Smallest enclosing disks (balls and ellipsoids)', Lecture Notes in Computer Science, Vol. 555,",
"hull of the point set hull = ConvexHull(array) hull_array = array[hull.vertices] hull_array =",
"hull = ConvexHull(array) hull_array = array[hull.vertices] hull_array = np.unique(hull_array, axis=0) # print(len(hull_array)) #",
"targetImage = regionProps[0].filled_image return targetImage @staticmethod def putIntoCube(image, size=48, **kwargs): longToWidthRatio = max(image.shape)",
"np.full(3, np.nan) return R, C # Check if the the points are co-planar",
"or np.isinf(R) or R < eps: chk = True else: chk = np.linalg.norm(p",
"of reference C = np.append(C, [np.mean(Xr[:, 2])], axis=0) C = np.transpose(np.dot(np.transpose(Rmat), C)) return",
"min([M // 4, 300]) # unnecessary ? # res = M % dM",
"the convex hull of the point set hull = ConvexHull(array) hull_array = array[hull.vertices]",
"+ idx[n-1] # idx = idx[:-1] # n -= 1 hull_array = np.array_split(hull_array,",
"if np.arccos(chk1)/np.pi*180 < tol or np.arccos(chk2)/np.pi*180 < tol: R = np.inf C =",
"Circle centroid x = Xr[:, :2] A = 2 * (x[1:] - np.full(2,",
"enclosing disks (balls and ellipsoids)', Lecture Notes in Computer Science, Vol. 555, pp.",
"io.imread(imgFile, as_gray=True) # 检测到边缘并进行滤波 edge = filters.sobel(img) edge = img_as_ubyte(rgb2gray(edge)) edge = ndi.median_filter(edge,",
"\"\"\"Compute exact minimum bounding sphere of a 3D point cloud (or a triangular",
"// 4, 300]) # unnecessary ? # res = M % dM #",
"sphere to boundary points return R, C, P # Remove the last (i.e.,",
"sphere. C=nan(1,3) when the sphere is undefined, as specified above. Matlab code author:",
"must be # part of the new boundary. R, C, P_new = cls.B_min_sphere(P_new,",
"p = P[-1].copy() # Check if p is on or inside the bounding",
"R, C # A single point elif N == 1: R = 0.",
"set hull_array = np.random.permutation(hull_array) if len(hull_array) <= 4: R, C = cls.fit_base(hull_array) return",
"TriRep object. - R : radius of the sphere. - C : 1-by-3",
"-r[0]], [-r[1], r[0], 0.] ])) ##print(\"Rmat\", Rmat) #Xr = np.transpose(Rmat*np.transpose(array)) Xr = np.transpose(np.dot(Rmat,",
"chk1 = np.clip(np.abs(np.dot(D12, D13)), 0., 1.) chk2 = np.clip(np.abs(np.dot(D12, D14)), 0., 1.) if",
"@classmethod def fit(cls, array): \"\"\"Compute exact minimum bounding sphere of a 3D point",
"D14 / np.linalg.norm(D14) chk1 = np.clip(np.abs(np.dot(D12, D13)), 0., 1.) chk2 = np.clip(np.abs(np.dot(D12, D14)),",
"64), dtype=np.uint8) initRowInd, initColInd = ( np.array(cube.shape) - np.array(image.shape))//2 cube[initRowInd:initRowInd+image.shape[0], initColInd:initColInd+image.shape[1]] = image",
"\"\"\"Decorator that reports the function execution time. \"\"\" @wraps(func) def wrapper(*args, **kwargs): start",
"(or a triangular surface mesh) using Welzl's algorithm. - X : M-by-3 list",
"np.linalg.norm(D12) D13 = array[2] - array[0] D13 = D13 / np.linalg.norm(D13) chk =",
"are co-planar n1 = np.linalg.norm(np.cross(D12, D13)) n2 = np.linalg.norm(np.cross(D12, D14)) chk = np.clip(np.abs(np.dot(n1,",
"function titled 'FitSphere2Points' for more info. REREFERENCES: [1] Welzl, E. (1991), 'Smallest enclosing",
"the points are co-linear D12 = array[1] - array[0] D12 = D12 /",
"hull_array = np.unique(hull_array, axis=0) # print(len(hull_array)) # Randomly permute the point set hull_array",
"permute the point set hull_array = np.random.permutation(hull_array) if len(hull_array) <= 4: R, C",
"boundary points return R, C, P # Remove the last (i.e., end) point,",
"@staticmethod def getOutline(imgFile=\"img.jpg\"): img = io.imread(imgFile, as_gray=True) # 检测到边缘并进行滤波 edge = filters.sobel(img) edge",
"and C were computed. See function titled 'FitSphere2Points' for more info. REREFERENCES: [1]",
"do not have well-defined solutions (i.e., they lie on spheres with inf radius).",
"res = M % dM # n = np.ceil(M/dM) # idx = dM",
"1 return data def project(tensor: torch.tensor, dim: int): return torch.max(tensor, dim=dim).values class TVSHelper:",
"return R, C # If we got to this point then we have",
"= np.unique(array, axis=0, return_index=True) array_nd = uniq[index.argsort()] if not np.array_equal(array, array_nd): print(\"found duplicate\")",
"sphere of a 3D point cloud (or a triangular surface mesh) using Welzl's",
"N-by-3 array of point coordinates, with N<=4') return # Empty set elif N",
"R = np.inf C = np.full(3, np.nan) return R, C # Make plane",
"np.arccos(chk)/np.pi*180 < tol: R = np.inf C = np.full(3, np.nan) return R, C",
"disks (balls and ellipsoids)', Lecture Notes in Computer Science, Vol. 555, pp. 359-370",
"wraps import numpy as np import scipy from scipy.spatial import ConvexHull from scipy.spatial.distance",
"coplanar points do not have well-defined solutions (i.e., they lie on spheres with",
"elif len(hull_array) < 1000: # try: R, C, _ = cls.B_min_sphere(hull_array, []) #",
"as np import scipy from scipy.spatial import ConvexHull from scipy.spatial.distance import jensenshannon from",
"np.array(image.shape))//2 cube[initRowInd:initRowInd+image.shape[0], initColInd:initColInd+image.shape[1]] = image return cube class Circumsphere: \"\"\"Copied from GitHub at",
"np.square(np.full(len(array)-1, array[0]))), axis=1) C = np.transpose(np.linalg.solve(A, b)) # Radius of the sphere R",
"= D[idx] Xb = hull_array[idx[:5]] D = D[:5] Xb = Xb[D < 1E-6]",
"rotation vector r = np.arccos(n[2]) * r / np.linalg.norm(r) ##print(\"r\", r) Rmat =",
"C))) # Rotate centroid back into the original frame of reference C =",
"C # If we got to this point then we have 4 unique,",
"array[0])) b = np.sum( (np.square(array[1:]) - np.square(np.full(len(array)-1, array[0]))), axis=1) C = np.transpose(np.linalg.solve(A, b))",
"0.] ])) ##print(\"Rmat\", Rmat) #Xr = np.transpose(Rmat*np.transpose(array)) Xr = np.transpose(np.dot(Rmat, np.transpose(array))) ##print(\"Xr\", Xr)",
"Coordiantes of the points used to compute parameters of the # minimum bounding",
"np.mean(array, axis=0) return R, C else: # 3 or 4 points # Remove",
"R = np.inf C = np.full(3, np.nan) return R, C # Centroid of",
"== 255] = 1 return data def project(tensor: torch.tensor, dim: int): return torch.max(tensor,",
"len(B) == 0: B = np.array([p]) else: B = np.array(np.insert(B, 0, p, axis=0))",
"return R, C # A single point elif N == 1: R =",
"in range(len(hull_array)): R, C, Xi = cls.B_min_sphere( np.vstack([Xb, hull_array[i]]), []) # 40 points",
"- start hour, timeCost = divmod(timeCost, 3600) minute, second = divmod(timeCost, 60) hour,",
"= np.array(np.insert(B, 0, p, axis=0)) R, C, _ = cls.B_min_sphere(P_new, B) P =",
"D = np.abs(np.sqrt(np.sum((Xi - C)**2, axis=1)) - R) idx = np.argsort(D, axis=0) Xb",
"= np.linalg.norm(array[1] - array[0]) / 2 C = np.mean(array, axis=0) return R, C",
"tolerance < np.sum(q) <= 1 return jensenshannon(p, q, base=base) if __name__ == '__main__':",
"np.inf C = np.full(3, np.nan) return R, C # Check if the the",
"**kwargs) end = time.time() timeCost = end - start hour, timeCost = divmod(timeCost,",
"execution time. \"\"\" @wraps(func) def wrapper(*args, **kwargs): start = time.time() res = func(*args,",
"np.nan) return R, C # Check if the the points are co-planar n1",
"if the the points are co-planar n1 = np.linalg.norm(np.cross(D12, D13)) n2 = np.linalg.norm(np.cross(D12,",
"tolerance=0.98, base=2): assert tolerance < np.sum(p) <= 1 and tolerance < np.sum(q) <=",
"edge[~maskOfWhite] = 0 # 提取 labeledImg = measure.label(edge, connectivity=2) regionProps = measure.regionprops(labeledImg) regionProps.sort(key=lambda",
"surface mesh) using Welzl's algorithm. - X : M-by-3 list of point co-ordinates",
"idx = np.argsort(D, axis=0) Xb = Xi[idx[:40]] D = np.sort(D, axis=0)[:4] # print(Xb)",
"D = np.sum(np.square(hull_array - C), axis=1) idx = np.argsort(D - R**2) D =",
"R, C = cls.fit_base(hull_array) return R, C, hull_array elif len(hull_array) < 1000: #",
"point co-ordinates or a triangular surface mesh specified as a TriRep object. -",
"X : M-by-3 array of point coordinates, where M<=4. - R : radius",
"initRowInd, initColInd = ( np.array(cube.shape) - np.array(image.shape))//2 cube[initRowInd:initRowInd+image.shape[0], initColInd:initColInd+image.shape[1]] = image return cube",
"- C : 1-by-3 vector specifying the centroid of the sphere. C=nan(1,3) when",
"= D[:5] Xb = Xb[D < 1E-6] idx = np.argsort(Xb[:, 0]) Xb =",
"chk: if len(B) == 0: B = np.array([p]) else: B = np.array(np.insert(B, 0,",
"See function titled 'FitSphere2Points' for more info. REREFERENCES: [1] Welzl, E. (1991), 'Smallest",
"np.unique(hull_array, axis=0) # print(len(hull_array)) # Randomly permute the point set hull_array = np.random.permutation(hull_array)",
"A = 2 * (array[1:] - np.full(len(array)-1, array[0])) b = np.sum( (np.square(array[1:]) -",
"Note that point configurations with 3 collinear or 4 coplanar points do not",
"closest to the sphere D = np.abs(np.sqrt(np.sum((Xi - C)**2, axis=1)) - R) idx",
"R, C, hull_array elif len(hull_array) < 1000: # try: R, C, _ =",
"as ndi import torch def loadNnData(sourcePath, keyword: str = None) -> torch.Tensor: if",
"3D point cloud (or a triangular surface mesh) using Welzl's algorithm. - X",
"time. \"\"\" @wraps(func) def wrapper(*args, **kwargs): start = time.time() res = func(*args, **kwargs)",
"the sphere. - C : 1-by-3 vector specifying the centroid of the sphere.",
"specifying the centroid of the sphere. C=nan(1,3) when the sphere is undefined, as",
"if len(B) == 0: B = np.array([p]) else: B = np.array(np.insert(B, 0, p,",
"# Check if the the points are co-planar n1 = np.linalg.norm(np.cross(D12, D13)) n2",
"= idx[:-1] # n -= 1 hull_array = np.array_split(hull_array, dM) Xb = np.empty([0,",
"= np.inf C = np.full(3, np.nan) return R, C # Check if the",
"axis=1) C = np.transpose(np.linalg.solve(A, b)) # Circle radius R = np.sqrt(np.sum(np.square(x[0] - C)))",
"(balls and ellipsoids)', Lecture Notes in Computer Science, Vol. 555, pp. 359-370 Matlab",
"return cube class Circumsphere: \"\"\"Copied from GitHub at https://github.com/shrx/mbsc.git, not my original. \"\"\"",
"= image return cube class Circumsphere: \"\"\"Copied from GitHub at https://github.com/shrx/mbsc.git, not my",
"[np.mean(Xr[:, 2])], axis=0) C = np.transpose(np.dot(np.transpose(Rmat), C)) return R, C # If we",
":2] A = 2 * (x[1:] - np.full(2, x[0])) b = np.sum( (np.square(x[1:])",
"C = np.full(3, np.nan) return R, C # Centroid of the sphere A",
"regionProps = measure.regionprops(labeledImg) regionProps.sort(key=lambda prop: prop.area, reverse=True) targetImage = regionProps[0].filled_image return targetImage @staticmethod",
"second = int(hour), int(minute), round(second, 1) print( f\"Function `{func.__name__}` runs for {hour}h {minute}min",
"eps) if chk: if len(B) == 0: B = np.array([p]) else: B =",
"= np.clip(np.abs(np.dot(n1, n2)), 0., 1.) if np.arccos(chk)/np.pi*180 < tol: R = np.inf C",
"D13 = array[2] - array[0] D13 = D13 / np.linalg.norm(D13) D14 = array[3]",
"np.isnan(R) or np.isinf(R) or R < eps: chk = True else: chk =",
"point configurations with 3 collinear or 4 coplanar points do not have well-defined",
"return torch.max(tensor, dim=dim).values class TVSHelper: @staticmethod def getOutline(imgFile=\"img.jpg\"): img = io.imread(imgFile, as_gray=True) #",
"ndi.median_filter(edge, 3) # 二值化 thrd = threshold_otsu(edge) maskOfWhite = edge > thrd edge[maskOfWhite]",
"# idx[-1] = res # # if res <= 0.25 * dM: #",
"R, C, _ = cls.B_min_sphere(hull_array, []) # Coordiantes of the points used to",
"C = np.transpose(np.dot(np.transpose(Rmat), C)) return R, C # If we got to this",
"二值化 thrd = threshold_otsu(edge) maskOfWhite = edge > thrd edge[maskOfWhite] = 255 edge[~maskOfWhite]",
"np.linalg.norm(array[1] - array[0]) / 2 C = np.mean(array, axis=0) return R, C else:",
"= torch.from_numpy(np.load(sourcePath)[keyword]) if data.max() == 255: data[data == 255] = 1 return data",
"though possibly co-linear # or co-planar points. else: # Check if the the",
"np.array_equal(array, array_nd): print(\"found duplicate\") print(array_nd) R, C = cls.fit_base(array_nd) return R, C tol",
"or co-planar points. else: # Check if the the points are co-linear D12",
"exact minimum bounding sphere of a 3D point cloud (or a triangular surface",
"points are co-planar n1 = np.linalg.norm(np.cross(D12, D13)) n2 = np.linalg.norm(np.cross(D12, D14)) chk =",
"boundary. R, C, P_new = cls.B_min_sphere(P_new, B) if np.isnan(R) or np.isinf(R) or R",
"N == 2: R = np.linalg.norm(array[1] - array[0]) / 2 C = np.mean(array,",
"__init__(self) -> None: pass @staticmethod def JSDivergence(p, q, tolerance=0.98, base=2): assert tolerance <",
"255] = 1 return data def project(tensor: torch.tensor, dim: int): return torch.max(tensor, dim=dim).values",
"keyword: str = None) -> torch.Tensor: if sourcePath.endswith('.npy'): data = torch.from_numpy(np.load(sourcePath)) elif sourcePath.endswith('.npz'):",
"rgb2gray from skimage.util import img_as_ubyte from skimage.filters import threshold_otsu from skimage import measure,",
"<NAME> (<EMAIL>) Date: Dec.2014\"\"\" N = len(array) if N > 4: print('Input must",
"# print(Xb) # print(D) #print(np.where(D/R < 1e-3)[0]) Xb = np.take(Xb, np.where(D/R < 1e-3)[0],",
"@wraps(func) def wrapper(*args, **kwargs): start = time.time() res = func(*args, **kwargs) end =",
"from scipy import ndimage as ndi import torch def loadNnData(sourcePath, keyword: str =",
"C # Check if the the points are co-planar n1 = np.linalg.norm(np.cross(D12, D13))",
"= np.argsort(D, axis=0) Xb = Xi[idx[:40]] D = np.sort(D, axis=0)[:4] # print(Xb) #",
"list of point co-ordinates or a triangular surface mesh specified as a TriRep",
"measure.regionprops(labeledImg) regionProps.sort(key=lambda prop: prop.area, reverse=True) targetImage = regionProps[0].filled_image return targetImage @staticmethod def putIntoCube(image,",
"np.sum( (np.square(array[1:]) - np.square(np.full(len(array)-1, array[0]))), axis=1) C = np.transpose(np.linalg.solve(A, b)) # Radius of",
"of X, listing K-by-3 list of point coordinates from which R and C",
"def putIntoCube(image, size=48, **kwargs): longToWidthRatio = max(image.shape) / min(image.shape) image = transform.resize( image,",
"fit sphere to boundary points return R, C, P # Remove the last",
"REREFERENCES: [1] Welzl, E. (1991), 'Smallest enclosing disks (balls and ellipsoids)', Lecture Notes",
"return R, C # Line segment elif N == 2: R = np.linalg.norm(array[1]",
"unnecessary ? # res = M % dM # n = np.ceil(M/dM) #",
"= img_as_ubyte(rgb2gray(edge)) edge = ndi.median_filter(edge, 3) # 二值化 thrd = threshold_otsu(edge) maskOfWhite =",
"import rgb2gray from skimage.util import img_as_ubyte from skimage.filters import threshold_otsu from skimage import",
"vertices, if there are any uniq, index = np.unique(array, axis=0, return_index=True) array_nd =",
"C = np.full(3, np.nan) return R, C # A single point elif N",
"point coordinates, with N<=4') return # Empty set elif N == 0: R",
"2 * (x[1:] - np.full(2, x[0])) b = np.sum( (np.square(x[1:]) - np.square(np.full(2, x[0]))),",
"solutions (i.e., they lie on spheres with inf radius). - X : M-by-3",
"used to compute parameters of the # minimum bounding sphere D = np.sum(np.square(hull_array",
"the function execution time. \"\"\" @wraps(func) def wrapper(*args, **kwargs): start = time.time() res",
"= 2 * (array[1:] - np.full(len(array)-1, array[0])) b = np.sum( (np.square(array[1:]) - np.square(np.full(len(array)-1,",
"D13 = D13 / np.linalg.norm(D13) chk = np.clip(np.abs(np.dot(D12, D13)), 0., 1.) if np.arccos(chk)/np.pi*180",
"D = D[idx] Xb = hull_array[idx[:5]] D = D[:5] Xb = Xb[D <",
"# print(len(hull_array)) # Randomly permute the point set hull_array = np.random.permutation(hull_array) if len(hull_array)",
"= torch.from_numpy(np.load(sourcePath)) elif sourcePath.endswith('.npz'): data = torch.from_numpy(np.load(sourcePath)[keyword]) if data.max() == 255: data[data ==",
"cls.fit_base(hull_array) return R, C, hull_array elif len(hull_array) < 1000: # try: R, C,",
"C : 1-by-3 vector specifying the centroid of the sphere. - Xb :",
"60) hour, minute, second = int(hour), int(minute), round(second, 1) print( f\"Function `{func.__name__}` runs",
"or inside the bounding sphere. If not, it must be # part of",
"// longToWidthRatio), **kwargs) cube = np.zeros((64, 64), dtype=np.uint8) initRowInd, initColInd = ( np.array(cube.shape)",
"for more info. REREFERENCES: [1] Welzl, E. (1991), 'Smallest enclosing disks (balls and",
"set of 2, 3, or at most 4 points in 3D space. Note",
"# res = M % dM # n = np.ceil(M/dM) # idx =",
"= np.mean(array, axis=0) return R, C else: # 3 or 4 points #",
"or a triangular surface mesh specified as a TriRep object. - R :",
"not have well-defined solutions (i.e., they lie on spheres with inf radius). -",
"points closest to the sphere D = np.abs(np.sqrt(np.sum((Xi - C)**2, axis=1)) - R)",
"edge > thrd edge[maskOfWhite] = 255 edge[~maskOfWhite] = 0 # 提取 labeledImg =",
"edge = img_as_ubyte(rgb2gray(edge)) edge = ndi.median_filter(edge, 3) # 二值化 thrd = threshold_otsu(edge) maskOfWhite",
"import time from functools import wraps import numpy as np import scipy from",
"minimum bounding sphere D = np.sum(np.square(hull_array - C), axis=1) idx = np.argsort(D -",
"as specified above. - C : 1-by-3 vector specifying the centroid of the",
"== 255: data[data == 255] = 1 return data def project(tensor: torch.tensor, dim:",
"3600) minute, second = divmod(timeCost, 60) hour, minute, second = int(hour), int(minute), round(second,",
"x[0]))), axis=1) C = np.transpose(np.linalg.solve(A, b)) # Circle radius R = np.sqrt(np.sum(np.square(x[0] -",
"Circle radius R = np.sqrt(np.sum(np.square(x[0] - C))) # Rotate centroid back into the",
"collinearity D12 = array[1] - array[0] D12 = D12 / np.linalg.norm(D12) D13 =",
"return R, C # Check if the the points are co-planar n1 =",
"# Randomly permute the point set hull_array = np.random.permutation(hull_array) if len(hull_array) <= 4:",
"hull_array[idx[:5]] D = D[:5] Xb = Xb[D < 1E-6] idx = np.argsort(Xb[:, 0])",
"== 0: R = np.nan C = np.full(3, np.nan) return R, C #",
"**kwargs): longToWidthRatio = max(image.shape) / min(image.shape) image = transform.resize( image, (size, size //",
"tolerance < np.sum(p) <= 1 and tolerance < np.sum(q) <= 1 return jensenshannon(p,",
"C), axis=0)) return R, C @classmethod def B_min_sphere(cls, P, B): eps = 1E-6",
"Line segment elif N == 2: R = np.linalg.norm(array[1] - array[0]) / 2",
"int(minute), round(second, 1) print( f\"Function `{func.__name__}` runs for {hour}h {minute}min {second}s\") return res",
"lie on spheres with inf radius). - X : M-by-3 array of point",
"np.clip(np.abs(np.dot(n1, n2)), 0., 1.) if np.arccos(chk)/np.pi*180 < tol: R = np.inf C =",
"C = cls.fit_base(array_nd) return R, C tol = 0.01 # collinearity/co-planarity threshold (in",
"4 unique, though possibly co-linear # or co-planar points. else: # Check if",
"when the sphere is undefined, as specified above. Matlab code author: <NAME> (<EMAIL>)",
"1E-6 if len(B) == 4 or len(P) == 0: R, C = cls.fit_base(B)",
"= np.transpose(np.linalg.solve(A, b)) # Circle radius R = np.sqrt(np.sum(np.square(x[0] - C))) # Rotate",
"#Xr = np.transpose(Rmat*np.transpose(array)) Xr = np.transpose(np.dot(Rmat, np.transpose(array))) ##print(\"Xr\", Xr) # Circle centroid x",
"sphere. R=Inf when the sphere is undefined, as specified above. - C :",
"Notes in Computer Science, Vol. 555, pp. 359-370 Matlab code author: <NAME> (<EMAIL>)",
"reference C = np.append(C, [np.mean(Xr[:, 2])], axis=0) C = np.transpose(np.dot(np.transpose(Rmat), C)) return R,",
"C = array[0] return R, C # Line segment elif N == 2:",
"dM * np.ones((1, n)) # if res > 0: # idx[-1] = res",
"= np.arccos(n[2]) * r / np.linalg.norm(r) ##print(\"r\", r) Rmat = scipy.linalg.expm(np.array([ [0., -r[2],",
"K-by-3 list of point coordinates from which R and C were computed. See",
"b = np.sum( (np.square(x[1:]) - np.square(np.full(2, x[0]))), axis=1) C = np.transpose(np.linalg.solve(A, b)) #",
"with inf radius). - X : M-by-3 array of point coordinates, where M<=4.",
"back into the original frame of reference C = np.append(C, [np.mean(Xr[:, 2])], axis=0)",
"print(Xb) # print(D) #print(np.where(D/R < 1e-3)[0]) Xb = np.take(Xb, np.where(D/R < 1e-3)[0], axis=0)",
"TVSHelper: @staticmethod def getOutline(imgFile=\"img.jpg\"): img = io.imread(imgFile, as_gray=True) # 检测到边缘并进行滤波 edge = filters.sobel(img)",
"dtype=np.uint8) initRowInd, initColInd = ( np.array(cube.shape) - np.array(image.shape))//2 cube[initRowInd:initRowInd+image.shape[0], initColInd:initColInd+image.shape[1]] = image return",
"chk = True else: chk = np.linalg.norm(p - C) > (R + eps)",
"- np.full(len(array)-1, array[0])) b = np.sum( (np.square(array[1:]) - np.square(np.full(len(array)-1, array[0]))), axis=1) C =",
"x[0])) b = np.sum( (np.square(x[1:]) - np.square(np.full(2, x[0]))), axis=1) C = np.transpose(np.linalg.solve(A, b))",
"r = np.cross(n, np.array([0, 0, 1])) if np.linalg.norm(r) != 0: # Euler rotation",
"class Entropy: def __init__(self) -> None: pass @staticmethod def JSDivergence(p, q, tolerance=0.98, base=2):",
"359-370 Matlab code author: <NAME> (<EMAIL>) Date: Dec.2014\"\"\" # Get the convex hull",
"True else: chk = np.linalg.norm(p - C) > (R + eps) if chk:",
"C # Line segment elif N == 2: R = np.linalg.norm(array[1] - array[0])",
"import threshold_otsu from skimage import measure, transform from scipy import ndimage as ndi",
"# 二值化 thrd = threshold_otsu(edge) maskOfWhite = edge > thrd edge[maskOfWhite] = 255",
"res > 0: # idx[-1] = res # # if res <= 0.25",
"# A single point elif N == 1: R = 0. C =",
"sourcePath.endswith('.npz'): data = torch.from_numpy(np.load(sourcePath)[keyword]) if data.max() == 255: data[data == 255] = 1",
"parameters of the # minimum bounding sphere D = np.sum(np.square(hull_array - C), axis=1)",
"array of point coordinates, where M<=4. - R : radius of the sphere.",
"start = time.time() res = func(*args, **kwargs) end = time.time() timeCost = end",
"or R < eps: chk = True else: chk = np.linalg.norm(p - C)",
"(<EMAIL>) Date: Dec.2014\"\"\" # Get the convex hull of the point set hull",
"compute parameters of the # minimum bounding sphere D = np.sum(np.square(hull_array - C),",
"3) # 二值化 thrd = threshold_otsu(edge) maskOfWhite = edge > thrd edge[maskOfWhite] =",
"len(hull_array) dM = min([M // 4, 300]) # unnecessary ? # res =",
"!= 0: # Euler rotation vector r = np.arccos(n[2]) * r / np.linalg.norm(r)",
"end - start hour, timeCost = divmod(timeCost, 3600) minute, second = divmod(timeCost, 60)",
"= P[:-1].copy() p = P[-1].copy() # Check if p is on or inside",
"sphere R = np.sqrt(np.sum(np.square(array[0] - C), axis=0)) return R, C @classmethod def B_min_sphere(cls,",
"edge = filters.sobel(img) edge = img_as_ubyte(rgb2gray(edge)) edge = ndi.median_filter(edge, 3) # 二值化 thrd",
"to boundary points return R, C, P # Remove the last (i.e., end)",
"algorithm. - X : M-by-3 list of point co-ordinates or a triangular surface",
"C, Xi = cls.B_min_sphere( np.vstack([Xb, hull_array[i]]), []) # 40 points closest to the",
"from functools import wraps import numpy as np import scipy from scipy.spatial import",
"np.array_split(hull_array, dM) Xb = np.empty([0, 3]) for i in range(len(hull_array)): R, C, Xi",
"< np.sum(q) <= 1 return jensenshannon(p, q, base=base) if __name__ == '__main__': pass",
"torch.from_numpy(np.load(sourcePath)) elif sourcePath.endswith('.npz'): data = torch.from_numpy(np.load(sourcePath)[keyword]) if data.max() == 255: data[data == 255]",
"bounding sphere D = np.sum(np.square(hull_array - C), axis=1) idx = np.argsort(D - R**2)",
"# idx = idx[:-1] # n -= 1 hull_array = np.array_split(hull_array, dM) Xb",
"3 collinear or 4 coplanar points do not have well-defined solutions (i.e., they",
"hull_array = np.array_split(hull_array, dM) Xb = np.empty([0, 3]) for i in range(len(hull_array)): R,",
"M-by-3 array of point coordinates, where M<=4. - R : radius of the",
"n)) # if res > 0: # idx[-1] = res # # if",
"Date: Dec.2014\"\"\" # Get the convex hull of the point set hull =",
"else: M = len(hull_array) dM = min([M // 4, 300]) # unnecessary ?",
"collinear or 4 coplanar points do not have well-defined solutions (i.e., they lie",
"axis=0) return R, C, P def timer(func): \"\"\"Decorator that reports the function execution",
"last (i.e., end) point, p, from the list P_new = P[:-1].copy() p =",
"time.time() timeCost = end - start hour, timeCost = divmod(timeCost, 3600) minute, second",
"Matlab code author: <NAME> (<EMAIL>) Date: Dec.2014\"\"\" # Get the convex hull of",
"chk = np.linalg.norm(p - C) > (R + eps) if chk: if len(B)",
"0: R = np.nan C = np.full(3, np.nan) return R, C # A",
"R, C # Centroid of the sphere A = 2 * (array[1:] -",
"C @classmethod def B_min_sphere(cls, P, B): eps = 1E-6 if len(B) == 4",
"r) Rmat = scipy.linalg.expm(np.array([ [0., -r[2], r[1]], [r[2], 0., -r[0]], [-r[1], r[0], 0.]",
"0]) Xb = Xb[idx] return R, C, Xb # except: #raise Exception else:",
"= idx[n-2] + idx[n-1] # idx = idx[:-1] # n -= 1 hull_array",
"torch.max(tensor, dim=dim).values class TVSHelper: @staticmethod def getOutline(imgFile=\"img.jpg\"): img = io.imread(imgFile, as_gray=True) # 检测到边缘并进行滤波",
"initColInd:initColInd+image.shape[1]] = image return cube class Circumsphere: \"\"\"Copied from GitHub at https://github.com/shrx/mbsc.git, not",
"np.inf C = np.full(3, np.nan) return R, C # Centroid of the sphere",
"the point set hull_array = np.random.permutation(hull_array) if len(hull_array) <= 4: R, C =",
"return R, C, P # Remove the last (i.e., end) point, p, from",
"1E-6] idx = np.argsort(Xb[:, 0]) Xb = Xb[idx] return R, C, Xb #",
"points do not have well-defined solutions (i.e., they lie on spheres with inf",
"scipy from scipy.spatial import ConvexHull from scipy.spatial.distance import jensenshannon from skimage import io,",
"data = torch.from_numpy(np.load(sourcePath)[keyword]) if data.max() == 255: data[data == 255] = 1 return",
"# idx = dM * np.ones((1, n)) # if res > 0: #",
"C), axis=1) idx = np.argsort(D - R**2) D = D[idx] Xb = hull_array[idx[:5]]",
"= uniq[index.argsort()] if not np.array_equal(array, array_nd): print(\"found duplicate\") print(array_nd) R, C = cls.fit_base(array_nd)",
": M-by-3 array of point coordinates, where M<=4. - R : radius of",
"(i.e., end) point, p, from the list P_new = P[:-1].copy() p = P[-1].copy()",
"= divmod(timeCost, 3600) minute, second = divmod(timeCost, 60) hour, minute, second = int(hour),",
"np.sort(D, axis=0)[:4] # print(Xb) # print(D) #print(np.where(D/R < 1e-3)[0]) Xb = np.take(Xb, np.where(D/R",
"-= 1 hull_array = np.array_split(hull_array, dM) Xb = np.empty([0, 3]) for i in",
"of point coordinates, with N<=4') return # Empty set elif N == 0:",
"Xi[idx[:40]] D = np.sort(D, axis=0)[:4] # print(Xb) # print(D) #print(np.where(D/R < 1e-3)[0]) Xb",
"1 hull_array = np.array_split(hull_array, dM) Xb = np.empty([0, 3]) for i in range(len(hull_array)):",
"- Xb : subset of X, listing K-by-3 list of point coordinates from",
"> 4: print('Input must a N-by-3 array of point coordinates, with N<=4') return",
"# 40 points closest to the sphere D = np.abs(np.sqrt(np.sum((Xi - C)**2, axis=1))",
"points. else: # Check if the the points are co-linear D12 = array[1]",
"plane formed by the points parallel with the xy-plane n = np.cross(D13, D12)",
"of a 3D point cloud (or a triangular surface mesh) using Welzl's algorithm.",
"author: <NAME> (<EMAIL>) Date: Dec.2014\"\"\" N = len(array) if N > 4: print('Input",
"_ = cls.B_min_sphere(P_new, B) P = np.insert(P_new.copy(), 0, p, axis=0) return R, C,",
"Xb[idx] return R, C, Xb # except: #raise Exception else: M = len(hull_array)",
"C, P # Remove the last (i.e., end) point, p, from the list",
"= ConvexHull(array) hull_array = array[hull.vertices] hull_array = np.unique(hull_array, axis=0) # print(len(hull_array)) # Randomly",
"tol: R = np.inf C = np.full(3, np.nan) return R, C # Make",
"filters.sobel(img) edge = img_as_ubyte(rgb2gray(edge)) edge = ndi.median_filter(edge, 3) # 二值化 thrd = threshold_otsu(edge)",
"# Coordiantes of the points used to compute parameters of the # minimum",
"from skimage.color import rgb2gray from skimage.util import img_as_ubyte from skimage.filters import threshold_otsu from",
"Xb # except: #raise Exception else: M = len(hull_array) dM = min([M //",
": radius of the sphere. - C : 1-by-3 vector specifying the centroid",
"np.linalg.norm(n) ##print(\"n\", n) r = np.cross(n, np.array([0, 0, 1])) if np.linalg.norm(r) != 0:",
"part of the new boundary. R, C, P_new = cls.B_min_sphere(P_new, B) if np.isnan(R)",
"be # part of the new boundary. R, C, P_new = cls.B_min_sphere(P_new, B)",
"undefined, as specified above. - C : 1-by-3 vector specifying the centroid of",
"# Remove duplicate vertices, if there are any uniq, index = np.unique(array, axis=0,",
"def __init__(self) -> None: pass @staticmethod def JSDivergence(p, q, tolerance=0.98, base=2): assert tolerance",
"end) point, p, from the list P_new = P[:-1].copy() p = P[-1].copy() #",
"sphere A = 2 * (array[1:] - np.full(len(array)-1, array[0])) b = np.sum( (np.square(array[1:])",
"if len(hull_array) <= 4: R, C = cls.fit_base(hull_array) return R, C, hull_array elif",
"= np.sort(Xb, axis=0) # print(Xb) return R, C, Xb @classmethod def fit_base(cls, array):",
"<= 0.25 * dM: # idx[n-2] = idx[n-2] + idx[n-1] # idx =",
"M-by-3 list of point co-ordinates or a triangular surface mesh specified as a",
"as_gray=True) # 检测到边缘并进行滤波 edge = filters.sobel(img) edge = img_as_ubyte(rgb2gray(edge)) edge = ndi.median_filter(edge, 3)",
"< 1000: # try: R, C, _ = cls.B_min_sphere(hull_array, []) # Coordiantes of",
"= cls.fit_base(array_nd) return R, C tol = 0.01 # collinearity/co-planarity threshold (in degrees)",
"R, C, _ = cls.B_min_sphere(P_new, B) P = np.insert(P_new.copy(), 0, p, axis=0) return",
"hull_array elif len(hull_array) < 1000: # try: R, C, _ = cls.B_min_sphere(hull_array, [])",
"= Xb[idx] return R, C, Xb # except: #raise Exception else: M =",
"well-defined solutions (i.e., they lie on spheres with inf radius). - X :",
"return wrapper class Entropy: def __init__(self) -> None: pass @staticmethod def JSDivergence(p, q,",
"= 255 edge[~maskOfWhite] = 0 # 提取 labeledImg = measure.label(edge, connectivity=2) regionProps =",
"if res <= 0.25 * dM: # idx[n-2] = idx[n-2] + idx[n-1] #",
"Empty set elif N == 0: R = np.nan C = np.full(3, np.nan)",
"-> None: pass @staticmethod def JSDivergence(p, q, tolerance=0.98, base=2): assert tolerance < np.sum(p)",
"= ( np.array(cube.shape) - np.array(image.shape))//2 cube[initRowInd:initRowInd+image.shape[0], initColInd:initColInd+image.shape[1]] = image return cube class Circumsphere:",
"of the sphere. - C : 1-by-3 vector specifying the centroid of the",
"Xb = np.sort(Xb, axis=0) # print(Xb) return R, C, Xb @classmethod def fit_base(cls,",
"A single point elif N == 1: R = 0. C = array[0]",
"project(tensor: torch.tensor, dim: int): return torch.max(tensor, dim=dim).values class TVSHelper: @staticmethod def getOutline(imgFile=\"img.jpg\"): img",
"the points parallel with the xy-plane n = np.cross(D13, D12) n = n",
"JSDivergence(p, q, tolerance=0.98, base=2): assert tolerance < np.sum(p) <= 1 and tolerance <",
"specifying the centroid of the sphere. - Xb : subset of X, listing",
"return R, C # Make plane formed by the points parallel with the",
"centroid x = Xr[:, :2] A = 2 * (x[1:] - np.full(2, x[0]))",
"labeledImg = measure.label(edge, connectivity=2) regionProps = measure.regionprops(labeledImg) regionProps.sort(key=lambda prop: prop.area, reverse=True) targetImage =",
"the centroid of the sphere. C=nan(1,3) when the sphere is undefined, as specified",
"# Line segment elif N == 2: R = np.linalg.norm(array[1] - array[0]) /",
"dM = min([M // 4, 300]) # unnecessary ? # res = M",
"= np.clip(np.abs(np.dot(D12, D13)), 0., 1.) chk2 = np.clip(np.abs(np.dot(D12, D14)), 0., 1.) if np.arccos(chk1)/np.pi*180",
"hull_array = np.random.permutation(hull_array) if len(hull_array) <= 4: R, C = cls.fit_base(hull_array) return R,",
"measure, transform from scipy import ndimage as ndi import torch def loadNnData(sourcePath, keyword:",
"# Euler rotation vector r = np.arccos(n[2]) * r / np.linalg.norm(r) ##print(\"r\", r)",
"D13)), 0., 1.) if np.arccos(chk)/np.pi*180 < tol: R = np.inf C = np.full(3,",
"the points used to compute parameters of the # minimum bounding sphere D",
"255 edge[~maskOfWhite] = 0 # 提取 labeledImg = measure.label(edge, connectivity=2) regionProps = measure.regionprops(labeledImg)",
"= D14 / np.linalg.norm(D14) chk1 = np.clip(np.abs(np.dot(D12, D13)), 0., 1.) chk2 = np.clip(np.abs(np.dot(D12,",
"at most 4 points in 3D space. Note that point configurations with 3",
"getOutline(imgFile=\"img.jpg\"): img = io.imread(imgFile, as_gray=True) # 检测到边缘并进行滤波 edge = filters.sobel(img) edge = img_as_ubyte(rgb2gray(edge))",
"# If we got to this point then we have 4 unique, though",
"collinearity/co-planarity threshold (in degrees) if N == 3: # Check for collinearity D12",
"single point elif N == 1: R = 0. C = array[0] return",
"specified above. - C : 1-by-3 vector specifying the centroid of the sphere.",
"axis=0) Xb = np.sort(Xb, axis=0) # print(Xb) return R, C, Xb @classmethod def",
"np.vstack([Xb, hull_array[i]]), []) # 40 points closest to the sphere D = np.abs(np.sqrt(np.sum((Xi",
"of the # minimum bounding sphere D = np.sum(np.square(hull_array - C), axis=1) idx",
"res <= 0.25 * dM: # idx[n-2] = idx[n-2] + idx[n-1] # idx",
"(1991), 'Smallest enclosing disks (balls and ellipsoids)', Lecture Notes in Computer Science, Vol.",
"C=nan(1,3) when the sphere is undefined, as specified above. Matlab code author: <NAME>",
"not, it must be # part of the new boundary. R, C, P_new",
"B = np.array(np.insert(B, 0, p, axis=0)) R, C, _ = cls.B_min_sphere(P_new, B) P",
"1-by-3 vector specifying the centroid of the sphere. C=nan(1,3) when the sphere is",
"= np.clip(np.abs(np.dot(D12, D14)), 0., 1.) if np.arccos(chk1)/np.pi*180 < tol or np.arccos(chk2)/np.pi*180 < tol:",
"Randomly permute the point set hull_array = np.random.permutation(hull_array) if len(hull_array) <= 4: R,",
"a sphere to a set of 2, 3, or at most 4 points",
"# Rotate centroid back into the original frame of reference C = np.append(C,",
"not my original. \"\"\" @classmethod def fit(cls, array): \"\"\"Compute exact minimum bounding sphere",
"if N == 3: # Check for collinearity D12 = array[1] - array[0]",
"P[-1].copy() # Check if p is on or inside the bounding sphere. If",
"co-linear D12 = array[1] - array[0] D12 = D12 / np.linalg.norm(D12) D13 =",
"a TriRep object. - R : radius of the sphere. - C :",
"when the sphere is undefined, as specified above. - C : 1-by-3 vector",
"= np.linalg.norm(np.cross(D12, D14)) chk = np.clip(np.abs(np.dot(n1, n2)), 0., 1.) if np.arccos(chk)/np.pi*180 < tol:",
"import jensenshannon from skimage import io, filters from skimage.color import rgb2gray from skimage.util",
"array[0]) / 2 C = np.mean(array, axis=0) return R, C else: # 3",
"R < eps: chk = True else: chk = np.linalg.norm(p - C) >",
"= np.inf C = np.full(3, np.nan) return R, C # Make plane formed",
"spheres with inf radius). - X : M-by-3 array of point coordinates, where",
"inside the bounding sphere. If not, it must be # part of the",
"r = np.arccos(n[2]) * r / np.linalg.norm(r) ##print(\"r\", r) Rmat = scipy.linalg.expm(np.array([ [0.,",
"n) r = np.cross(n, np.array([0, 0, 1])) if np.linalg.norm(r) != 0: # Euler",
"D = D[:5] Xb = Xb[D < 1E-6] idx = np.argsort(Xb[:, 0]) Xb",
"= Xi[idx[:40]] D = np.sort(D, axis=0)[:4] # print(Xb) # print(D) #print(np.where(D/R < 1e-3)[0])",
": radius of the sphere. R=Inf when the sphere is undefined, as specified",
"chk = np.clip(np.abs(np.dot(n1, n2)), 0., 1.) if np.arccos(chk)/np.pi*180 < tol: R = np.inf",
"above. - C : 1-by-3 vector specifying the centroid of the sphere. C=nan(1,3)",
"ellipsoids)', Lecture Notes in Computer Science, Vol. 555, pp. 359-370 Matlab code author:",
"data.max() == 255: data[data == 255] = 1 return data def project(tensor: torch.tensor,",
"print(Xb) return R, C, Xb @classmethod def fit_base(cls, array): \"\"\"Fit a sphere to",
"Xr) # Circle centroid x = Xr[:, :2] A = 2 * (x[1:]",
"np.transpose(Rmat*np.transpose(array)) Xr = np.transpose(np.dot(Rmat, np.transpose(array))) ##print(\"Xr\", Xr) # Circle centroid x = Xr[:,",
"the original frame of reference C = np.append(C, [np.mean(Xr[:, 2])], axis=0) C =",
"sphere. - Xb : subset of X, listing K-by-3 list of point coordinates",
"# collinearity/co-planarity threshold (in degrees) if N == 3: # Check for collinearity",
"0.01 # collinearity/co-planarity threshold (in degrees) if N == 3: # Check for",
"Xb = np.empty([0, 3]) for i in range(len(hull_array)): R, C, Xi = cls.B_min_sphere(",
"of the sphere. C=nan(1,3) when the sphere is undefined, as specified above. Matlab",
"Xb = np.take(Xb, np.where(D/R < 1e-3)[0], axis=0) Xb = np.sort(Xb, axis=0) # print(Xb)",
"of point coordinates from which R and C were computed. See function titled",
"= divmod(timeCost, 60) hour, minute, second = int(hour), int(minute), round(second, 1) print( f\"Function",
"cls.B_min_sphere(P_new, B) if np.isnan(R) or np.isinf(R) or R < eps: chk = True",
"- X : M-by-3 list of point co-ordinates or a triangular surface mesh",
"== 0: R, C = cls.fit_base(B) # fit sphere to boundary points return",
"C tol = 0.01 # collinearity/co-planarity threshold (in degrees) if N == 3:",
"import ConvexHull from scipy.spatial.distance import jensenshannon from skimage import io, filters from skimage.color",
"= np.linalg.norm(np.cross(D12, D13)) n2 = np.linalg.norm(np.cross(D12, D14)) chk = np.clip(np.abs(np.dot(n1, n2)), 0., 1.)",
"undefined, as specified above. Matlab code author: <NAME> (<EMAIL>) Date: Dec.2014\"\"\" N =",
"= np.cross(n, np.array([0, 0, 1])) if np.linalg.norm(r) != 0: # Euler rotation vector",
"4 coplanar points do not have well-defined solutions (i.e., they lie on spheres",
"unique, though possibly co-linear # or co-planar points. else: # Check if the",
"Xb = Xb[idx] return R, C, Xb # except: #raise Exception else: M",
"= cls.B_min_sphere(hull_array, []) # Coordiantes of the points used to compute parameters of",
"np.sum(np.square(hull_array - C), axis=1) idx = np.argsort(D - R**2) D = D[idx] Xb",
"X, listing K-by-3 list of point coordinates from which R and C were",
"R, C # If we got to this point then we have 4",
"size=48, **kwargs): longToWidthRatio = max(image.shape) / min(image.shape) image = transform.resize( image, (size, size",
"= np.sqrt(np.sum(np.square(x[0] - C))) # Rotate centroid back into the original frame of",
"[]) # Coordiantes of the points used to compute parameters of the #",
"= transform.resize( image, (size, size // longToWidthRatio), **kwargs) cube = np.zeros((64, 64), dtype=np.uint8)",
"D14 = D14 / np.linalg.norm(D14) chk1 = np.clip(np.abs(np.dot(D12, D13)), 0., 1.) chk2 =",
"idx = dM * np.ones((1, n)) # if res > 0: # idx[-1]",
"it must be # part of the new boundary. R, C, P_new =",
"array[1] - array[0] D12 = D12 / np.linalg.norm(D12) D13 = array[2] - array[0]",
"np.cross(D13, D12) n = n / np.linalg.norm(n) ##print(\"n\", n) r = np.cross(n, np.array([0,",
"= 1E-6 if len(B) == 4 or len(P) == 0: R, C =",
"np.linalg.norm(r) ##print(\"r\", r) Rmat = scipy.linalg.expm(np.array([ [0., -r[2], r[1]], [r[2], 0., -r[0]], [-r[1],",
"bounding sphere. If not, it must be # part of the new boundary.",
"np.transpose(np.linalg.solve(A, b)) # Radius of the sphere R = np.sqrt(np.sum(np.square(array[0] - C), axis=0))",
"dim: int): return torch.max(tensor, dim=dim).values class TVSHelper: @staticmethod def getOutline(imgFile=\"img.jpg\"): img = io.imread(imgFile,",
"Dec.2014\"\"\" # Get the convex hull of the point set hull = ConvexHull(array)",
"np.full(3, np.nan) return R, C # A single point elif N == 1:",
"# 3 or 4 points # Remove duplicate vertices, if there are any",
"D13)) n2 = np.linalg.norm(np.cross(D12, D14)) chk = np.clip(np.abs(np.dot(n1, n2)), 0., 1.) if np.arccos(chk)/np.pi*180",
"- R : radius of the sphere. R=Inf when the sphere is undefined,",
"coordinates, where M<=4. - R : radius of the sphere. R=Inf when the",
"ndi import torch def loadNnData(sourcePath, keyword: str = None) -> torch.Tensor: if sourcePath.endswith('.npy'):",
"(<EMAIL>) Date: Dec.2014\"\"\" N = len(array) if N > 4: print('Input must a",
"Xb @classmethod def fit_base(cls, array): \"\"\"Fit a sphere to a set of 2,",
"None) -> torch.Tensor: if sourcePath.endswith('.npy'): data = torch.from_numpy(np.load(sourcePath)) elif sourcePath.endswith('.npz'): data = torch.from_numpy(np.load(sourcePath)[keyword])",
"R=Inf when the sphere is undefined, as specified above. - C : 1-by-3",
"chk2 = np.clip(np.abs(np.dot(D12, D14)), 0., 1.) if np.arccos(chk1)/np.pi*180 < tol or np.arccos(chk2)/np.pi*180 <",
"data def project(tensor: torch.tensor, dim: int): return torch.max(tensor, dim=dim).values class TVSHelper: @staticmethod def",
"= np.argsort(D - R**2) D = D[idx] Xb = hull_array[idx[:5]] D = D[:5]",
"N == 0: R = np.nan C = np.full(3, np.nan) return R, C",
"= np.random.permutation(hull_array) if len(hull_array) <= 4: R, C = cls.fit_base(hull_array) return R, C,",
"R : radius of the sphere. R=Inf when the sphere is undefined, as",
"C, P def timer(func): \"\"\"Decorator that reports the function execution time. \"\"\" @wraps(func)",
"C, P_new = cls.B_min_sphere(P_new, B) if np.isnan(R) or np.isinf(R) or R < eps:",
"0., 1.) if np.arccos(chk1)/np.pi*180 < tol or np.arccos(chk2)/np.pi*180 < tol: R = np.inf",
"np.transpose(np.dot(Rmat, np.transpose(array))) ##print(\"Xr\", Xr) # Circle centroid x = Xr[:, :2] A =",
"= np.ceil(M/dM) # idx = dM * np.ones((1, n)) # if res >",
"the last (i.e., end) point, p, from the list P_new = P[:-1].copy() p",
"0, p, axis=0) return R, C, P def timer(func): \"\"\"Decorator that reports the",
"array[0] D14 = D14 / np.linalg.norm(D14) chk1 = np.clip(np.abs(np.dot(D12, D13)), 0., 1.) chk2",
"point set hull_array = np.random.permutation(hull_array) if len(hull_array) <= 4: R, C = cls.fit_base(hull_array)",
"connectivity=2) regionProps = measure.regionprops(labeledImg) regionProps.sort(key=lambda prop: prop.area, reverse=True) targetImage = regionProps[0].filled_image return targetImage",
"= io.imread(imgFile, as_gray=True) # 检测到边缘并进行滤波 edge = filters.sobel(img) edge = img_as_ubyte(rgb2gray(edge)) edge =",
": M-by-3 list of point co-ordinates or a triangular surface mesh specified as",
"Exception else: M = len(hull_array) dM = min([M // 4, 300]) # unnecessary",
"np.array(np.insert(B, 0, p, axis=0)) R, C, _ = cls.B_min_sphere(P_new, B) P = np.insert(P_new.copy(),",
"torch def loadNnData(sourcePath, keyword: str = None) -> torch.Tensor: if sourcePath.endswith('.npy'): data =",
"= max(image.shape) / min(image.shape) image = transform.resize( image, (size, size // longToWidthRatio), **kwargs)",
"n2 = np.linalg.norm(np.cross(D12, D14)) chk = np.clip(np.abs(np.dot(n1, n2)), 0., 1.) if np.arccos(chk)/np.pi*180 <",
"from skimage.filters import threshold_otsu from skimage import measure, transform from scipy import ndimage",
"M = len(hull_array) dM = min([M // 4, 300]) # unnecessary ? #",
"= np.nan C = np.full(3, np.nan) return R, C # A single point",
"scipy import ndimage as ndi import torch def loadNnData(sourcePath, keyword: str = None)",
"print(\"found duplicate\") print(array_nd) R, C = cls.fit_base(array_nd) return R, C tol = 0.01",
"= np.transpose(np.linalg.solve(A, b)) # Radius of the sphere R = np.sqrt(np.sum(np.square(array[0] - C),",
"= np.abs(np.sqrt(np.sum((Xi - C)**2, axis=1)) - R) idx = np.argsort(D, axis=0) Xb =",
"3]) for i in range(len(hull_array)): R, C, Xi = cls.B_min_sphere( np.vstack([Xb, hull_array[i]]), [])",
"])) ##print(\"Rmat\", Rmat) #Xr = np.transpose(Rmat*np.transpose(array)) Xr = np.transpose(np.dot(Rmat, np.transpose(array))) ##print(\"Xr\", Xr) #",
"- np.square(np.full(len(array)-1, array[0]))), axis=1) C = np.transpose(np.linalg.solve(A, b)) # Radius of the sphere",
"divmod(timeCost, 60) hour, minute, second = int(hour), int(minute), round(second, 1) print( f\"Function `{func.__name__}`",
"R, C, Xi = cls.B_min_sphere( np.vstack([Xb, hull_array[i]]), []) # 40 points closest to",
"def timer(func): \"\"\"Decorator that reports the function execution time. \"\"\" @wraps(func) def wrapper(*args,",
"= hull_array[idx[:5]] D = D[:5] Xb = Xb[D < 1E-6] idx = np.argsort(Xb[:,",
"the point set hull = ConvexHull(array) hull_array = array[hull.vertices] hull_array = np.unique(hull_array, axis=0)",
"len(array) if N > 4: print('Input must a N-by-3 array of point coordinates,",
"0: B = np.array([p]) else: B = np.array(np.insert(B, 0, p, axis=0)) R, C,",
"hour, timeCost = divmod(timeCost, 3600) minute, second = divmod(timeCost, 60) hour, minute, second",
"x = Xr[:, :2] A = 2 * (x[1:] - np.full(2, x[0])) b",
"Vol. 555, pp. 359-370 Matlab code author: <NAME> (<EMAIL>) Date: Dec.2014\"\"\" # Get",
"= Xb[D < 1E-6] idx = np.argsort(Xb[:, 0]) Xb = Xb[idx] return R,",
"radius). - X : M-by-3 array of point coordinates, where M<=4. - R",
"axis=0) # print(Xb) return R, C, Xb @classmethod def fit_base(cls, array): \"\"\"Fit a",
"np.nan C = np.full(3, np.nan) return R, C # A single point elif",
"cls.B_min_sphere( np.vstack([Xb, hull_array[i]]), []) # 40 points closest to the sphere D =",
"r / np.linalg.norm(r) ##print(\"r\", r) Rmat = scipy.linalg.expm(np.array([ [0., -r[2], r[1]], [r[2], 0.,",
"from skimage import io, filters from skimage.color import rgb2gray from skimage.util import img_as_ubyte",
"into the original frame of reference C = np.append(C, [np.mean(Xr[:, 2])], axis=0) C",
"dM # n = np.ceil(M/dM) # idx = dM * np.ones((1, n)) #",
"sphere to a set of 2, 3, or at most 4 points in",
"D = np.sort(D, axis=0)[:4] # print(Xb) # print(D) #print(np.where(D/R < 1e-3)[0]) Xb =",
"- array[0] D13 = D13 / np.linalg.norm(D13) chk = np.clip(np.abs(np.dot(D12, D13)), 0., 1.)",
"most 4 points in 3D space. Note that point configurations with 3 collinear",
"None: pass @staticmethod def JSDivergence(p, q, tolerance=0.98, base=2): assert tolerance < np.sum(p) <=",
"= np.sqrt(np.sum(np.square(array[0] - C), axis=0)) return R, C @classmethod def B_min_sphere(cls, P, B):",
"Check if the the points are co-linear D12 = array[1] - array[0] D12",
"int): return torch.max(tensor, dim=dim).values class TVSHelper: @staticmethod def getOutline(imgFile=\"img.jpg\"): img = io.imread(imgFile, as_gray=True)",
"- R**2) D = D[idx] Xb = hull_array[idx[:5]] D = D[:5] Xb =",
"R = np.sqrt(np.sum(np.square(array[0] - C), axis=0)) return R, C @classmethod def B_min_sphere(cls, P,",
"if the the points are co-linear D12 = array[1] - array[0] D12 =",
"to this point then we have 4 unique, though possibly co-linear # or",
"P_new = P[:-1].copy() p = P[-1].copy() # Check if p is on or",
"# 提取 labeledImg = measure.label(edge, connectivity=2) regionProps = measure.regionprops(labeledImg) regionProps.sort(key=lambda prop: prop.area, reverse=True)",
"1.) if np.arccos(chk)/np.pi*180 < tol: R = np.inf C = np.full(3, np.nan) return",
"return_index=True) array_nd = uniq[index.argsort()] if not np.array_equal(array, array_nd): print(\"found duplicate\") print(array_nd) R, C",
"= edge > thrd edge[maskOfWhite] = 255 edge[~maskOfWhite] = 0 # 提取 labeledImg",
"/ np.linalg.norm(r) ##print(\"r\", r) Rmat = scipy.linalg.expm(np.array([ [0., -r[2], r[1]], [r[2], 0., -r[0]],",
"n / np.linalg.norm(n) ##print(\"n\", n) r = np.cross(n, np.array([0, 0, 1])) if np.linalg.norm(r)",
"the # minimum bounding sphere D = np.sum(np.square(hull_array - C), axis=1) idx =",
"return R, C else: # 3 or 4 points # Remove duplicate vertices,",
"the centroid of the sphere. - Xb : subset of X, listing K-by-3",
"for {hour}h {minute}min {second}s\") return res return wrapper class Entropy: def __init__(self) ->",
"0: # Euler rotation vector r = np.arccos(n[2]) * r / np.linalg.norm(r) ##print(\"r\",",
"C = np.transpose(np.linalg.solve(A, b)) # Radius of the sphere R = np.sqrt(np.sum(np.square(array[0] -",
"- array[0] D13 = D13 / np.linalg.norm(D13) D14 = array[3] - array[0] D14",
"n2)), 0., 1.) if np.arccos(chk)/np.pi*180 < tol: R = np.inf C = np.full(3,",
"C = cls.fit_base(hull_array) return R, C, hull_array elif len(hull_array) < 1000: # try:",
"> (R + eps) if chk: if len(B) == 0: B = np.array([p])",
"f\"Function `{func.__name__}` runs for {hour}h {minute}min {second}s\") return res return wrapper class Entropy:",
"p, axis=0)) R, C, _ = cls.B_min_sphere(P_new, B) P = np.insert(P_new.copy(), 0, p,",
"== 4 or len(P) == 0: R, C = cls.fit_base(B) # fit sphere",
"# print(Xb) return R, C, Xb @classmethod def fit_base(cls, array): \"\"\"Fit a sphere",
"that reports the function execution time. \"\"\" @wraps(func) def wrapper(*args, **kwargs): start =",
"? # res = M % dM # n = np.ceil(M/dM) # idx",
"minute, second = divmod(timeCost, 60) hour, minute, second = int(hour), int(minute), round(second, 1)",
"0: # idx[-1] = res # # if res <= 0.25 * dM:",
"def getOutline(imgFile=\"img.jpg\"): img = io.imread(imgFile, as_gray=True) # 检测到边缘并进行滤波 edge = filters.sobel(img) edge =",
"a N-by-3 array of point coordinates, with N<=4') return # Empty set elif",
"+ eps) if chk: if len(B) == 0: B = np.array([p]) else: B",
"P_new = cls.B_min_sphere(P_new, B) if np.isnan(R) or np.isinf(R) or R < eps: chk",
"np.nan) return R, C # A single point elif N == 1: R",
"1e-3)[0]) Xb = np.take(Xb, np.where(D/R < 1e-3)[0], axis=0) Xb = np.sort(Xb, axis=0) #",
"jensenshannon from skimage import io, filters from skimage.color import rgb2gray from skimage.util import",
"4 or len(P) == 0: R, C = cls.fit_base(B) # fit sphere to",
"def B_min_sphere(cls, P, B): eps = 1E-6 if len(B) == 4 or len(P)",
"np.sqrt(np.sum(np.square(array[0] - C), axis=0)) return R, C @classmethod def B_min_sphere(cls, P, B): eps",
"N == 1: R = 0. C = array[0] return R, C #",
"[r[2], 0., -r[0]], [-r[1], r[0], 0.] ])) ##print(\"Rmat\", Rmat) #Xr = np.transpose(Rmat*np.transpose(array)) Xr",
"they lie on spheres with inf radius). - X : M-by-3 array of",
"Check for collinearity D12 = array[1] - array[0] D12 = D12 / np.linalg.norm(D12)",
"the points are co-planar n1 = np.linalg.norm(np.cross(D12, D13)) n2 = np.linalg.norm(np.cross(D12, D14)) chk",
"2 C = np.mean(array, axis=0) return R, C else: # 3 or 4",
"C : 1-by-3 vector specifying the centroid of the sphere. C=nan(1,3) when the",
"= None) -> torch.Tensor: if sourcePath.endswith('.npy'): data = torch.from_numpy(np.load(sourcePath)) elif sourcePath.endswith('.npz'): data =",
"co-planar points. else: # Check if the the points are co-linear D12 =",
"wrapper(*args, **kwargs): start = time.time() res = func(*args, **kwargs) end = time.time() timeCost",
"np.zeros((64, 64), dtype=np.uint8) initRowInd, initColInd = ( np.array(cube.shape) - np.array(image.shape))//2 cube[initRowInd:initRowInd+image.shape[0], initColInd:initColInd+image.shape[1]] =",
"P, B): eps = 1E-6 if len(B) == 4 or len(P) == 0:",
"= np.sum( (np.square(x[1:]) - np.square(np.full(2, x[0]))), axis=1) C = np.transpose(np.linalg.solve(A, b)) # Circle",
"of the sphere A = 2 * (array[1:] - np.full(len(array)-1, array[0])) b =",
"- C), axis=0)) return R, C @classmethod def B_min_sphere(cls, P, B): eps =",
"= filters.sobel(img) edge = img_as_ubyte(rgb2gray(edge)) edge = ndi.median_filter(edge, 3) # 二值化 thrd =",
"= np.full(3, np.nan) return R, C # A single point elif N ==",
"timeCost = end - start hour, timeCost = divmod(timeCost, 3600) minute, second =",
"= res # # if res <= 0.25 * dM: # idx[n-2] =",
"the sphere. C=nan(1,3) when the sphere is undefined, as specified above. Matlab code",
"return # Empty set elif N == 0: R = np.nan C =",
"point elif N == 1: R = 0. C = array[0] return R,",
"# Get the convex hull of the point set hull = ConvexHull(array) hull_array",
"with N<=4') return # Empty set elif N == 0: R = np.nan",
"sphere D = np.sum(np.square(hull_array - C), axis=1) idx = np.argsort(D - R**2) D",
"3, or at most 4 points in 3D space. Note that point configurations",
"= np.unique(hull_array, axis=0) # print(len(hull_array)) # Randomly permute the point set hull_array =",
"regionProps[0].filled_image return targetImage @staticmethod def putIntoCube(image, size=48, **kwargs): longToWidthRatio = max(image.shape) / min(image.shape)",
"= cls.B_min_sphere( np.vstack([Xb, hull_array[i]]), []) # 40 points closest to the sphere D",
"2 * (array[1:] - np.full(len(array)-1, array[0])) b = np.sum( (np.square(array[1:]) - np.square(np.full(len(array)-1, array[0]))),",
"array_nd): print(\"found duplicate\") print(array_nd) R, C = cls.fit_base(array_nd) return R, C tol =",
"print( f\"Function `{func.__name__}` runs for {hour}h {minute}min {second}s\") return res return wrapper class",
"return R, C, hull_array elif len(hull_array) < 1000: # try: R, C, _",
"data[data == 255] = 1 return data def project(tensor: torch.tensor, dim: int): return",
"vector specifying the centroid of the sphere. C=nan(1,3) when the sphere is undefined,",
"def project(tensor: torch.tensor, dim: int): return torch.max(tensor, dim=dim).values class TVSHelper: @staticmethod def getOutline(imgFile=\"img.jpg\"):",
"skimage.color import rgb2gray from skimage.util import img_as_ubyte from skimage.filters import threshold_otsu from skimage",
"ConvexHull from scipy.spatial.distance import jensenshannon from skimage import io, filters from skimage.color import",
"(R + eps) if chk: if len(B) == 0: B = np.array([p]) else:",
"np.ones((1, n)) # if res > 0: # idx[-1] = res # #",
"- array[0]) / 2 C = np.mean(array, axis=0) return R, C else: #",
"D12) n = n / np.linalg.norm(n) ##print(\"n\", n) r = np.cross(n, np.array([0, 0,",
"GitHub at https://github.com/shrx/mbsc.git, not my original. \"\"\" @classmethod def fit(cls, array): \"\"\"Compute exact",
"convex hull of the point set hull = ConvexHull(array) hull_array = array[hull.vertices] hull_array",
"= 2 * (x[1:] - np.full(2, x[0])) b = np.sum( (np.square(x[1:]) - np.square(np.full(2,",
"[-r[1], r[0], 0.] ])) ##print(\"Rmat\", Rmat) #Xr = np.transpose(Rmat*np.transpose(array)) Xr = np.transpose(np.dot(Rmat, np.transpose(array)))",
"if N > 4: print('Input must a N-by-3 array of point coordinates, with",
"/ np.linalg.norm(D12) D13 = array[2] - array[0] D13 = D13 / np.linalg.norm(D13) D14",
"4 points # Remove duplicate vertices, if there are any uniq, index =",
"= np.transpose(Rmat*np.transpose(array)) Xr = np.transpose(np.dot(Rmat, np.transpose(array))) ##print(\"Xr\", Xr) # Circle centroid x =",
"n -= 1 hull_array = np.array_split(hull_array, dM) Xb = np.empty([0, 3]) for i",
"/ min(image.shape) image = transform.resize( image, (size, size // longToWidthRatio), **kwargs) cube =",
"np.square(np.full(2, x[0]))), axis=1) C = np.transpose(np.linalg.solve(A, b)) # Circle radius R = np.sqrt(np.sum(np.square(x[0]",
"R, C, P # Remove the last (i.e., end) point, p, from the",
"{minute}min {second}s\") return res return wrapper class Entropy: def __init__(self) -> None: pass",
"above. Matlab code author: <NAME> (<EMAIL>) Date: Dec.2014\"\"\" N = len(array) if N",
"res = func(*args, **kwargs) end = time.time() timeCost = end - start hour,",
"if sourcePath.endswith('.npy'): data = torch.from_numpy(np.load(sourcePath)) elif sourcePath.endswith('.npz'): data = torch.from_numpy(np.load(sourcePath)[keyword]) if data.max() ==",
"- R : radius of the sphere. - C : 1-by-3 vector specifying",
"np.transpose(np.dot(np.transpose(Rmat), C)) return R, C # If we got to this point then",
"<NAME> (<EMAIL>) Date: Dec.2014\"\"\" # Get the convex hull of the point set",
"cls.B_min_sphere(hull_array, []) # Coordiantes of the points used to compute parameters of the",
"= time.time() res = func(*args, **kwargs) end = time.time() timeCost = end -",
"q, tolerance=0.98, base=2): assert tolerance < np.sum(p) <= 1 and tolerance < np.sum(q)",
"filters from skimage.color import rgb2gray from skimage.util import img_as_ubyte from skimage.filters import threshold_otsu",
"hull_array = array[hull.vertices] hull_array = np.unique(hull_array, axis=0) # print(len(hull_array)) # Randomly permute the",
"> 0: # idx[-1] = res # # if res <= 0.25 *",
"return R, C, Xb @classmethod def fit_base(cls, array): \"\"\"Fit a sphere to a",
"(x[1:] - np.full(2, x[0])) b = np.sum( (np.square(x[1:]) - np.square(np.full(2, x[0]))), axis=1) C",
"0 # 提取 labeledImg = measure.label(edge, connectivity=2) regionProps = measure.regionprops(labeledImg) regionProps.sort(key=lambda prop: prop.area,",
"idx[n-1] # idx = idx[:-1] # n -= 1 hull_array = np.array_split(hull_array, dM)",
"and ellipsoids)', Lecture Notes in Computer Science, Vol. 555, pp. 359-370 Matlab code",
"D12 = D12 / np.linalg.norm(D12) D13 = array[2] - array[0] D13 = D13",
"np.random.permutation(hull_array) if len(hull_array) <= 4: R, C = cls.fit_base(hull_array) return R, C, hull_array",
"tol: R = np.inf C = np.full(3, np.nan) return R, C # Check",
"n = np.cross(D13, D12) n = n / np.linalg.norm(n) ##print(\"n\", n) r =",
"= 1 return data def project(tensor: torch.tensor, dim: int): return torch.max(tensor, dim=dim).values class",
"D14 = array[3] - array[0] D14 = D14 / np.linalg.norm(D14) chk1 = np.clip(np.abs(np.dot(D12,",
"sphere. - C : 1-by-3 vector specifying the centroid of the sphere. -",
"= np.sum(np.square(hull_array - C), axis=1) idx = np.argsort(D - R**2) D = D[idx]",
"is undefined, as specified above. - C : 1-by-3 vector specifying the centroid",
"skimage import measure, transform from scipy import ndimage as ndi import torch def",
"a set of 2, 3, or at most 4 points in 3D space.",
"R, C # Check if the the points are co-planar n1 = np.linalg.norm(np.cross(D12,",
"R = np.nan C = np.full(3, np.nan) return R, C # A single",
"= Xr[:, :2] A = 2 * (x[1:] - np.full(2, x[0])) b =",
"list of point coordinates from which R and C were computed. See function",
"[1] Welzl, E. (1991), 'Smallest enclosing disks (balls and ellipsoids)', Lecture Notes in",
"< 1e-3)[0], axis=0) Xb = np.sort(Xb, axis=0) # print(Xb) return R, C, Xb",
"= np.array([p]) else: B = np.array(np.insert(B, 0, p, axis=0)) R, C, _ =",
"= int(hour), int(minute), round(second, 1) print( f\"Function `{func.__name__}` runs for {hour}h {minute}min {second}s\")",
"C, Xb # except: #raise Exception else: M = len(hull_array) dM = min([M",
"- np.square(np.full(2, x[0]))), axis=1) C = np.transpose(np.linalg.solve(A, b)) # Circle radius R =",
"eps = 1E-6 if len(B) == 4 or len(P) == 0: R, C",
"coordinates, with N<=4') return # Empty set elif N == 0: R =",
"== 3: # Check for collinearity D12 = array[1] - array[0] D12 =",
"formed by the points parallel with the xy-plane n = np.cross(D13, D12) n",
"new boundary. R, C, P_new = cls.B_min_sphere(P_new, B) if np.isnan(R) or np.isinf(R) or",
"Xr[:, :2] A = 2 * (x[1:] - np.full(2, x[0])) b = np.sum(",
"timer(func): \"\"\"Decorator that reports the function execution time. \"\"\" @wraps(func) def wrapper(*args, **kwargs):",
"idx[-1] = res # # if res <= 0.25 * dM: # idx[n-2]",
"* (array[1:] - np.full(len(array)-1, array[0])) b = np.sum( (np.square(array[1:]) - np.square(np.full(len(array)-1, array[0]))), axis=1)",
"Dec.2014\"\"\" N = len(array) if N > 4: print('Input must a N-by-3 array",
"C # Centroid of the sphere A = 2 * (array[1:] - np.full(len(array)-1,",
"sourcePath.endswith('.npy'): data = torch.from_numpy(np.load(sourcePath)) elif sourcePath.endswith('.npz'): data = torch.from_numpy(np.load(sourcePath)[keyword]) if data.max() == 255:",
"R, C # Make plane formed by the points parallel with the xy-plane",
"2])], axis=0) C = np.transpose(np.dot(np.transpose(Rmat), C)) return R, C # If we got",
"and tolerance < np.sum(q) <= 1 return jensenshannon(p, q, base=base) if __name__ ==",
"2: R = np.linalg.norm(array[1] - array[0]) / 2 C = np.mean(array, axis=0) return",
"R, C @classmethod def B_min_sphere(cls, P, B): eps = 1E-6 if len(B) ==",
"from scipy.spatial.distance import jensenshannon from skimage import io, filters from skimage.color import rgb2gray",
"res return wrapper class Entropy: def __init__(self) -> None: pass @staticmethod def JSDivergence(p,",
"author: <NAME> (<EMAIL>) Date: Dec.2014\"\"\" # Get the convex hull of the point",
"axis=0) Xb = Xi[idx[:40]] D = np.sort(D, axis=0)[:4] # print(Xb) # print(D) #print(np.where(D/R",
"P[:-1].copy() p = P[-1].copy() # Check if p is on or inside the",
"have 4 unique, though possibly co-linear # or co-planar points. else: # Check",
"if len(B) == 4 or len(P) == 0: R, C = cls.fit_base(B) #",
"or at most 4 points in 3D space. Note that point configurations with",
"longToWidthRatio = max(image.shape) / min(image.shape) image = transform.resize( image, (size, size // longToWidthRatio),",
"A = 2 * (x[1:] - np.full(2, x[0])) b = np.sum( (np.square(x[1:]) -",
"of the sphere R = np.sqrt(np.sum(np.square(array[0] - C), axis=0)) return R, C @classmethod",
"the bounding sphere. If not, it must be # part of the new",
"1) print( f\"Function `{func.__name__}` runs for {hour}h {minute}min {second}s\") return res return wrapper",
"cls.fit_base(B) # fit sphere to boundary points return R, C, P # Remove",
"= len(hull_array) dM = min([M // 4, 300]) # unnecessary ? # res",
"#raise Exception else: M = len(hull_array) dM = min([M // 4, 300]) #",
"##print(\"Rmat\", Rmat) #Xr = np.transpose(Rmat*np.transpose(array)) Xr = np.transpose(np.dot(Rmat, np.transpose(array))) ##print(\"Xr\", Xr) # Circle",
"centroid back into the original frame of reference C = np.append(C, [np.mean(Xr[:, 2])],",
"the new boundary. R, C, P_new = cls.B_min_sphere(P_new, B) if np.isnan(R) or np.isinf(R)",
"this point then we have 4 unique, though possibly co-linear # or co-planar",
"not np.array_equal(array, array_nd): print(\"found duplicate\") print(array_nd) R, C = cls.fit_base(array_nd) return R, C",
"< eps: chk = True else: chk = np.linalg.norm(p - C) > (R",
"2, 3, or at most 4 points in 3D space. Note that point",
"np.transpose(array))) ##print(\"Xr\", Xr) # Circle centroid x = Xr[:, :2] A = 2",
"point set hull = ConvexHull(array) hull_array = array[hull.vertices] hull_array = np.unique(hull_array, axis=0) #",
"import img_as_ubyte from skimage.filters import threshold_otsu from skimage import measure, transform from scipy",
"sphere is undefined, as specified above. Matlab code author: <NAME> (<EMAIL>) Date: Dec.2014\"\"\"",
"return R, C tol = 0.01 # collinearity/co-planarity threshold (in degrees) if N",
"@staticmethod def JSDivergence(p, q, tolerance=0.98, base=2): assert tolerance < np.sum(p) <= 1 and",
"threshold_otsu from skimage import measure, transform from scipy import ndimage as ndi import",
"point, p, from the list P_new = P[:-1].copy() p = P[-1].copy() # Check",
"frame of reference C = np.append(C, [np.mean(Xr[:, 2])], axis=0) C = np.transpose(np.dot(np.transpose(Rmat), C))",
"by the points parallel with the xy-plane n = np.cross(D13, D12) n =",
"array[0] D13 = D13 / np.linalg.norm(D13) D14 = array[3] - array[0] D14 =",
"* np.ones((1, n)) # if res > 0: # idx[-1] = res #",
"n1 = np.linalg.norm(np.cross(D12, D13)) n2 = np.linalg.norm(np.cross(D12, D14)) chk = np.clip(np.abs(np.dot(n1, n2)), 0.,",
"info. REREFERENCES: [1] Welzl, E. (1991), 'Smallest enclosing disks (balls and ellipsoids)', Lecture",
"dim=dim).values class TVSHelper: @staticmethod def getOutline(imgFile=\"img.jpg\"): img = io.imread(imgFile, as_gray=True) # 检测到边缘并进行滤波 edge",
"= min([M // 4, 300]) # unnecessary ? # res = M %",
"elif N == 2: R = np.linalg.norm(array[1] - array[0]) / 2 C =",
"class Circumsphere: \"\"\"Copied from GitHub at https://github.com/shrx/mbsc.git, not my original. \"\"\" @classmethod def",
"# minimum bounding sphere D = np.sum(np.square(hull_array - C), axis=1) idx = np.argsort(D",
"skimage.util import img_as_ubyte from skimage.filters import threshold_otsu from skimage import measure, transform from",
"= D12 / np.linalg.norm(D12) D13 = array[2] - array[0] D13 = D13 /",
"Remove the last (i.e., end) point, p, from the list P_new = P[:-1].copy()",
"img_as_ubyte from skimage.filters import threshold_otsu from skimage import measure, transform from scipy import",
"if np.linalg.norm(r) != 0: # Euler rotation vector r = np.arccos(n[2]) * r",
"Computer Science, Vol. 555, pp. 359-370 Matlab code author: <NAME> (<EMAIL>) Date: Dec.2014\"\"\"",
"at https://github.com/shrx/mbsc.git, not my original. \"\"\" @classmethod def fit(cls, array): \"\"\"Compute exact minimum",
"B_min_sphere(cls, P, B): eps = 1E-6 if len(B) == 4 or len(P) ==",
"P def timer(func): \"\"\"Decorator that reports the function execution time. \"\"\" @wraps(func) def",
"idx = np.argsort(D - R**2) D = D[idx] Xb = hull_array[idx[:5]] D =",
"R = np.linalg.norm(array[1] - array[0]) / 2 C = np.mean(array, axis=0) return R,",
"import io, filters from skimage.color import rgb2gray from skimage.util import img_as_ubyte from skimage.filters",
"np.array(cube.shape) - np.array(image.shape))//2 cube[initRowInd:initRowInd+image.shape[0], initColInd:initColInd+image.shape[1]] = image return cube class Circumsphere: \"\"\"Copied from",
"Xr = np.transpose(np.dot(Rmat, np.transpose(array))) ##print(\"Xr\", Xr) # Circle centroid x = Xr[:, :2]",
"= scipy.linalg.expm(np.array([ [0., -r[2], r[1]], [r[2], 0., -r[0]], [-r[1], r[0], 0.] ])) ##print(\"Rmat\",",
"np.linalg.norm(p - C) > (R + eps) if chk: if len(B) == 0:",
"0, p, axis=0)) R, C, _ = cls.B_min_sphere(P_new, B) P = np.insert(P_new.copy(), 0,",
"image return cube class Circumsphere: \"\"\"Copied from GitHub at https://github.com/shrx/mbsc.git, not my original.",
"N = len(array) if N > 4: print('Input must a N-by-3 array of",
"##print(\"n\", n) r = np.cross(n, np.array([0, 0, 1])) if np.linalg.norm(r) != 0: #",
"R, C = cls.fit_base(array_nd) return R, C tol = 0.01 # collinearity/co-planarity threshold",
"Welzl, E. (1991), 'Smallest enclosing disks (balls and ellipsoids)', Lecture Notes in Computer",
"-r[2], r[1]], [r[2], 0., -r[0]], [-r[1], r[0], 0.] ])) ##print(\"Rmat\", Rmat) #Xr =",
"R**2) D = D[idx] Xb = hull_array[idx[:5]] D = D[:5] Xb = Xb[D",
"# Make plane formed by the points parallel with the xy-plane n =",
"# # if res <= 0.25 * dM: # idx[n-2] = idx[n-2] +",
"np.linalg.norm(D13) D14 = array[3] - array[0] D14 = D14 / np.linalg.norm(D14) chk1 =",
"{hour}h {minute}min {second}s\") return res return wrapper class Entropy: def __init__(self) -> None:",
"minute, second = int(hour), int(minute), round(second, 1) print( f\"Function `{func.__name__}` runs for {hour}h",
"using Welzl's algorithm. - X : M-by-3 list of point co-ordinates or a",
"scipy.spatial.distance import jensenshannon from skimage import io, filters from skimage.color import rgb2gray from",
"@classmethod def B_min_sphere(cls, P, B): eps = 1E-6 if len(B) == 4 or",
"D[idx] Xb = hull_array[idx[:5]] D = D[:5] Xb = Xb[D < 1E-6] idx",
"1000: # try: R, C, _ = cls.B_min_sphere(hull_array, []) # Coordiantes of the",
"np.sum(p) <= 1 and tolerance < np.sum(q) <= 1 return jensenshannon(p, q, base=base)",
"C = np.append(C, [np.mean(Xr[:, 2])], axis=0) C = np.transpose(np.dot(np.transpose(Rmat), C)) return R, C",
"chk = np.clip(np.abs(np.dot(D12, D13)), 0., 1.) if np.arccos(chk)/np.pi*180 < tol: R = np.inf",
"np.ceil(M/dM) # idx = dM * np.ones((1, n)) # if res > 0:",
"def fit(cls, array): \"\"\"Compute exact minimum bounding sphere of a 3D point cloud",
"- C) > (R + eps) if chk: if len(B) == 0: B",
"with 3 collinear or 4 coplanar points do not have well-defined solutions (i.e.,",
"longToWidthRatio), **kwargs) cube = np.zeros((64, 64), dtype=np.uint8) initRowInd, initColInd = ( np.array(cube.shape) -",
"np.argsort(Xb[:, 0]) Xb = Xb[idx] return R, C, Xb # except: #raise Exception",
"Xb = Xb[D < 1E-6] idx = np.argsort(Xb[:, 0]) Xb = Xb[idx] return",
"# n -= 1 hull_array = np.array_split(hull_array, dM) Xb = np.empty([0, 3]) for",
"# Check if the the points are co-linear D12 = array[1] - array[0]",
"提取 labeledImg = measure.label(edge, connectivity=2) regionProps = measure.regionprops(labeledImg) regionProps.sort(key=lambda prop: prop.area, reverse=True) targetImage",
"len(P) == 0: R, C = cls.fit_base(B) # fit sphere to boundary points",
"point then we have 4 unique, though possibly co-linear # or co-planar points.",
"= func(*args, **kwargs) end = time.time() timeCost = end - start hour, timeCost",
"B): eps = 1E-6 if len(B) == 4 or len(P) == 0: R,",
"as a TriRep object. - R : radius of the sphere. - C",
"tol: R = np.inf C = np.full(3, np.nan) return R, C # Centroid",
"int(hour), int(minute), round(second, 1) print( f\"Function `{func.__name__}` runs for {hour}h {minute}min {second}s\") return",
"Rotate centroid back into the original frame of reference C = np.append(C, [np.mean(Xr[:,",
"= end - start hour, timeCost = divmod(timeCost, 3600) minute, second = divmod(timeCost,",
"C # Make plane formed by the points parallel with the xy-plane n",
"res # # if res <= 0.25 * dM: # idx[n-2] = idx[n-2]",
"np.arccos(n[2]) * r / np.linalg.norm(r) ##print(\"r\", r) Rmat = scipy.linalg.expm(np.array([ [0., -r[2], r[1]],",
"np.array([0, 0, 1])) if np.linalg.norm(r) != 0: # Euler rotation vector r =",
"= array[hull.vertices] hull_array = np.unique(hull_array, axis=0) # print(len(hull_array)) # Randomly permute the point",
"or 4 points # Remove duplicate vertices, if there are any uniq, index",
"fit_base(cls, array): \"\"\"Fit a sphere to a set of 2, 3, or at",
"{second}s\") return res return wrapper class Entropy: def __init__(self) -> None: pass @staticmethod",
"surface mesh specified as a TriRep object. - R : radius of the",
"< 1E-6] idx = np.argsort(Xb[:, 0]) Xb = Xb[idx] return R, C, Xb",
"thrd edge[maskOfWhite] = 255 edge[~maskOfWhite] = 0 # 提取 labeledImg = measure.label(edge, connectivity=2)",
"4: print('Input must a N-by-3 array of point coordinates, with N<=4') return #",
"= D13 / np.linalg.norm(D13) chk = np.clip(np.abs(np.dot(D12, D13)), 0., 1.) if np.arccos(chk)/np.pi*180 <",
"- C), axis=1) idx = np.argsort(D - R**2) D = D[idx] Xb =",
"axis=0)) return R, C @classmethod def B_min_sphere(cls, P, B): eps = 1E-6 if",
"reverse=True) targetImage = regionProps[0].filled_image return targetImage @staticmethod def putIntoCube(image, size=48, **kwargs): longToWidthRatio =",
"#print(np.where(D/R < 1e-3)[0]) Xb = np.take(Xb, np.where(D/R < 1e-3)[0], axis=0) Xb = np.sort(Xb,",
"points in 3D space. Note that point configurations with 3 collinear or 4",
"scipy.spatial import ConvexHull from scipy.spatial.distance import jensenshannon from skimage import io, filters from",
"/ np.linalg.norm(D14) chk1 = np.clip(np.abs(np.dot(D12, D13)), 0., 1.) chk2 = np.clip(np.abs(np.dot(D12, D14)), 0.,",
"Science, Vol. 555, pp. 359-370 Matlab code author: <NAME> (<EMAIL>) Date: Dec.2014\"\"\" #",
"np.full(3, np.nan) return R, C # Make plane formed by the points parallel",
"then we have 4 unique, though possibly co-linear # or co-planar points. else:",
"len(hull_array) <= 4: R, C = cls.fit_base(hull_array) return R, C, hull_array elif len(hull_array)",
"the xy-plane n = np.cross(D13, D12) n = n / np.linalg.norm(n) ##print(\"n\", n)",
"B = np.array([p]) else: B = np.array(np.insert(B, 0, p, axis=0)) R, C, _",
"np.full(len(array)-1, array[0])) b = np.sum( (np.square(array[1:]) - np.square(np.full(len(array)-1, array[0]))), axis=1) C = np.transpose(np.linalg.solve(A,",
"from scipy.spatial import ConvexHull from scipy.spatial.distance import jensenshannon from skimage import io, filters",
"np.linalg.norm(D12) D13 = array[2] - array[0] D13 = D13 / np.linalg.norm(D13) D14 =",
"1-by-3 vector specifying the centroid of the sphere. - Xb : subset of",
"Date: Dec.2014\"\"\" N = len(array) if N > 4: print('Input must a N-by-3",
"set elif N == 0: R = np.nan C = np.full(3, np.nan) return",
"= np.append(C, [np.mean(Xr[:, 2])], axis=0) C = np.transpose(np.dot(np.transpose(Rmat), C)) return R, C #",
"the list P_new = P[:-1].copy() p = P[-1].copy() # Check if p is",
"measure.label(edge, connectivity=2) regionProps = measure.regionprops(labeledImg) regionProps.sort(key=lambda prop: prop.area, reverse=True) targetImage = regionProps[0].filled_image return",
"len(hull_array) < 1000: # try: R, C, _ = cls.B_min_sphere(hull_array, []) # Coordiantes",
"/ np.linalg.norm(n) ##print(\"n\", n) r = np.cross(n, np.array([0, 0, 1])) if np.linalg.norm(r) !=",
"targetImage @staticmethod def putIntoCube(image, size=48, **kwargs): longToWidthRatio = max(image.shape) / min(image.shape) image =",
"- array[0] D14 = D14 / np.linalg.norm(D14) chk1 = np.clip(np.abs(np.dot(D12, D13)), 0., 1.)",
"return R, C, Xb # except: #raise Exception else: M = len(hull_array) dM",
"np.clip(np.abs(np.dot(D12, D14)), 0., 1.) if np.arccos(chk1)/np.pi*180 < tol or np.arccos(chk2)/np.pi*180 < tol: R",
"= np.inf C = np.full(3, np.nan) return R, C # Centroid of the",
"# unnecessary ? # res = M % dM # n = np.ceil(M/dM)",
"a triangular surface mesh) using Welzl's algorithm. - X : M-by-3 list of",
"C else: # 3 or 4 points # Remove duplicate vertices, if there",
"= ndi.median_filter(edge, 3) # 二值化 thrd = threshold_otsu(edge) maskOfWhite = edge > thrd",
"with the xy-plane n = np.cross(D13, D12) n = n / np.linalg.norm(n) ##print(\"n\",",
"1 and tolerance < np.sum(q) <= 1 return jensenshannon(p, q, base=base) if __name__",
"import measure, transform from scipy import ndimage as ndi import torch def loadNnData(sourcePath,",
"C) > (R + eps) if chk: if len(B) == 0: B =",
"more info. REREFERENCES: [1] Welzl, E. (1991), 'Smallest enclosing disks (balls and ellipsoids)',",
"P = np.insert(P_new.copy(), 0, p, axis=0) return R, C, P def timer(func): \"\"\"Decorator",
"np.array([p]) else: B = np.array(np.insert(B, 0, p, axis=0)) R, C, _ = cls.B_min_sphere(P_new,",
"np.linalg.norm(np.cross(D12, D13)) n2 = np.linalg.norm(np.cross(D12, D14)) chk = np.clip(np.abs(np.dot(n1, n2)), 0., 1.) if",
"- C : 1-by-3 vector specifying the centroid of the sphere. - Xb",
"pass @staticmethod def JSDivergence(p, q, tolerance=0.98, base=2): assert tolerance < np.sum(p) <= 1",
"original frame of reference C = np.append(C, [np.mean(Xr[:, 2])], axis=0) C = np.transpose(np.dot(np.transpose(Rmat),",
"Euler rotation vector r = np.arccos(n[2]) * r / np.linalg.norm(r) ##print(\"r\", r) Rmat",
": 1-by-3 vector specifying the centroid of the sphere. - Xb : subset",
"Xb = hull_array[idx[:5]] D = D[:5] Xb = Xb[D < 1E-6] idx =",
"##print(\"r\", r) Rmat = scipy.linalg.expm(np.array([ [0., -r[2], r[1]], [r[2], 0., -r[0]], [-r[1], r[0],",
"min(image.shape) image = transform.resize( image, (size, size // longToWidthRatio), **kwargs) cube = np.zeros((64,",
"# Check for collinearity D12 = array[1] - array[0] D12 = D12 /",
"= cls.B_min_sphere(P_new, B) P = np.insert(P_new.copy(), 0, p, axis=0) return R, C, P",
"of 2, 3, or at most 4 points in 3D space. Note that",
"from skimage.util import img_as_ubyte from skimage.filters import threshold_otsu from skimage import measure, transform",
"C = np.transpose(np.linalg.solve(A, b)) # Circle radius R = np.sqrt(np.sum(np.square(x[0] - C))) #",
"# 检测到边缘并进行滤波 edge = filters.sobel(img) edge = img_as_ubyte(rgb2gray(edge)) edge = ndi.median_filter(edge, 3) #",
"assert tolerance < np.sum(p) <= 1 and tolerance < np.sum(q) <= 1 return",
"max(image.shape) / min(image.shape) image = transform.resize( image, (size, size // longToWidthRatio), **kwargs) cube",
"3 or 4 points # Remove duplicate vertices, if there are any uniq,",
"= np.empty([0, 3]) for i in range(len(hull_array)): R, C, Xi = cls.B_min_sphere( np.vstack([Xb,",
"is on or inside the bounding sphere. If not, it must be #",
"the sphere R = np.sqrt(np.sum(np.square(array[0] - C), axis=0)) return R, C @classmethod def",
"[0., -r[2], r[1]], [r[2], 0., -r[0]], [-r[1], r[0], 0.] ])) ##print(\"Rmat\", Rmat) #Xr",
"tol or np.arccos(chk2)/np.pi*180 < tol: R = np.inf C = np.full(3, np.nan) return",
"Make plane formed by the points parallel with the xy-plane n = np.cross(D13,",
"np.full(2, x[0])) b = np.sum( (np.square(x[1:]) - np.square(np.full(2, x[0]))), axis=1) C = np.transpose(np.linalg.solve(A,",
"https://github.com/shrx/mbsc.git, not my original. \"\"\" @classmethod def fit(cls, array): \"\"\"Compute exact minimum bounding",
"255: data[data == 255] = 1 return data def project(tensor: torch.tensor, dim: int):",
"Welzl's algorithm. - X : M-by-3 list of point co-ordinates or a triangular",
"array[3] - array[0] D14 = D14 / np.linalg.norm(D14) chk1 = np.clip(np.abs(np.dot(D12, D13)), 0.,",
"must a N-by-3 array of point coordinates, with N<=4') return # Empty set",
"R, C, Xb @classmethod def fit_base(cls, array): \"\"\"Fit a sphere to a set",
"which R and C were computed. See function titled 'FitSphere2Points' for more info.",
"where M<=4. - R : radius of the sphere. R=Inf when the sphere",
"points parallel with the xy-plane n = np.cross(D13, D12) n = n /",
"timeCost = divmod(timeCost, 3600) minute, second = divmod(timeCost, 60) hour, minute, second =",
"co-planar n1 = np.linalg.norm(np.cross(D12, D13)) n2 = np.linalg.norm(np.cross(D12, D14)) chk = np.clip(np.abs(np.dot(n1, n2)),",
"cloud (or a triangular surface mesh) using Welzl's algorithm. - X : M-by-3",
"R : radius of the sphere. - C : 1-by-3 vector specifying the",
"# fit sphere to boundary points return R, C, P # Remove the",
"set hull = ConvexHull(array) hull_array = array[hull.vertices] hull_array = np.unique(hull_array, axis=0) # print(len(hull_array))",
"np.argsort(D, axis=0) Xb = Xi[idx[:40]] D = np.sort(D, axis=0)[:4] # print(Xb) # print(D)",
"Radius of the sphere R = np.sqrt(np.sum(np.square(array[0] - C), axis=0)) return R, C",
"io, filters from skimage.color import rgb2gray from skimage.util import img_as_ubyte from skimage.filters import",
"/ np.linalg.norm(D13) chk = np.clip(np.abs(np.dot(D12, D13)), 0., 1.) if np.arccos(chk)/np.pi*180 < tol: R",
"uniq, index = np.unique(array, axis=0, return_index=True) array_nd = uniq[index.argsort()] if not np.array_equal(array, array_nd):",
"3: # Check for collinearity D12 = array[1] - array[0] D12 = D12",
"R = 0. C = array[0] return R, C # Line segment elif",
"elif sourcePath.endswith('.npz'): data = torch.from_numpy(np.load(sourcePath)[keyword]) if data.max() == 255: data[data == 255] =",
"regionProps.sort(key=lambda prop: prop.area, reverse=True) targetImage = regionProps[0].filled_image return targetImage @staticmethod def putIntoCube(image, size=48,",
"= cls.fit_base(B) # fit sphere to boundary points return R, C, P #",
"hour, minute, second = int(hour), int(minute), round(second, 1) print( f\"Function `{func.__name__}` runs for",
"D13)), 0., 1.) chk2 = np.clip(np.abs(np.dot(D12, D14)), 0., 1.) if np.arccos(chk1)/np.pi*180 < tol",
"were computed. See function titled 'FitSphere2Points' for more info. REREFERENCES: [1] Welzl, E.",
"a triangular surface mesh specified as a TriRep object. - R : radius",
"= array[0] return R, C # Line segment elif N == 2: R",
"\"\"\" @wraps(func) def wrapper(*args, **kwargs): start = time.time() res = func(*args, **kwargs) end",
"D[:5] Xb = Xb[D < 1E-6] idx = np.argsort(Xb[:, 0]) Xb = Xb[idx]",
"M % dM # n = np.ceil(M/dM) # idx = dM * np.ones((1,",
"on or inside the bounding sphere. If not, it must be # part",
"- array[0] D12 = D12 / np.linalg.norm(D12) D13 = array[2] - array[0] D13",
"% dM # n = np.ceil(M/dM) # idx = dM * np.ones((1, n))",
"triangular surface mesh specified as a TriRep object. - R : radius of",
"n = n / np.linalg.norm(n) ##print(\"n\", n) r = np.cross(n, np.array([0, 0, 1]))",
"= np.clip(np.abs(np.dot(D12, D13)), 0., 1.) if np.arccos(chk)/np.pi*180 < tol: R = np.inf C",
"of the point set hull = ConvexHull(array) hull_array = array[hull.vertices] hull_array = np.unique(hull_array,",
"axis=0) # print(len(hull_array)) # Randomly permute the point set hull_array = np.random.permutation(hull_array) if",
"str = None) -> torch.Tensor: if sourcePath.endswith('.npy'): data = torch.from_numpy(np.load(sourcePath)) elif sourcePath.endswith('.npz'): data",
"of the points used to compute parameters of the # minimum bounding sphere",
"to compute parameters of the # minimum bounding sphere D = np.sum(np.square(hull_array -",
"if there are any uniq, index = np.unique(array, axis=0, return_index=True) array_nd = uniq[index.argsort()]",
"D14)) chk = np.clip(np.abs(np.dot(n1, n2)), 0., 1.) if np.arccos(chk)/np.pi*180 < tol: R =",
"C)) return R, C # If we got to this point then we",
"start hour, timeCost = divmod(timeCost, 3600) minute, second = divmod(timeCost, 60) hour, minute,",
"# Circle radius R = np.sqrt(np.sum(np.square(x[0] - C))) # Rotate centroid back into",
"Xb = Xi[idx[:40]] D = np.sort(D, axis=0)[:4] # print(Xb) # print(D) #print(np.where(D/R <",
"second = divmod(timeCost, 60) hour, minute, second = int(hour), int(minute), round(second, 1) print(",
"= 0 # 提取 labeledImg = measure.label(edge, connectivity=2) regionProps = measure.regionprops(labeledImg) regionProps.sort(key=lambda prop:",
"of the sphere. R=Inf when the sphere is undefined, as specified above. -",
"p, from the list P_new = P[:-1].copy() p = P[-1].copy() # Check if",
"_ = cls.B_min_sphere(hull_array, []) # Coordiantes of the points used to compute parameters",
"= np.insert(P_new.copy(), 0, p, axis=0) return R, C, P def timer(func): \"\"\"Decorator that",
"np.append(C, [np.mean(Xr[:, 2])], axis=0) C = np.transpose(np.dot(np.transpose(Rmat), C)) return R, C # If",
"array): \"\"\"Compute exact minimum bounding sphere of a 3D point cloud (or a",
"def fit_base(cls, array): \"\"\"Fit a sphere to a set of 2, 3, or",
"of the sphere. - Xb : subset of X, listing K-by-3 list of",
"mesh specified as a TriRep object. - R : radius of the sphere.",
"# n = np.ceil(M/dM) # idx = dM * np.ones((1, n)) # if",
"np.abs(np.sqrt(np.sum((Xi - C)**2, axis=1)) - R) idx = np.argsort(D, axis=0) Xb = Xi[idx[:40]]",
"duplicate vertices, if there are any uniq, index = np.unique(array, axis=0, return_index=True) array_nd",
"array[hull.vertices] hull_array = np.unique(hull_array, axis=0) # print(len(hull_array)) # Randomly permute the point set",
"function execution time. \"\"\" @wraps(func) def wrapper(*args, **kwargs): start = time.time() res =",
"the sphere A = 2 * (array[1:] - np.full(len(array)-1, array[0])) b = np.sum(",
"of the new boundary. R, C, P_new = cls.B_min_sphere(P_new, B) if np.isnan(R) or",
"in 3D space. Note that point configurations with 3 collinear or 4 coplanar",
"runs for {hour}h {minute}min {second}s\") return res return wrapper class Entropy: def __init__(self)",
"D14)), 0., 1.) if np.arccos(chk1)/np.pi*180 < tol or np.arccos(chk2)/np.pi*180 < tol: R =",
"< tol or np.arccos(chk2)/np.pi*180 < tol: R = np.inf C = np.full(3, np.nan)",
"import numpy as np import scipy from scipy.spatial import ConvexHull from scipy.spatial.distance import",
"Check if the the points are co-planar n1 = np.linalg.norm(np.cross(D12, D13)) n2 =",
"D12 / np.linalg.norm(D12) D13 = array[2] - array[0] D13 = D13 / np.linalg.norm(D13)",
"cube = np.zeros((64, 64), dtype=np.uint8) initRowInd, initColInd = ( np.array(cube.shape) - np.array(image.shape))//2 cube[initRowInd:initRowInd+image.shape[0],",
"cube[initRowInd:initRowInd+image.shape[0], initColInd:initColInd+image.shape[1]] = image return cube class Circumsphere: \"\"\"Copied from GitHub at https://github.com/shrx/mbsc.git,",
"1.) chk2 = np.clip(np.abs(np.dot(D12, D14)), 0., 1.) if np.arccos(chk1)/np.pi*180 < tol or np.arccos(chk2)/np.pi*180",
"\"\"\"Copied from GitHub at https://github.com/shrx/mbsc.git, not my original. \"\"\" @classmethod def fit(cls, array):",
"segment elif N == 2: R = np.linalg.norm(array[1] - array[0]) / 2 C",
"co-linear # or co-planar points. else: # Check if the the points are",
"0, 1])) if np.linalg.norm(r) != 0: # Euler rotation vector r = np.arccos(n[2])",
"Centroid of the sphere A = 2 * (array[1:] - np.full(len(array)-1, array[0])) b",
"the sphere is undefined, as specified above. Matlab code author: <NAME> (<EMAIL>) Date:",
"\"\"\" @classmethod def fit(cls, array): \"\"\"Compute exact minimum bounding sphere of a 3D",
"1: R = 0. C = array[0] return R, C # Line segment",
"eps: chk = True else: chk = np.linalg.norm(p - C) > (R +",
"np import scipy from scipy.spatial import ConvexHull from scipy.spatial.distance import jensenshannon from skimage",
"fit(cls, array): \"\"\"Compute exact minimum bounding sphere of a 3D point cloud (or",
"np.isinf(R) or R < eps: chk = True else: chk = np.linalg.norm(p -",
"np.sort(Xb, axis=0) # print(Xb) return R, C, Xb @classmethod def fit_base(cls, array): \"\"\"Fit",
"def wrapper(*args, **kwargs): start = time.time() res = func(*args, **kwargs) end = time.time()",
"of point co-ordinates or a triangular surface mesh specified as a TriRep object.",
"cls.B_min_sphere(P_new, B) P = np.insert(P_new.copy(), 0, p, axis=0) return R, C, P def",
"the sphere. R=Inf when the sphere is undefined, as specified above. - C",
"if p is on or inside the bounding sphere. If not, it must",
"if not np.array_equal(array, array_nd): print(\"found duplicate\") print(array_nd) R, C = cls.fit_base(array_nd) return R,",
"end = time.time() timeCost = end - start hour, timeCost = divmod(timeCost, 3600)",
"np.nan) return R, C # Centroid of the sphere A = 2 *",
"R, C = cls.fit_base(B) # fit sphere to boundary points return R, C,",
"mesh) using Welzl's algorithm. - X : M-by-3 list of point co-ordinates or",
"np.take(Xb, np.where(D/R < 1e-3)[0], axis=0) Xb = np.sort(Xb, axis=0) # print(Xb) return R,",
"0: R, C = cls.fit_base(B) # fit sphere to boundary points return R,",
"( np.array(cube.shape) - np.array(image.shape))//2 cube[initRowInd:initRowInd+image.shape[0], initColInd:initColInd+image.shape[1]] = image return cube class Circumsphere: \"\"\"Copied",
"= np.full(3, np.nan) return R, C # Centroid of the sphere A =",
"print(D) #print(np.where(D/R < 1e-3)[0]) Xb = np.take(Xb, np.where(D/R < 1e-3)[0], axis=0) Xb =",
"if np.arccos(chk)/np.pi*180 < tol: R = np.inf C = np.full(3, np.nan) return R,",
"print('Input must a N-by-3 array of point coordinates, with N<=4') return # Empty",
"ndimage as ndi import torch def loadNnData(sourcePath, keyword: str = None) -> torch.Tensor:",
"= threshold_otsu(edge) maskOfWhite = edge > thrd edge[maskOfWhite] = 255 edge[~maskOfWhite] = 0",
"= len(array) if N > 4: print('Input must a N-by-3 array of point",
"array[0]))), axis=1) C = np.transpose(np.linalg.solve(A, b)) # Radius of the sphere R =",
"i in range(len(hull_array)): R, C, Xi = cls.B_min_sphere( np.vstack([Xb, hull_array[i]]), []) # 40",
"300]) # unnecessary ? # res = M % dM # n =",
"if data.max() == 255: data[data == 255] = 1 return data def project(tensor:",
"np.linalg.norm(r) != 0: # Euler rotation vector r = np.arccos(n[2]) * r /",
"loadNnData(sourcePath, keyword: str = None) -> torch.Tensor: if sourcePath.endswith('.npy'): data = torch.from_numpy(np.load(sourcePath)) elif",
"= np.full(3, np.nan) return R, C # Check if the the points are",
"3D space. Note that point configurations with 3 collinear or 4 coplanar points",
"skimage import io, filters from skimage.color import rgb2gray from skimage.util import img_as_ubyte from",
"import torch def loadNnData(sourcePath, keyword: str = None) -> torch.Tensor: if sourcePath.endswith('.npy'): data",
"R, C # Line segment elif N == 2: R = np.linalg.norm(array[1] -",
"* r / np.linalg.norm(r) ##print(\"r\", r) Rmat = scipy.linalg.expm(np.array([ [0., -r[2], r[1]], [r[2],",
"C, _ = cls.B_min_sphere(P_new, B) P = np.insert(P_new.copy(), 0, p, axis=0) return R,",
"points are co-linear D12 = array[1] - array[0] D12 = D12 / np.linalg.norm(D12)",
"**kwargs): start = time.time() res = func(*args, **kwargs) end = time.time() timeCost =",
"< tol: R = np.inf C = np.full(3, np.nan) return R, C #",
"40 points closest to the sphere D = np.abs(np.sqrt(np.sum((Xi - C)**2, axis=1)) -",
"sphere D = np.abs(np.sqrt(np.sum((Xi - C)**2, axis=1)) - R) idx = np.argsort(D, axis=0)",
"R, C else: # 3 or 4 points # Remove duplicate vertices, if",
"triangular surface mesh) using Welzl's algorithm. - X : M-by-3 list of point",
"R = np.inf C = np.full(3, np.nan) return R, C # Check if",
"<= 4: R, C = cls.fit_base(hull_array) return R, C, hull_array elif len(hull_array) <",
"np.unique(array, axis=0, return_index=True) array_nd = uniq[index.argsort()] if not np.array_equal(array, array_nd): print(\"found duplicate\") print(array_nd)",
"np.linalg.norm(D14) chk1 = np.clip(np.abs(np.dot(D12, D13)), 0., 1.) chk2 = np.clip(np.abs(np.dot(D12, D14)), 0., 1.)"
] |
[
"aa in zip(residues, WTseq): if str(residue) in Mut: ID += Mut.rsplit(str(residue))[1][0] else: ID",
"'WT' else Mut2ID(mut, WTseq, sorted(lib_variants.keys(), key= lambda x:int(x))) fit_dict[strain][ID] = {'input_count': input_count, 'fit':fit,",
"return 'no' return 'yes' def read_lib_variants(filename): lib_variants = {} infile = open(filename, 'r')",
"'no' elif aa not in lib_variants[pos]: return 'no' return 'yes' def read_lib_variants(filename): lib_variants",
"'fit_R2':rep2_fit} return fit_dict def mutate_full_protein(WT_seq, mut, positions): mut_seq = WT_seq for pos, mutaa",
"outfile.write(\"\\t\".join([mut, strain, pI, chg, R1fit, R2fit, fit])+\"\\n\") outfile.close() def main(): filenames = glob.glob('result/NA_Epi_*.tsv')",
"def read_fitness_data(filename, fit_dict, WTseq, lib_variants, strain): infile = open(filename, 'r') for line in",
"line: continue strain, seq = line.rstrip().rsplit(\"\\t\") WT_seqs[strain] = seq return WT_seqs def read_fasta(filename):",
"= read_lib_variants('data/lib_variants.tsv') N2_seqs = read_fasta('Fasta/N2.fa') WT_seqs = read_WT_seqs('data/WT_seq.tsv') fit_dict = defaultdict(dict) for filename",
"= mut_seq[0:pos-1]+mutaa+mut_seq[pos::] return mut_seq def calculate_charge(mut): charge = 0 charge -= mut.count('D') charge",
"strain in ['HK68','Bk79','Bei89','Mos99','Vic11','HK19']: for mut in mut_list: WT_seq = N2_seqs[strain] full_seq = mutate_full_protein(WT_seq,",
"infile = open(filename, 'r') for line in infile.readlines(): if 'Mut' in line: continue",
"open(outfile, 'w') mut_list = fit_dict['HK68'].keys() header = \"\\t\".join(['ID', 'strain', 'pI', 'charge', 'rep1_fit', 'rep2_fit',",
"line.rstrip().rsplit(\"\\t\") if check_mut_in_lib(mut, lib_variants) == 'no': continue if int(input_count) < 10: continue ID",
"'yes' def read_lib_variants(filename): lib_variants = {} infile = open(filename, 'r') for line in",
"def calculate_charge(mut): charge = 0 charge -= mut.count('D') charge -= mut.count('E') charge +=",
"fit_dict = defaultdict(dict) for filename in filenames: strain = filename.rsplit('_')[-1].rsplit('.')[0] WTseq = WT_seqs[strain]",
"fit_dict[strain][mut]['fit'] R1fit = fit_dict[strain][mut]['fit_R1'] R2fit = fit_dict[strain][mut]['fit_R2'] outfile.write(\"\\t\".join([mut, strain, pI, chg, R1fit, R2fit,",
"records = SeqIO.parse(filename,\"fasta\") for record in records: ID = str(record.id) seq = str(record.seq)",
"continue pos, muts = line.rstrip().rsplit(\"\\t\") lib_variants[pos] = muts.rsplit(',') return lib_variants def read_WT_seqs(filename): WT_seqs",
"mut, sample, input_count, rep1_count, rep2_count, rep1_fit, rep2_fit, fit = line.rstrip().rsplit(\"\\t\") if check_mut_in_lib(mut, lib_variants)",
"fit_dict['HK68'].keys() header = \"\\t\".join(['ID', 'strain', 'pI', 'charge', 'rep1_fit', 'rep2_fit', 'fit']) outfile.write(header+\"\\n\") positions =",
"infile = open(filename, 'r') for line in infile.readlines(): if 'strain' in line: continue",
"os import sys import glob import numpy as np from Bio import SeqIO",
"'strain', 'pI', 'charge', 'rep1_fit', 'rep2_fit', 'fit']) outfile.write(header+\"\\n\") positions = (sorted(map(int,list(lib_variants.keys())))) for strain in",
"'fit_R1':rep1_fit, 'fit_R2':rep2_fit} return fit_dict def mutate_full_protein(WT_seq, mut, positions): mut_seq = WT_seq for pos,",
"refseq_dict = {} records = SeqIO.parse(filename,\"fasta\") for record in records: ID = str(record.id)",
"mut_list: WT_seq = N2_seqs[strain] full_seq = mutate_full_protein(WT_seq, mut, positions) #pI = str(np.mean([PA('A'+aa+'A').isoelectric_point() for",
"ID def check_mut_in_lib(mut, lib_variants): if mut == 'WT': return 'yes' for m in",
"in mut.rsplit('-'): pos = m[1:-1] aa = m[-1] if pos not in lib_variants.keys():",
"in mut])) #pI = str(PA('A'+mut+'A').isoelectric_point()) #pI = str(PA(mut).isoelectric_point()) pI = str(PA(full_seq).isoelectric_point()) chg =",
"Mut2ID(mut, WTseq, sorted(lib_variants.keys(), key= lambda x:int(x))) fit_dict[strain][ID] = {'input_count': input_count, 'fit':fit, 'fit_R1':rep1_fit, 'fit_R2':rep2_fit}",
"str(record.id) seq = str(record.seq) refseq_dict[ID] = seq return refseq_dict def read_fitness_data(filename, fit_dict, WTseq,",
"in line: continue strain, seq = line.rstrip().rsplit(\"\\t\") WT_seqs[strain] = seq return WT_seqs def",
"fit_dict, N2_seqs, lib_variants): print (\"writing: %s\" % outfile) outfile = open(outfile, 'w') mut_list",
"= WT_seq for pos, mutaa in zip(positions, mut): mut_seq = mut_seq[0:pos-1]+mutaa+mut_seq[pos::] return mut_seq",
"m[1:-1] aa = m[-1] if pos not in lib_variants.keys(): return 'no' elif aa",
"charge = 0 charge -= mut.count('D') charge -= mut.count('E') charge += mut.count('K') charge",
"= muts.rsplit(',') return lib_variants def read_WT_seqs(filename): WT_seqs = {} infile = open(filename, 'r')",
"'rep1_fit', 'rep2_fit', 'fit']) outfile.write(header+\"\\n\") positions = (sorted(map(int,list(lib_variants.keys())))) for strain in ['HK68','Bk79','Bei89','Mos99','Vic11','HK19']: for mut",
"charge += mut.count('R') return charge def write_output_file(outfile, fit_dict, N2_seqs, lib_variants): print (\"writing: %s\"",
"Mut2ID(Mut, WTseq, residues): ID = '' for residue, aa in zip(residues, WTseq): if",
"= (sorted(map(int,list(lib_variants.keys())))) for strain in ['HK68','Bk79','Bei89','Mos99','Vic11','HK19']: for mut in mut_list: WT_seq = N2_seqs[strain]",
"line.rstrip().rsplit(\"\\t\") WT_seqs[strain] = seq return WT_seqs def read_fasta(filename): refseq_dict = {} records =",
"'Mut' in line: continue mut, sample, input_count, rep1_count, rep2_count, rep1_fit, rep2_fit, fit =",
"sys import glob import numpy as np from Bio import SeqIO from collections",
"mut, positions) #pI = str(np.mean([PA('A'+aa+'A').isoelectric_point() for aa in mut])) #pI = str(PA('A'+mut+'A').isoelectric_point()) #pI",
"aa not in lib_variants[pos]: return 'no' return 'yes' def read_lib_variants(filename): lib_variants = {}",
"ID = '' for residue, aa in zip(residues, WTseq): if str(residue) in Mut:",
"#!/usr/bin/python import os import sys import glob import numpy as np from Bio",
"import SeqIO from collections import defaultdict from Bio.SeqUtils.ProtParam import ProteinAnalysis as PA def",
"= fit_dict[strain][mut]['fit_R1'] R2fit = fit_dict[strain][mut]['fit_R2'] outfile.write(\"\\t\".join([mut, strain, pI, chg, R1fit, R2fit, fit])+\"\\n\") outfile.close()",
"in zip(residues, WTseq): if str(residue) in Mut: ID += Mut.rsplit(str(residue))[1][0] else: ID +=",
"outfile.close() def main(): filenames = glob.glob('result/NA_Epi_*.tsv') outfile = 'result/NA_compile_results.tsv' lib_variants = read_lib_variants('data/lib_variants.tsv') N2_seqs",
"muts = line.rstrip().rsplit(\"\\t\") lib_variants[pos] = muts.rsplit(',') return lib_variants def read_WT_seqs(filename): WT_seqs = {}",
"records: ID = str(record.id) seq = str(record.seq) refseq_dict[ID] = seq return refseq_dict def",
"mut_list = fit_dict['HK68'].keys() header = \"\\t\".join(['ID', 'strain', 'pI', 'charge', 'rep1_fit', 'rep2_fit', 'fit']) outfile.write(header+\"\\n\")",
"def write_output_file(outfile, fit_dict, N2_seqs, lib_variants): print (\"writing: %s\" % outfile) outfile = open(outfile,",
"seq = line.rstrip().rsplit(\"\\t\") WT_seqs[strain] = seq return WT_seqs def read_fasta(filename): refseq_dict = {}",
"fit_dict[strain][mut]['fit_R2'] outfile.write(\"\\t\".join([mut, strain, pI, chg, R1fit, R2fit, fit])+\"\\n\") outfile.close() def main(): filenames =",
"lib_variants, strain): infile = open(filename, 'r') for line in infile.readlines(): if 'Mut' in",
"strain): infile = open(filename, 'r') for line in infile.readlines(): if 'Mut' in line:",
"mut): mut_seq = mut_seq[0:pos-1]+mutaa+mut_seq[pos::] return mut_seq def calculate_charge(mut): charge = 0 charge -=",
"= {'input_count': input_count, 'fit':fit, 'fit_R1':rep1_fit, 'fit_R2':rep2_fit} return fit_dict def mutate_full_protein(WT_seq, mut, positions): mut_seq",
"int(input_count) < 10: continue ID = WTseq if mut == 'WT' else Mut2ID(mut,",
"lib_variants = read_lib_variants('data/lib_variants.tsv') N2_seqs = read_fasta('Fasta/N2.fa') WT_seqs = read_WT_seqs('data/WT_seq.tsv') fit_dict = defaultdict(dict) for",
"= str(np.mean([PA('A'+aa+'A').isoelectric_point() for aa in mut])) #pI = str(PA('A'+mut+'A').isoelectric_point()) #pI = str(PA(mut).isoelectric_point()) pI",
"positions = (sorted(map(int,list(lib_variants.keys())))) for strain in ['HK68','Bk79','Bei89','Mos99','Vic11','HK19']: for mut in mut_list: WT_seq =",
"write_output_file(outfile, fit_dict, N2_seqs, lib_variants): print (\"writing: %s\" % outfile) outfile = open(outfile, 'w')",
"in line: continue mut, sample, input_count, rep1_count, rep2_count, rep1_fit, rep2_fit, fit = line.rstrip().rsplit(\"\\t\")",
"open(filename, 'r') for line in infile.readlines(): if 'strain' in line: continue strain, seq",
"read_fasta(filename): refseq_dict = {} records = SeqIO.parse(filename,\"fasta\") for record in records: ID =",
"N2_seqs[strain] full_seq = mutate_full_protein(WT_seq, mut, positions) #pI = str(np.mean([PA('A'+aa+'A').isoelectric_point() for aa in mut]))",
"return ID def check_mut_in_lib(mut, lib_variants): if mut == 'WT': return 'yes' for m",
"'fit':fit, 'fit_R1':rep1_fit, 'fit_R2':rep2_fit} return fit_dict def mutate_full_protein(WT_seq, mut, positions): mut_seq = WT_seq for",
"'charge', 'rep1_fit', 'rep2_fit', 'fit']) outfile.write(header+\"\\n\") positions = (sorted(map(int,list(lib_variants.keys())))) for strain in ['HK68','Bk79','Bei89','Mos99','Vic11','HK19']: for",
"= 'result/NA_compile_results.tsv' lib_variants = read_lib_variants('data/lib_variants.tsv') N2_seqs = read_fasta('Fasta/N2.fa') WT_seqs = read_WT_seqs('data/WT_seq.tsv') fit_dict =",
"line in infile.readlines(): if 'Mut' in line: continue mut, sample, input_count, rep1_count, rep2_count,",
"str(PA(full_seq).isoelectric_point()) chg = str(calculate_charge(mut)) fit = fit_dict[strain][mut]['fit'] R1fit = fit_dict[strain][mut]['fit_R1'] R2fit = fit_dict[strain][mut]['fit_R2']",
"== 'no': continue if int(input_count) < 10: continue ID = WTseq if mut",
"import ProteinAnalysis as PA def Mut2ID(Mut, WTseq, residues): ID = '' for residue,",
"return fit_dict def mutate_full_protein(WT_seq, mut, positions): mut_seq = WT_seq for pos, mutaa in",
"return WT_seqs def read_fasta(filename): refseq_dict = {} records = SeqIO.parse(filename,\"fasta\") for record in",
"WTseq = WT_seqs[strain] fit_dict = read_fitness_data(filename, fit_dict, WTseq, lib_variants, strain) write_output_file(outfile, fit_dict, N2_seqs,",
"= seq return refseq_dict def read_fitness_data(filename, fit_dict, WTseq, lib_variants, strain): infile = open(filename,",
"input_count, rep1_count, rep2_count, rep1_fit, rep2_fit, fit = line.rstrip().rsplit(\"\\t\") if check_mut_in_lib(mut, lib_variants) == 'no':",
"aa = m[-1] if pos not in lib_variants.keys(): return 'no' elif aa not",
"positions) #pI = str(np.mean([PA('A'+aa+'A').isoelectric_point() for aa in mut])) #pI = str(PA('A'+mut+'A').isoelectric_point()) #pI =",
"outfile.write(header+\"\\n\") positions = (sorted(map(int,list(lib_variants.keys())))) for strain in ['HK68','Bk79','Bei89','Mos99','Vic11','HK19']: for mut in mut_list: WT_seq",
"lambda x:int(x))) fit_dict[strain][ID] = {'input_count': input_count, 'fit':fit, 'fit_R1':rep1_fit, 'fit_R2':rep2_fit} return fit_dict def mutate_full_protein(WT_seq,",
"chg, R1fit, R2fit, fit])+\"\\n\") outfile.close() def main(): filenames = glob.glob('result/NA_Epi_*.tsv') outfile = 'result/NA_compile_results.tsv'",
"fit_dict[strain][ID] = {'input_count': input_count, 'fit':fit, 'fit_R1':rep1_fit, 'fit_R2':rep2_fit} return fit_dict def mutate_full_protein(WT_seq, mut, positions):",
"= filename.rsplit('_')[-1].rsplit('.')[0] WTseq = WT_seqs[strain] fit_dict = read_fitness_data(filename, fit_dict, WTseq, lib_variants, strain) write_output_file(outfile,",
"'r') for line in infile.readlines(): if 'strain' in line: continue strain, seq =",
"collections import defaultdict from Bio.SeqUtils.ProtParam import ProteinAnalysis as PA def Mut2ID(Mut, WTseq, residues):",
"= line.rstrip().rsplit(\"\\t\") if check_mut_in_lib(mut, lib_variants) == 'no': continue if int(input_count) < 10: continue",
"read_fasta('Fasta/N2.fa') WT_seqs = read_WT_seqs('data/WT_seq.tsv') fit_dict = defaultdict(dict) for filename in filenames: strain =",
"lib_variants) == 'no': continue if int(input_count) < 10: continue ID = WTseq if",
"continue if int(input_count) < 10: continue ID = WTseq if mut == 'WT'",
"['HK68','Bk79','Bei89','Mos99','Vic11','HK19']: for mut in mut_list: WT_seq = N2_seqs[strain] full_seq = mutate_full_protein(WT_seq, mut, positions)",
"lib_variants): if mut == 'WT': return 'yes' for m in mut.rsplit('-'): pos =",
"PA def Mut2ID(Mut, WTseq, residues): ID = '' for residue, aa in zip(residues,",
"{} infile = open(filename, 'r') for line in infile.readlines(): if 'strain' in line:",
"numpy as np from Bio import SeqIO from collections import defaultdict from Bio.SeqUtils.ProtParam",
"'no' return 'yes' def read_lib_variants(filename): lib_variants = {} infile = open(filename, 'r') for",
"glob import numpy as np from Bio import SeqIO from collections import defaultdict",
"'pI', 'charge', 'rep1_fit', 'rep2_fit', 'fit']) outfile.write(header+\"\\n\") positions = (sorted(map(int,list(lib_variants.keys())))) for strain in ['HK68','Bk79','Bei89','Mos99','Vic11','HK19']:",
"refseq_dict def read_fitness_data(filename, fit_dict, WTseq, lib_variants, strain): infile = open(filename, 'r') for line",
"mutate_full_protein(WT_seq, mut, positions) #pI = str(np.mean([PA('A'+aa+'A').isoelectric_point() for aa in mut])) #pI = str(PA('A'+mut+'A').isoelectric_point())",
"header = \"\\t\".join(['ID', 'strain', 'pI', 'charge', 'rep1_fit', 'rep2_fit', 'fit']) outfile.write(header+\"\\n\") positions = (sorted(map(int,list(lib_variants.keys()))))",
"R1fit, R2fit, fit])+\"\\n\") outfile.close() def main(): filenames = glob.glob('result/NA_Epi_*.tsv') outfile = 'result/NA_compile_results.tsv' lib_variants",
"if mut == 'WT' else Mut2ID(mut, WTseq, sorted(lib_variants.keys(), key= lambda x:int(x))) fit_dict[strain][ID] =",
"not in lib_variants[pos]: return 'no' return 'yes' def read_lib_variants(filename): lib_variants = {} infile",
"{} infile = open(filename, 'r') for line in infile.readlines(): if 'pos' in line:",
"WT_seq for pos, mutaa in zip(positions, mut): mut_seq = mut_seq[0:pos-1]+mutaa+mut_seq[pos::] return mut_seq def",
"= {} infile = open(filename, 'r') for line in infile.readlines(): if 'pos' in",
"rep1_count, rep2_count, rep1_fit, rep2_fit, fit = line.rstrip().rsplit(\"\\t\") if check_mut_in_lib(mut, lib_variants) == 'no': continue",
"key= lambda x:int(x))) fit_dict[strain][ID] = {'input_count': input_count, 'fit':fit, 'fit_R1':rep1_fit, 'fit_R2':rep2_fit} return fit_dict def",
"def Mut2ID(Mut, WTseq, residues): ID = '' for residue, aa in zip(residues, WTseq):",
"rep1_fit, rep2_fit, fit = line.rstrip().rsplit(\"\\t\") if check_mut_in_lib(mut, lib_variants) == 'no': continue if int(input_count)",
"-= mut.count('D') charge -= mut.count('E') charge += mut.count('K') charge += mut.count('R') return charge",
"Bio.SeqUtils.ProtParam import ProteinAnalysis as PA def Mut2ID(Mut, WTseq, residues): ID = '' for",
"m[-1] if pos not in lib_variants.keys(): return 'no' elif aa not in lib_variants[pos]:",
"'' for residue, aa in zip(residues, WTseq): if str(residue) in Mut: ID +=",
"muts.rsplit(',') return lib_variants def read_WT_seqs(filename): WT_seqs = {} infile = open(filename, 'r') for",
"x:int(x))) fit_dict[strain][ID] = {'input_count': input_count, 'fit':fit, 'fit_R1':rep1_fit, 'fit_R2':rep2_fit} return fit_dict def mutate_full_protein(WT_seq, mut,",
"R1fit = fit_dict[strain][mut]['fit_R1'] R2fit = fit_dict[strain][mut]['fit_R2'] outfile.write(\"\\t\".join([mut, strain, pI, chg, R1fit, R2fit, fit])+\"\\n\")",
"def read_WT_seqs(filename): WT_seqs = {} infile = open(filename, 'r') for line in infile.readlines():",
"mut in mut_list: WT_seq = N2_seqs[strain] full_seq = mutate_full_protein(WT_seq, mut, positions) #pI =",
"if check_mut_in_lib(mut, lib_variants) == 'no': continue if int(input_count) < 10: continue ID =",
"as PA def Mut2ID(Mut, WTseq, residues): ID = '' for residue, aa in",
"= str(record.seq) refseq_dict[ID] = seq return refseq_dict def read_fitness_data(filename, fit_dict, WTseq, lib_variants, strain):",
"if 'Mut' in line: continue mut, sample, input_count, rep1_count, rep2_count, rep1_fit, rep2_fit, fit",
"fit])+\"\\n\") outfile.close() def main(): filenames = glob.glob('result/NA_Epi_*.tsv') outfile = 'result/NA_compile_results.tsv' lib_variants = read_lib_variants('data/lib_variants.tsv')",
"pI = str(PA(full_seq).isoelectric_point()) chg = str(calculate_charge(mut)) fit = fit_dict[strain][mut]['fit'] R1fit = fit_dict[strain][mut]['fit_R1'] R2fit",
"\"\\t\".join(['ID', 'strain', 'pI', 'charge', 'rep1_fit', 'rep2_fit', 'fit']) outfile.write(header+\"\\n\") positions = (sorted(map(int,list(lib_variants.keys())))) for strain",
"glob.glob('result/NA_Epi_*.tsv') outfile = 'result/NA_compile_results.tsv' lib_variants = read_lib_variants('data/lib_variants.tsv') N2_seqs = read_fasta('Fasta/N2.fa') WT_seqs = read_WT_seqs('data/WT_seq.tsv')",
"return lib_variants def read_WT_seqs(filename): WT_seqs = {} infile = open(filename, 'r') for line",
"charge def write_output_file(outfile, fit_dict, N2_seqs, lib_variants): print (\"writing: %s\" % outfile) outfile =",
"in infile.readlines(): if 'pos' in line: continue pos, muts = line.rstrip().rsplit(\"\\t\") lib_variants[pos] =",
"SeqIO.parse(filename,\"fasta\") for record in records: ID = str(record.id) seq = str(record.seq) refseq_dict[ID] =",
"return charge def write_output_file(outfile, fit_dict, N2_seqs, lib_variants): print (\"writing: %s\" % outfile) outfile",
"def main(): filenames = glob.glob('result/NA_Epi_*.tsv') outfile = 'result/NA_compile_results.tsv' lib_variants = read_lib_variants('data/lib_variants.tsv') N2_seqs =",
"'pos' in line: continue pos, muts = line.rstrip().rsplit(\"\\t\") lib_variants[pos] = muts.rsplit(',') return lib_variants",
"continue mut, sample, input_count, rep1_count, rep2_count, rep1_fit, rep2_fit, fit = line.rstrip().rsplit(\"\\t\") if check_mut_in_lib(mut,",
"in mut_list: WT_seq = N2_seqs[strain] full_seq = mutate_full_protein(WT_seq, mut, positions) #pI = str(np.mean([PA('A'+aa+'A').isoelectric_point()",
"#pI = str(PA(mut).isoelectric_point()) pI = str(PA(full_seq).isoelectric_point()) chg = str(calculate_charge(mut)) fit = fit_dict[strain][mut]['fit'] R1fit",
"check_mut_in_lib(mut, lib_variants): if mut == 'WT': return 'yes' for m in mut.rsplit('-'): pos",
"strain, seq = line.rstrip().rsplit(\"\\t\") WT_seqs[strain] = seq return WT_seqs def read_fasta(filename): refseq_dict =",
"= mutate_full_protein(WT_seq, mut, positions) #pI = str(np.mean([PA('A'+aa+'A').isoelectric_point() for aa in mut])) #pI =",
"'w') mut_list = fit_dict['HK68'].keys() header = \"\\t\".join(['ID', 'strain', 'pI', 'charge', 'rep1_fit', 'rep2_fit', 'fit'])",
"pos, mutaa in zip(positions, mut): mut_seq = mut_seq[0:pos-1]+mutaa+mut_seq[pos::] return mut_seq def calculate_charge(mut): charge",
"= seq return WT_seqs def read_fasta(filename): refseq_dict = {} records = SeqIO.parse(filename,\"fasta\") for",
"from Bio import SeqIO from collections import defaultdict from Bio.SeqUtils.ProtParam import ProteinAnalysis as",
"import glob import numpy as np from Bio import SeqIO from collections import",
"import sys import glob import numpy as np from Bio import SeqIO from",
"line in infile.readlines(): if 'strain' in line: continue strain, seq = line.rstrip().rsplit(\"\\t\") WT_seqs[strain]",
"'rep2_fit', 'fit']) outfile.write(header+\"\\n\") positions = (sorted(map(int,list(lib_variants.keys())))) for strain in ['HK68','Bk79','Bei89','Mos99','Vic11','HK19']: for mut in",
"= read_fasta('Fasta/N2.fa') WT_seqs = read_WT_seqs('data/WT_seq.tsv') fit_dict = defaultdict(dict) for filename in filenames: strain",
"ID += Mut.rsplit(str(residue))[1][0] else: ID += aa return ID def check_mut_in_lib(mut, lib_variants): if",
"for residue, aa in zip(residues, WTseq): if str(residue) in Mut: ID += Mut.rsplit(str(residue))[1][0]",
"mut.rsplit('-'): pos = m[1:-1] aa = m[-1] if pos not in lib_variants.keys(): return",
"+= mut.count('R') return charge def write_output_file(outfile, fit_dict, N2_seqs, lib_variants): print (\"writing: %s\" %",
"pI, chg, R1fit, R2fit, fit])+\"\\n\") outfile.close() def main(): filenames = glob.glob('result/NA_Epi_*.tsv') outfile =",
"for line in infile.readlines(): if 'Mut' in line: continue mut, sample, input_count, rep1_count,",
"< 10: continue ID = WTseq if mut == 'WT' else Mut2ID(mut, WTseq,",
"= \"\\t\".join(['ID', 'strain', 'pI', 'charge', 'rep1_fit', 'rep2_fit', 'fit']) outfile.write(header+\"\\n\") positions = (sorted(map(int,list(lib_variants.keys())))) for",
"infile.readlines(): if 'Mut' in line: continue mut, sample, input_count, rep1_count, rep2_count, rep1_fit, rep2_fit,",
"str(PA(mut).isoelectric_point()) pI = str(PA(full_seq).isoelectric_point()) chg = str(calculate_charge(mut)) fit = fit_dict[strain][mut]['fit'] R1fit = fit_dict[strain][mut]['fit_R1']",
"in Mut: ID += Mut.rsplit(str(residue))[1][0] else: ID += aa return ID def check_mut_in_lib(mut,",
"line.rstrip().rsplit(\"\\t\") lib_variants[pos] = muts.rsplit(',') return lib_variants def read_WT_seqs(filename): WT_seqs = {} infile =",
"mutate_full_protein(WT_seq, mut, positions): mut_seq = WT_seq for pos, mutaa in zip(positions, mut): mut_seq",
"= glob.glob('result/NA_Epi_*.tsv') outfile = 'result/NA_compile_results.tsv' lib_variants = read_lib_variants('data/lib_variants.tsv') N2_seqs = read_fasta('Fasta/N2.fa') WT_seqs =",
"record in records: ID = str(record.id) seq = str(record.seq) refseq_dict[ID] = seq return",
"pos, muts = line.rstrip().rsplit(\"\\t\") lib_variants[pos] = muts.rsplit(',') return lib_variants def read_WT_seqs(filename): WT_seqs =",
"== 'WT' else Mut2ID(mut, WTseq, sorted(lib_variants.keys(), key= lambda x:int(x))) fit_dict[strain][ID] = {'input_count': input_count,",
"{} records = SeqIO.parse(filename,\"fasta\") for record in records: ID = str(record.id) seq =",
"= open(outfile, 'w') mut_list = fit_dict['HK68'].keys() header = \"\\t\".join(['ID', 'strain', 'pI', 'charge', 'rep1_fit',",
"str(calculate_charge(mut)) fit = fit_dict[strain][mut]['fit'] R1fit = fit_dict[strain][mut]['fit_R1'] R2fit = fit_dict[strain][mut]['fit_R2'] outfile.write(\"\\t\".join([mut, strain, pI,",
"'yes' for m in mut.rsplit('-'): pos = m[1:-1] aa = m[-1] if pos",
"for line in infile.readlines(): if 'pos' in line: continue pos, muts = line.rstrip().rsplit(\"\\t\")",
"mut.count('R') return charge def write_output_file(outfile, fit_dict, N2_seqs, lib_variants): print (\"writing: %s\" % outfile)",
"input_count, 'fit':fit, 'fit_R1':rep1_fit, 'fit_R2':rep2_fit} return fit_dict def mutate_full_protein(WT_seq, mut, positions): mut_seq = WT_seq",
"lib_variants): print (\"writing: %s\" % outfile) outfile = open(outfile, 'w') mut_list = fit_dict['HK68'].keys()",
"in lib_variants.keys(): return 'no' elif aa not in lib_variants[pos]: return 'no' return 'yes'",
"lib_variants[pos]: return 'no' return 'yes' def read_lib_variants(filename): lib_variants = {} infile = open(filename,",
"lib_variants def read_WT_seqs(filename): WT_seqs = {} infile = open(filename, 'r') for line in",
"filename.rsplit('_')[-1].rsplit('.')[0] WTseq = WT_seqs[strain] fit_dict = read_fitness_data(filename, fit_dict, WTseq, lib_variants, strain) write_output_file(outfile, fit_dict,",
"if pos not in lib_variants.keys(): return 'no' elif aa not in lib_variants[pos]: return",
"def read_lib_variants(filename): lib_variants = {} infile = open(filename, 'r') for line in infile.readlines():",
"in lib_variants[pos]: return 'no' return 'yes' def read_lib_variants(filename): lib_variants = {} infile =",
"fit_dict, WTseq, lib_variants, strain) write_output_file(outfile, fit_dict, N2_seqs, lib_variants) if __name__ == \"__main__\": main()",
"= str(calculate_charge(mut)) fit = fit_dict[strain][mut]['fit'] R1fit = fit_dict[strain][mut]['fit_R1'] R2fit = fit_dict[strain][mut]['fit_R2'] outfile.write(\"\\t\".join([mut, strain,",
"mut.count('D') charge -= mut.count('E') charge += mut.count('K') charge += mut.count('R') return charge def",
"'fit']) outfile.write(header+\"\\n\") positions = (sorted(map(int,list(lib_variants.keys())))) for strain in ['HK68','Bk79','Bei89','Mos99','Vic11','HK19']: for mut in mut_list:",
"== 'WT': return 'yes' for m in mut.rsplit('-'): pos = m[1:-1] aa =",
"if int(input_count) < 10: continue ID = WTseq if mut == 'WT' else",
"read_WT_seqs('data/WT_seq.tsv') fit_dict = defaultdict(dict) for filename in filenames: strain = filename.rsplit('_')[-1].rsplit('.')[0] WTseq =",
"= m[1:-1] aa = m[-1] if pos not in lib_variants.keys(): return 'no' elif",
"fit = fit_dict[strain][mut]['fit'] R1fit = fit_dict[strain][mut]['fit_R1'] R2fit = fit_dict[strain][mut]['fit_R2'] outfile.write(\"\\t\".join([mut, strain, pI, chg,",
"R2fit = fit_dict[strain][mut]['fit_R2'] outfile.write(\"\\t\".join([mut, strain, pI, chg, R1fit, R2fit, fit])+\"\\n\") outfile.close() def main():",
"= str(record.id) seq = str(record.seq) refseq_dict[ID] = seq return refseq_dict def read_fitness_data(filename, fit_dict,",
"WT_seqs = {} infile = open(filename, 'r') for line in infile.readlines(): if 'strain'",
"fit_dict, WTseq, lib_variants, strain): infile = open(filename, 'r') for line in infile.readlines(): if",
"= '' for residue, aa in zip(residues, WTseq): if str(residue) in Mut: ID",
"def read_fasta(filename): refseq_dict = {} records = SeqIO.parse(filename,\"fasta\") for record in records: ID",
"-= mut.count('E') charge += mut.count('K') charge += mut.count('R') return charge def write_output_file(outfile, fit_dict,",
"read_fitness_data(filename, fit_dict, WTseq, lib_variants, strain) write_output_file(outfile, fit_dict, N2_seqs, lib_variants) if __name__ == \"__main__\":",
"strain = filename.rsplit('_')[-1].rsplit('.')[0] WTseq = WT_seqs[strain] fit_dict = read_fitness_data(filename, fit_dict, WTseq, lib_variants, strain)",
"ID = WTseq if mut == 'WT' else Mut2ID(mut, WTseq, sorted(lib_variants.keys(), key= lambda",
"def mutate_full_protein(WT_seq, mut, positions): mut_seq = WT_seq for pos, mutaa in zip(positions, mut):",
"N2_seqs, lib_variants): print (\"writing: %s\" % outfile) outfile = open(outfile, 'w') mut_list =",
"chg = str(calculate_charge(mut)) fit = fit_dict[strain][mut]['fit'] R1fit = fit_dict[strain][mut]['fit_R1'] R2fit = fit_dict[strain][mut]['fit_R2'] outfile.write(\"\\t\".join([mut,",
"Bio import SeqIO from collections import defaultdict from Bio.SeqUtils.ProtParam import ProteinAnalysis as PA",
"mutaa in zip(positions, mut): mut_seq = mut_seq[0:pos-1]+mutaa+mut_seq[pos::] return mut_seq def calculate_charge(mut): charge =",
"= WT_seqs[strain] fit_dict = read_fitness_data(filename, fit_dict, WTseq, lib_variants, strain) write_output_file(outfile, fit_dict, N2_seqs, lib_variants)",
"mut == 'WT': return 'yes' for m in mut.rsplit('-'): pos = m[1:-1] aa",
"check_mut_in_lib(mut, lib_variants) == 'no': continue if int(input_count) < 10: continue ID = WTseq",
"read_fitness_data(filename, fit_dict, WTseq, lib_variants, strain): infile = open(filename, 'r') for line in infile.readlines():",
"in infile.readlines(): if 'Mut' in line: continue mut, sample, input_count, rep1_count, rep2_count, rep1_fit,",
"open(filename, 'r') for line in infile.readlines(): if 'Mut' in line: continue mut, sample,",
"= line.rstrip().rsplit(\"\\t\") WT_seqs[strain] = seq return WT_seqs def read_fasta(filename): refseq_dict = {} records",
"m in mut.rsplit('-'): pos = m[1:-1] aa = m[-1] if pos not in",
"from Bio.SeqUtils.ProtParam import ProteinAnalysis as PA def Mut2ID(Mut, WTseq, residues): ID = ''",
"WT_seqs[strain] = seq return WT_seqs def read_fasta(filename): refseq_dict = {} records = SeqIO.parse(filename,\"fasta\")",
"for pos, mutaa in zip(positions, mut): mut_seq = mut_seq[0:pos-1]+mutaa+mut_seq[pos::] return mut_seq def calculate_charge(mut):",
"for aa in mut])) #pI = str(PA('A'+mut+'A').isoelectric_point()) #pI = str(PA(mut).isoelectric_point()) pI = str(PA(full_seq).isoelectric_point())",
"outfile) outfile = open(outfile, 'w') mut_list = fit_dict['HK68'].keys() header = \"\\t\".join(['ID', 'strain', 'pI',",
"= fit_dict[strain][mut]['fit_R2'] outfile.write(\"\\t\".join([mut, strain, pI, chg, R1fit, R2fit, fit])+\"\\n\") outfile.close() def main(): filenames",
"= open(filename, 'r') for line in infile.readlines(): if 'strain' in line: continue strain,",
"filenames: strain = filename.rsplit('_')[-1].rsplit('.')[0] WTseq = WT_seqs[strain] fit_dict = read_fitness_data(filename, fit_dict, WTseq, lib_variants,",
"'WT': return 'yes' for m in mut.rsplit('-'): pos = m[1:-1] aa = m[-1]",
"continue ID = WTseq if mut == 'WT' else Mut2ID(mut, WTseq, sorted(lib_variants.keys(), key=",
"WTseq, residues): ID = '' for residue, aa in zip(residues, WTseq): if str(residue)",
"= 0 charge -= mut.count('D') charge -= mut.count('E') charge += mut.count('K') charge +=",
"pos = m[1:-1] aa = m[-1] if pos not in lib_variants.keys(): return 'no'",
"calculate_charge(mut): charge = 0 charge -= mut.count('D') charge -= mut.count('E') charge += mut.count('K')",
"0 charge -= mut.count('D') charge -= mut.count('E') charge += mut.count('K') charge += mut.count('R')",
"WT_seqs def read_fasta(filename): refseq_dict = {} records = SeqIO.parse(filename,\"fasta\") for record in records:",
"N2_seqs = read_fasta('Fasta/N2.fa') WT_seqs = read_WT_seqs('data/WT_seq.tsv') fit_dict = defaultdict(dict) for filename in filenames:",
"strain, pI, chg, R1fit, R2fit, fit])+\"\\n\") outfile.close() def main(): filenames = glob.glob('result/NA_Epi_*.tsv') outfile",
"= str(PA('A'+mut+'A').isoelectric_point()) #pI = str(PA(mut).isoelectric_point()) pI = str(PA(full_seq).isoelectric_point()) chg = str(calculate_charge(mut)) fit =",
"= fit_dict[strain][mut]['fit'] R1fit = fit_dict[strain][mut]['fit_R1'] R2fit = fit_dict[strain][mut]['fit_R2'] outfile.write(\"\\t\".join([mut, strain, pI, chg, R1fit,",
"'r') for line in infile.readlines(): if 'pos' in line: continue pos, muts =",
"lib_variants = {} infile = open(filename, 'r') for line in infile.readlines(): if 'pos'",
"= open(filename, 'r') for line in infile.readlines(): if 'Mut' in line: continue mut,",
"10: continue ID = WTseq if mut == 'WT' else Mut2ID(mut, WTseq, sorted(lib_variants.keys(),",
"Mut: ID += Mut.rsplit(str(residue))[1][0] else: ID += aa return ID def check_mut_in_lib(mut, lib_variants):",
"'result/NA_compile_results.tsv' lib_variants = read_lib_variants('data/lib_variants.tsv') N2_seqs = read_fasta('Fasta/N2.fa') WT_seqs = read_WT_seqs('data/WT_seq.tsv') fit_dict = defaultdict(dict)",
"fit_dict = read_fitness_data(filename, fit_dict, WTseq, lib_variants, strain) write_output_file(outfile, fit_dict, N2_seqs, lib_variants) if __name__",
"mut.count('E') charge += mut.count('K') charge += mut.count('R') return charge def write_output_file(outfile, fit_dict, N2_seqs,",
"continue strain, seq = line.rstrip().rsplit(\"\\t\") WT_seqs[strain] = seq return WT_seqs def read_fasta(filename): refseq_dict",
"+= mut.count('K') charge += mut.count('R') return charge def write_output_file(outfile, fit_dict, N2_seqs, lib_variants): print",
"return 'yes' for m in mut.rsplit('-'): pos = m[1:-1] aa = m[-1] if",
"refseq_dict[ID] = seq return refseq_dict def read_fitness_data(filename, fit_dict, WTseq, lib_variants, strain): infile =",
"= m[-1] if pos not in lib_variants.keys(): return 'no' elif aa not in",
"infile.readlines(): if 'strain' in line: continue strain, seq = line.rstrip().rsplit(\"\\t\") WT_seqs[strain] = seq",
"WT_seq = N2_seqs[strain] full_seq = mutate_full_protein(WT_seq, mut, positions) #pI = str(np.mean([PA('A'+aa+'A').isoelectric_point() for aa",
"seq return WT_seqs def read_fasta(filename): refseq_dict = {} records = SeqIO.parse(filename,\"fasta\") for record",
"if 'pos' in line: continue pos, muts = line.rstrip().rsplit(\"\\t\") lib_variants[pos] = muts.rsplit(',') return",
"for strain in ['HK68','Bk79','Bei89','Mos99','Vic11','HK19']: for mut in mut_list: WT_seq = N2_seqs[strain] full_seq =",
"WTseq if mut == 'WT' else Mut2ID(mut, WTseq, sorted(lib_variants.keys(), key= lambda x:int(x))) fit_dict[strain][ID]",
"seq return refseq_dict def read_fitness_data(filename, fit_dict, WTseq, lib_variants, strain): infile = open(filename, 'r')",
"WTseq, sorted(lib_variants.keys(), key= lambda x:int(x))) fit_dict[strain][ID] = {'input_count': input_count, 'fit':fit, 'fit_R1':rep1_fit, 'fit_R2':rep2_fit} return",
"filenames = glob.glob('result/NA_Epi_*.tsv') outfile = 'result/NA_compile_results.tsv' lib_variants = read_lib_variants('data/lib_variants.tsv') N2_seqs = read_fasta('Fasta/N2.fa') WT_seqs",
"charge -= mut.count('E') charge += mut.count('K') charge += mut.count('R') return charge def write_output_file(outfile,",
"mut_seq = WT_seq for pos, mutaa in zip(positions, mut): mut_seq = mut_seq[0:pos-1]+mutaa+mut_seq[pos::] return",
"Mut.rsplit(str(residue))[1][0] else: ID += aa return ID def check_mut_in_lib(mut, lib_variants): if mut ==",
"else: ID += aa return ID def check_mut_in_lib(mut, lib_variants): if mut == 'WT':",
"<filename>script/compile_fit_result.py<gh_stars>1-10 #!/usr/bin/python import os import sys import glob import numpy as np from",
"'no': continue if int(input_count) < 10: continue ID = WTseq if mut ==",
"full_seq = mutate_full_protein(WT_seq, mut, positions) #pI = str(np.mean([PA('A'+aa+'A').isoelectric_point() for aa in mut])) #pI",
"in infile.readlines(): if 'strain' in line: continue strain, seq = line.rstrip().rsplit(\"\\t\") WT_seqs[strain] =",
"lib_variants.keys(): return 'no' elif aa not in lib_variants[pos]: return 'no' return 'yes' def",
"aa return ID def check_mut_in_lib(mut, lib_variants): if mut == 'WT': return 'yes' for",
"in zip(positions, mut): mut_seq = mut_seq[0:pos-1]+mutaa+mut_seq[pos::] return mut_seq def calculate_charge(mut): charge = 0",
"open(filename, 'r') for line in infile.readlines(): if 'pos' in line: continue pos, muts",
"elif aa not in lib_variants[pos]: return 'no' return 'yes' def read_lib_variants(filename): lib_variants =",
"mut, positions): mut_seq = WT_seq for pos, mutaa in zip(positions, mut): mut_seq =",
"import defaultdict from Bio.SeqUtils.ProtParam import ProteinAnalysis as PA def Mut2ID(Mut, WTseq, residues): ID",
"SeqIO from collections import defaultdict from Bio.SeqUtils.ProtParam import ProteinAnalysis as PA def Mut2ID(Mut,",
"zip(residues, WTseq): if str(residue) in Mut: ID += Mut.rsplit(str(residue))[1][0] else: ID += aa",
"'strain' in line: continue strain, seq = line.rstrip().rsplit(\"\\t\") WT_seqs[strain] = seq return WT_seqs",
"read_lib_variants('data/lib_variants.tsv') N2_seqs = read_fasta('Fasta/N2.fa') WT_seqs = read_WT_seqs('data/WT_seq.tsv') fit_dict = defaultdict(dict) for filename in",
"defaultdict from Bio.SeqUtils.ProtParam import ProteinAnalysis as PA def Mut2ID(Mut, WTseq, residues): ID =",
"defaultdict(dict) for filename in filenames: strain = filename.rsplit('_')[-1].rsplit('.')[0] WTseq = WT_seqs[strain] fit_dict =",
"def check_mut_in_lib(mut, lib_variants): if mut == 'WT': return 'yes' for m in mut.rsplit('-'):",
"in filenames: strain = filename.rsplit('_')[-1].rsplit('.')[0] WTseq = WT_seqs[strain] fit_dict = read_fitness_data(filename, fit_dict, WTseq,",
"from collections import defaultdict from Bio.SeqUtils.ProtParam import ProteinAnalysis as PA def Mut2ID(Mut, WTseq,",
"infile.readlines(): if 'pos' in line: continue pos, muts = line.rstrip().rsplit(\"\\t\") lib_variants[pos] = muts.rsplit(',')",
"= WTseq if mut == 'WT' else Mut2ID(mut, WTseq, sorted(lib_variants.keys(), key= lambda x:int(x)))",
"for record in records: ID = str(record.id) seq = str(record.seq) refseq_dict[ID] = seq",
"%s\" % outfile) outfile = open(outfile, 'w') mut_list = fit_dict['HK68'].keys() header = \"\\t\".join(['ID',",
"str(record.seq) refseq_dict[ID] = seq return refseq_dict def read_fitness_data(filename, fit_dict, WTseq, lib_variants, strain): infile",
"mut.count('K') charge += mut.count('R') return charge def write_output_file(outfile, fit_dict, N2_seqs, lib_variants): print (\"writing:",
"for filename in filenames: strain = filename.rsplit('_')[-1].rsplit('.')[0] WTseq = WT_seqs[strain] fit_dict = read_fitness_data(filename,",
"= {} infile = open(filename, 'r') for line in infile.readlines(): if 'strain' in",
"'r') for line in infile.readlines(): if 'Mut' in line: continue mut, sample, input_count,",
"charge += mut.count('K') charge += mut.count('R') return charge def write_output_file(outfile, fit_dict, N2_seqs, lib_variants):",
"= N2_seqs[strain] full_seq = mutate_full_protein(WT_seq, mut, positions) #pI = str(np.mean([PA('A'+aa+'A').isoelectric_point() for aa in",
"str(np.mean([PA('A'+aa+'A').isoelectric_point() for aa in mut])) #pI = str(PA('A'+mut+'A').isoelectric_point()) #pI = str(PA(mut).isoelectric_point()) pI =",
"not in lib_variants.keys(): return 'no' elif aa not in lib_variants[pos]: return 'no' return",
"+= Mut.rsplit(str(residue))[1][0] else: ID += aa return ID def check_mut_in_lib(mut, lib_variants): if mut",
"sample, input_count, rep1_count, rep2_count, rep1_fit, rep2_fit, fit = line.rstrip().rsplit(\"\\t\") if check_mut_in_lib(mut, lib_variants) ==",
"outfile = 'result/NA_compile_results.tsv' lib_variants = read_lib_variants('data/lib_variants.tsv') N2_seqs = read_fasta('Fasta/N2.fa') WT_seqs = read_WT_seqs('data/WT_seq.tsv') fit_dict",
"mut])) #pI = str(PA('A'+mut+'A').isoelectric_point()) #pI = str(PA(mut).isoelectric_point()) pI = str(PA(full_seq).isoelectric_point()) chg = str(calculate_charge(mut))",
"if mut == 'WT': return 'yes' for m in mut.rsplit('-'): pos = m[1:-1]",
"residues): ID = '' for residue, aa in zip(residues, WTseq): if str(residue) in",
"str(residue) in Mut: ID += Mut.rsplit(str(residue))[1][0] else: ID += aa return ID def",
"positions): mut_seq = WT_seq for pos, mutaa in zip(positions, mut): mut_seq = mut_seq[0:pos-1]+mutaa+mut_seq[pos::]",
"for line in infile.readlines(): if 'strain' in line: continue strain, seq = line.rstrip().rsplit(\"\\t\")",
"np from Bio import SeqIO from collections import defaultdict from Bio.SeqUtils.ProtParam import ProteinAnalysis",
"fit_dict def mutate_full_protein(WT_seq, mut, positions): mut_seq = WT_seq for pos, mutaa in zip(positions,",
"filename in filenames: strain = filename.rsplit('_')[-1].rsplit('.')[0] WTseq = WT_seqs[strain] fit_dict = read_fitness_data(filename, fit_dict,",
"= {} records = SeqIO.parse(filename,\"fasta\") for record in records: ID = str(record.id) seq",
"for mut in mut_list: WT_seq = N2_seqs[strain] full_seq = mutate_full_protein(WT_seq, mut, positions) #pI",
"read_lib_variants(filename): lib_variants = {} infile = open(filename, 'r') for line in infile.readlines(): if",
"mut == 'WT' else Mut2ID(mut, WTseq, sorted(lib_variants.keys(), key= lambda x:int(x))) fit_dict[strain][ID] = {'input_count':",
"ID += aa return ID def check_mut_in_lib(mut, lib_variants): if mut == 'WT': return",
"#pI = str(np.mean([PA('A'+aa+'A').isoelectric_point() for aa in mut])) #pI = str(PA('A'+mut+'A').isoelectric_point()) #pI = str(PA(mut).isoelectric_point())",
"= line.rstrip().rsplit(\"\\t\") lib_variants[pos] = muts.rsplit(',') return lib_variants def read_WT_seqs(filename): WT_seqs = {} infile",
"aa in mut])) #pI = str(PA('A'+mut+'A').isoelectric_point()) #pI = str(PA(mut).isoelectric_point()) pI = str(PA(full_seq).isoelectric_point()) chg",
"WTseq): if str(residue) in Mut: ID += Mut.rsplit(str(residue))[1][0] else: ID += aa return",
"zip(positions, mut): mut_seq = mut_seq[0:pos-1]+mutaa+mut_seq[pos::] return mut_seq def calculate_charge(mut): charge = 0 charge",
"line: continue mut, sample, input_count, rep1_count, rep2_count, rep1_fit, rep2_fit, fit = line.rstrip().rsplit(\"\\t\") if",
"= open(filename, 'r') for line in infile.readlines(): if 'pos' in line: continue pos,",
"return 'yes' def read_lib_variants(filename): lib_variants = {} infile = open(filename, 'r') for line",
"(\"writing: %s\" % outfile) outfile = open(outfile, 'w') mut_list = fit_dict['HK68'].keys() header =",
"mut_seq = mut_seq[0:pos-1]+mutaa+mut_seq[pos::] return mut_seq def calculate_charge(mut): charge = 0 charge -= mut.count('D')",
"= str(PA(mut).isoelectric_point()) pI = str(PA(full_seq).isoelectric_point()) chg = str(calculate_charge(mut)) fit = fit_dict[strain][mut]['fit'] R1fit =",
"fit = line.rstrip().rsplit(\"\\t\") if check_mut_in_lib(mut, lib_variants) == 'no': continue if int(input_count) < 10:",
"= str(PA(full_seq).isoelectric_point()) chg = str(calculate_charge(mut)) fit = fit_dict[strain][mut]['fit'] R1fit = fit_dict[strain][mut]['fit_R1'] R2fit =",
"R2fit, fit])+\"\\n\") outfile.close() def main(): filenames = glob.glob('result/NA_Epi_*.tsv') outfile = 'result/NA_compile_results.tsv' lib_variants =",
"import os import sys import glob import numpy as np from Bio import",
"ID = str(record.id) seq = str(record.seq) refseq_dict[ID] = seq return refseq_dict def read_fitness_data(filename,",
"as np from Bio import SeqIO from collections import defaultdict from Bio.SeqUtils.ProtParam import",
"return mut_seq def calculate_charge(mut): charge = 0 charge -= mut.count('D') charge -= mut.count('E')",
"line: continue pos, muts = line.rstrip().rsplit(\"\\t\") lib_variants[pos] = muts.rsplit(',') return lib_variants def read_WT_seqs(filename):",
"main(): filenames = glob.glob('result/NA_Epi_*.tsv') outfile = 'result/NA_compile_results.tsv' lib_variants = read_lib_variants('data/lib_variants.tsv') N2_seqs = read_fasta('Fasta/N2.fa')",
"+= aa return ID def check_mut_in_lib(mut, lib_variants): if mut == 'WT': return 'yes'",
"fit_dict[strain][mut]['fit_R1'] R2fit = fit_dict[strain][mut]['fit_R2'] outfile.write(\"\\t\".join([mut, strain, pI, chg, R1fit, R2fit, fit])+\"\\n\") outfile.close() def",
"mut_seq def calculate_charge(mut): charge = 0 charge -= mut.count('D') charge -= mut.count('E') charge",
"return refseq_dict def read_fitness_data(filename, fit_dict, WTseq, lib_variants, strain): infile = open(filename, 'r') for",
"= defaultdict(dict) for filename in filenames: strain = filename.rsplit('_')[-1].rsplit('.')[0] WTseq = WT_seqs[strain] fit_dict",
"line in infile.readlines(): if 'pos' in line: continue pos, muts = line.rstrip().rsplit(\"\\t\") lib_variants[pos]",
"for m in mut.rsplit('-'): pos = m[1:-1] aa = m[-1] if pos not",
"WTseq, lib_variants, strain): infile = open(filename, 'r') for line in infile.readlines(): if 'Mut'",
"#pI = str(PA('A'+mut+'A').isoelectric_point()) #pI = str(PA(mut).isoelectric_point()) pI = str(PA(full_seq).isoelectric_point()) chg = str(calculate_charge(mut)) fit",
"in line: continue pos, muts = line.rstrip().rsplit(\"\\t\") lib_variants[pos] = muts.rsplit(',') return lib_variants def",
"charge -= mut.count('D') charge -= mut.count('E') charge += mut.count('K') charge += mut.count('R') return",
"{'input_count': input_count, 'fit':fit, 'fit_R1':rep1_fit, 'fit_R2':rep2_fit} return fit_dict def mutate_full_protein(WT_seq, mut, positions): mut_seq =",
"sorted(lib_variants.keys(), key= lambda x:int(x))) fit_dict[strain][ID] = {'input_count': input_count, 'fit':fit, 'fit_R1':rep1_fit, 'fit_R2':rep2_fit} return fit_dict",
"else Mut2ID(mut, WTseq, sorted(lib_variants.keys(), key= lambda x:int(x))) fit_dict[strain][ID] = {'input_count': input_count, 'fit':fit, 'fit_R1':rep1_fit,",
"ProteinAnalysis as PA def Mut2ID(Mut, WTseq, residues): ID = '' for residue, aa",
"(sorted(map(int,list(lib_variants.keys())))) for strain in ['HK68','Bk79','Bei89','Mos99','Vic11','HK19']: for mut in mut_list: WT_seq = N2_seqs[strain] full_seq",
"= fit_dict['HK68'].keys() header = \"\\t\".join(['ID', 'strain', 'pI', 'charge', 'rep1_fit', 'rep2_fit', 'fit']) outfile.write(header+\"\\n\") positions",
"import numpy as np from Bio import SeqIO from collections import defaultdict from",
"% outfile) outfile = open(outfile, 'w') mut_list = fit_dict['HK68'].keys() header = \"\\t\".join(['ID', 'strain',",
"= SeqIO.parse(filename,\"fasta\") for record in records: ID = str(record.id) seq = str(record.seq) refseq_dict[ID]",
"pos not in lib_variants.keys(): return 'no' elif aa not in lib_variants[pos]: return 'no'",
"read_WT_seqs(filename): WT_seqs = {} infile = open(filename, 'r') for line in infile.readlines(): if",
"str(PA('A'+mut+'A').isoelectric_point()) #pI = str(PA(mut).isoelectric_point()) pI = str(PA(full_seq).isoelectric_point()) chg = str(calculate_charge(mut)) fit = fit_dict[strain][mut]['fit']",
"if str(residue) in Mut: ID += Mut.rsplit(str(residue))[1][0] else: ID += aa return ID",
"lib_variants[pos] = muts.rsplit(',') return lib_variants def read_WT_seqs(filename): WT_seqs = {} infile = open(filename,",
"rep2_fit, fit = line.rstrip().rsplit(\"\\t\") if check_mut_in_lib(mut, lib_variants) == 'no': continue if int(input_count) <",
"outfile = open(outfile, 'w') mut_list = fit_dict['HK68'].keys() header = \"\\t\".join(['ID', 'strain', 'pI', 'charge',",
"seq = str(record.seq) refseq_dict[ID] = seq return refseq_dict def read_fitness_data(filename, fit_dict, WTseq, lib_variants,",
"return 'no' elif aa not in lib_variants[pos]: return 'no' return 'yes' def read_lib_variants(filename):",
"print (\"writing: %s\" % outfile) outfile = open(outfile, 'w') mut_list = fit_dict['HK68'].keys() header",
"WT_seqs[strain] fit_dict = read_fitness_data(filename, fit_dict, WTseq, lib_variants, strain) write_output_file(outfile, fit_dict, N2_seqs, lib_variants) if",
"residue, aa in zip(residues, WTseq): if str(residue) in Mut: ID += Mut.rsplit(str(residue))[1][0] else:",
"infile = open(filename, 'r') for line in infile.readlines(): if 'pos' in line: continue",
"in records: ID = str(record.id) seq = str(record.seq) refseq_dict[ID] = seq return refseq_dict",
"if 'strain' in line: continue strain, seq = line.rstrip().rsplit(\"\\t\") WT_seqs[strain] = seq return",
"rep2_count, rep1_fit, rep2_fit, fit = line.rstrip().rsplit(\"\\t\") if check_mut_in_lib(mut, lib_variants) == 'no': continue if",
"= read_WT_seqs('data/WT_seq.tsv') fit_dict = defaultdict(dict) for filename in filenames: strain = filename.rsplit('_')[-1].rsplit('.')[0] WTseq",
"WT_seqs = read_WT_seqs('data/WT_seq.tsv') fit_dict = defaultdict(dict) for filename in filenames: strain = filename.rsplit('_')[-1].rsplit('.')[0]",
"= read_fitness_data(filename, fit_dict, WTseq, lib_variants, strain) write_output_file(outfile, fit_dict, N2_seqs, lib_variants) if __name__ ==",
"mut_seq[0:pos-1]+mutaa+mut_seq[pos::] return mut_seq def calculate_charge(mut): charge = 0 charge -= mut.count('D') charge -=",
"in ['HK68','Bk79','Bei89','Mos99','Vic11','HK19']: for mut in mut_list: WT_seq = N2_seqs[strain] full_seq = mutate_full_protein(WT_seq, mut,"
] |
[
"schema_file_contents = self.__get_data() @test(groups=['redfish.get_schema_content_invalid'], depends_on_groups=['redfish.get_schema']) def test_get_schema_content_invalid(self): \"\"\" Testing GET /Schemas/en/{identifier} 404s properly",
"dataId = member.get('@odata.id') assert_not_equal(None,dataId) dataId = dataId.split('/redfish/v1/Schemas/')[1] try: redfish().get_schema(dataId + '-invalid') fail(message='did not",
"from proboscis.asserts import assert_not_equal from proboscis.asserts import assert_true from proboscis.asserts import fail from",
"import assert_equal from proboscis.asserts import assert_false from proboscis.asserts import assert_raises from proboscis.asserts import",
"test from json import loads,dumps LOG = Log(__name__) @test(groups=['redfish.schema.tests'], depends_on_groups=['obm.tests']) class SchemaTests(object): def",
"{1}'.format(id,dataId)) assert_equal(type(schema_ref.get('Location')), list, message='expected list not found') location = schema_ref.get('Location')[0] assert_equal(type(location.get('Uri')), unicode, message='expected",
"proboscis.asserts import assert_true from proboscis.asserts import fail from proboscis import SkipTest from proboscis",
"= dataId.split('/redfish/v1/Schemas/')[1] redfish().get_schema(dataId) schema_ref = self.__get_data() LOG.debug(schema_ref,json=True) id = schema_ref.get('Id') assert_equal(dataId, id, message='unexpected",
"= dataId.split('/redfish/v1/Schemas/')[1] try: redfish().get_schema(dataId + '-invalid') fail(message='did not raise exception') except rest.ApiException as",
"404s properly \"\"\" assert_not_equal([], self.__locationUri) for member in self.__locationUri: assert_not_equal(None,member) dataId = member.split('/redfish/v1/SchemaStore/en/')[1]",
"<filename>test/tests/api/redfish_1_0/schema_tests.py from config.redfish1_0_config import * from modules.logger import Log from on_http_redfish_1_0 import RedfishvApi",
"redfish().get_schema(dataId) schema_ref = self.__get_data() LOG.debug(schema_ref,json=True) id = schema_ref.get('Id') assert_equal(dataId, id, message='unexpected id {0},",
"from on_http_redfish_1_0 import RedfishvApi as redfish from on_http_redfish_1_0 import rest from datetime import",
"break @test(groups=['redfish.get_schema_content'], depends_on_groups=['redfish.get_schema']) def test_get_schema_content(self): \"\"\" Testing GET /SchemaStore/en/{identifier} \"\"\" assert_not_equal([], self.__locationUri) for",
"= schemas @test(groups=['redfish.get_schema'], depends_on_groups=['redfish.list_schemas']) def test_get_schema(self): \"\"\" Testing GET /Schemas/{identifier} \"\"\" self.__membersList =",
"@test(groups=['redfish.get_schema'], depends_on_groups=['redfish.list_schemas']) def test_get_schema(self): \"\"\" Testing GET /Schemas/{identifier} \"\"\" self.__membersList = self.__schemaList.get('Members') assert_not_equal(None,",
"assert_equal(type(schema_ref.get('Location')), list, message='expected list not found') location = schema_ref.get('Location')[0] assert_equal(type(location.get('Uri')), unicode, message='expected uri",
"/Schemas \"\"\" redfish().list_schemas() schemas = self.__get_data() LOG.debug(schemas,json=True) assert_not_equal(0, len(schemas), message='Schema list was empty!')",
"was empty!') self.__schemaList = schemas @test(groups=['redfish.get_schema'], depends_on_groups=['redfish.list_schemas']) def test_get_schema(self): \"\"\" Testing GET /Schemas/{identifier}",
"depends_on_groups=['redfish.get_schema']) def test_get_schema_content_invalid(self): \"\"\" Testing GET /Schemas/en/{identifier} 404s properly \"\"\" assert_not_equal([], self.__locationUri) for",
"member in self.__membersList: dataId = member.get('@odata.id') assert_not_equal(None,dataId) dataId = dataId.split('/redfish/v1/Schemas/')[1] redfish().get_schema(dataId) schema_ref =",
"not found') location = schema_ref.get('Location')[0] assert_equal(type(location.get('Uri')), unicode, message='expected uri string not found') self.__locationUri.append(location.get('Uri'))",
"member.split('/redfish/v1/SchemaStore/en/')[1] redfish().get_schema_content(dataId) schema_file_contents = self.__get_data() @test(groups=['redfish.get_schema_content_invalid'], depends_on_groups=['redfish.get_schema']) def test_get_schema_content_invalid(self): \"\"\" Testing GET /Schemas/en/{identifier}",
"dataId = member.get('@odata.id') assert_not_equal(None,dataId) dataId = dataId.split('/redfish/v1/Schemas/')[1] redfish().get_schema(dataId) schema_ref = self.__get_data() LOG.debug(schema_ref,json=True) id",
"__get_data(self): return loads(self.__client.last_response.data) @test(groups=['redfish.list_schemas']) def test_list_schemas(self): \"\"\" Testing GET /Schemas \"\"\" redfish().list_schemas() schemas",
"= member.split('/redfish/v1/SchemaStore/en/')[1] try: redfish().get_schema_content(dataId + '-invalid') fail(message='did not raise exception') except rest.ApiException as",
"from proboscis.asserts import fail from proboscis import SkipTest from proboscis import test from",
"member.get('@odata.id') assert_not_equal(None,dataId) dataId = dataId.split('/redfish/v1/Schemas/')[1] try: redfish().get_schema(dataId + '-invalid') fail(message='did not raise exception')",
"/Schemas/{identifier} \"\"\" self.__membersList = self.__schemaList.get('Members') assert_not_equal(None, self.__membersList) for member in self.__membersList: dataId =",
"import datetime from proboscis.asserts import assert_equal from proboscis.asserts import assert_false from proboscis.asserts import",
"self.__membersList = self.__schemaList.get('Members') assert_not_equal(None, self.__membersList) for member in self.__membersList: dataId = member.get('@odata.id') assert_not_equal(None,dataId)",
"in self.__locationUri: assert_not_equal(None,member) dataId = member.split('/redfish/v1/SchemaStore/en/')[1] redfish().get_schema_content(dataId) schema_file_contents = self.__get_data() @test(groups=['redfish.get_schema_content_invalid'], depends_on_groups=['redfish.get_schema']) def",
"for member in self.__locationUri: assert_not_equal(None,member) dataId = member.split('/redfish/v1/SchemaStore/en/')[1] try: redfish().get_schema_content(dataId + '-invalid') fail(message='did",
"member in self.__locationUri: assert_not_equal(None,member) dataId = member.split('/redfish/v1/SchemaStore/en/')[1] redfish().get_schema_content(dataId) schema_file_contents = self.__get_data() @test(groups=['redfish.get_schema_content_invalid'], depends_on_groups=['redfish.get_schema'])",
"in self.__membersList: dataId = member.get('@odata.id') assert_not_equal(None,dataId) dataId = dataId.split('/redfish/v1/Schemas/')[1] redfish().get_schema(dataId) schema_ref = self.__get_data()",
"@test(groups=['redfish.list_schemas']) def test_list_schemas(self): \"\"\" Testing GET /Schemas \"\"\" redfish().list_schemas() schemas = self.__get_data() LOG.debug(schemas,json=True)",
"member in self.__membersList: dataId = member.get('@odata.id') assert_not_equal(None,dataId) dataId = dataId.split('/redfish/v1/Schemas/')[1] try: redfish().get_schema(dataId +",
"from proboscis.asserts import assert_raises from proboscis.asserts import assert_not_equal from proboscis.asserts import assert_true from",
"uri string not found') self.__locationUri.append(location.get('Uri')) @test(groups=['redfish.get_schema_invalid'], depends_on_groups=['redfish.list_schemas']) def test_get_schema_invalid(self): \"\"\" Testing GET /Schemas/{identifier}",
"config.redfish1_0_config import * from modules.logger import Log from on_http_redfish_1_0 import RedfishvApi as redfish",
"for member in self.__membersList: dataId = member.get('@odata.id') assert_not_equal(None,dataId) dataId = dataId.split('/redfish/v1/Schemas/')[1] try: redfish().get_schema(dataId",
"proboscis.asserts import assert_raises from proboscis.asserts import assert_not_equal from proboscis.asserts import assert_true from proboscis.asserts",
"None self.__membersList = None self.__locationUri = [] def __get_data(self): return loads(self.__client.last_response.data) @test(groups=['redfish.list_schemas']) def",
"from on_http_redfish_1_0 import rest from datetime import datetime from proboscis.asserts import assert_equal from",
"LOG = Log(__name__) @test(groups=['redfish.schema.tests'], depends_on_groups=['obm.tests']) class SchemaTests(object): def __init__(self): self.__client = config.api_client self.__schemaList",
"/SchemaStore/en/{identifier} \"\"\" assert_not_equal([], self.__locationUri) for member in self.__locationUri: assert_not_equal(None,member) dataId = member.split('/redfish/v1/SchemaStore/en/')[1] redfish().get_schema_content(dataId)",
"unicode, message='expected uri string not found') self.__locationUri.append(location.get('Uri')) @test(groups=['redfish.get_schema_invalid'], depends_on_groups=['redfish.list_schemas']) def test_get_schema_invalid(self): \"\"\" Testing",
"/Schemas/{identifier} 404s properly \"\"\" self.__membersList = self.__schemaList.get('Members') assert_not_equal(None, self.__membersList) for member in self.__membersList:",
"Testing GET /Schemas/{identifier} \"\"\" self.__membersList = self.__schemaList.get('Members') assert_not_equal(None, self.__membersList) for member in self.__membersList:",
"list was empty!') self.__schemaList = schemas @test(groups=['redfish.get_schema'], depends_on_groups=['redfish.list_schemas']) def test_get_schema(self): \"\"\" Testing GET",
"* from modules.logger import Log from on_http_redfish_1_0 import RedfishvApi as redfish from on_http_redfish_1_0",
"datetime import datetime from proboscis.asserts import assert_equal from proboscis.asserts import assert_false from proboscis.asserts",
"in self.__membersList: dataId = member.get('@odata.id') assert_not_equal(None,dataId) dataId = dataId.split('/redfish/v1/Schemas/')[1] try: redfish().get_schema(dataId + '-invalid')",
"loads,dumps LOG = Log(__name__) @test(groups=['redfish.schema.tests'], depends_on_groups=['obm.tests']) class SchemaTests(object): def __init__(self): self.__client = config.api_client",
"self.__schemaList = schemas @test(groups=['redfish.get_schema'], depends_on_groups=['redfish.list_schemas']) def test_get_schema(self): \"\"\" Testing GET /Schemas/{identifier} \"\"\" self.__membersList",
"list, message='expected list not found') location = schema_ref.get('Location')[0] assert_equal(type(location.get('Uri')), unicode, message='expected uri string",
"@test(groups=['redfish.get_schema_content_invalid'], depends_on_groups=['redfish.get_schema']) def test_get_schema_content_invalid(self): \"\"\" Testing GET /Schemas/en/{identifier} 404s properly \"\"\" assert_not_equal([], self.__locationUri)",
"def test_get_schema_content_invalid(self): \"\"\" Testing GET /Schemas/en/{identifier} 404s properly \"\"\" assert_not_equal([], self.__locationUri) for member",
"assert_not_equal(None,dataId) dataId = dataId.split('/redfish/v1/Schemas/')[1] redfish().get_schema(dataId) schema_ref = self.__get_data() LOG.debug(schema_ref,json=True) id = schema_ref.get('Id') assert_equal(dataId,",
"def test_get_schema_invalid(self): \"\"\" Testing GET /Schemas/{identifier} 404s properly \"\"\" self.__membersList = self.__schemaList.get('Members') assert_not_equal(None,",
"test_get_schema_invalid(self): \"\"\" Testing GET /Schemas/{identifier} 404s properly \"\"\" self.__membersList = self.__schemaList.get('Members') assert_not_equal(None, self.__membersList)",
"'-invalid') fail(message='did not raise exception') except rest.ApiException as e: assert_equal(404, e.status, message='unexpected response",
"expected 404'.format(e.status)) break @test(groups=['redfish.get_schema_content'], depends_on_groups=['redfish.get_schema']) def test_get_schema_content(self): \"\"\" Testing GET /SchemaStore/en/{identifier} \"\"\" assert_not_equal([],",
"@test(groups=['redfish.get_schema_content'], depends_on_groups=['redfish.get_schema']) def test_get_schema_content(self): \"\"\" Testing GET /SchemaStore/en/{identifier} \"\"\" assert_not_equal([], self.__locationUri) for member",
"= None self.__locationUri = [] def __get_data(self): return loads(self.__client.last_response.data) @test(groups=['redfish.list_schemas']) def test_list_schemas(self): \"\"\"",
"assert_not_equal(None,dataId) dataId = dataId.split('/redfish/v1/Schemas/')[1] try: redfish().get_schema(dataId + '-invalid') fail(message='did not raise exception') except",
"depends_on_groups=['redfish.list_schemas']) def test_get_schema(self): \"\"\" Testing GET /Schemas/{identifier} \"\"\" self.__membersList = self.__schemaList.get('Members') assert_not_equal(None, self.__membersList)",
"self.__get_data() LOG.debug(schema_ref,json=True) id = schema_ref.get('Id') assert_equal(dataId, id, message='unexpected id {0}, expected {1}'.format(id,dataId)) assert_equal(type(schema_ref.get('Location')),",
"member.get('@odata.id') assert_not_equal(None,dataId) dataId = dataId.split('/redfish/v1/Schemas/')[1] redfish().get_schema(dataId) schema_ref = self.__get_data() LOG.debug(schema_ref,json=True) id = schema_ref.get('Id')",
"\"\"\" redfish().list_schemas() schemas = self.__get_data() LOG.debug(schemas,json=True) assert_not_equal(0, len(schemas), message='Schema list was empty!') self.__schemaList",
"from proboscis.asserts import assert_equal from proboscis.asserts import assert_false from proboscis.asserts import assert_raises from",
"except rest.ApiException as e: assert_equal(404, e.status, message='unexpected response {0}, expected 404'.format(e.status)) break @test(groups=['redfish.get_schema_content'],",
"e.status, message='unexpected response {0}, expected 404'.format(e.status)) break @test(groups=['redfish.get_schema_content'], depends_on_groups=['redfish.get_schema']) def test_get_schema_content(self): \"\"\" Testing",
"assert_not_equal([], self.__locationUri) for member in self.__locationUri: assert_not_equal(None,member) dataId = member.split('/redfish/v1/SchemaStore/en/')[1] redfish().get_schema_content(dataId) schema_file_contents =",
"assert_not_equal from proboscis.asserts import assert_true from proboscis.asserts import fail from proboscis import SkipTest",
"404'.format(e.status)) break @test(groups=['redfish.get_schema_content'], depends_on_groups=['redfish.get_schema']) def test_get_schema_content(self): \"\"\" Testing GET /SchemaStore/en/{identifier} \"\"\" assert_not_equal([], self.__locationUri)",
"@test(groups=['redfish.get_schema_invalid'], depends_on_groups=['redfish.list_schemas']) def test_get_schema_invalid(self): \"\"\" Testing GET /Schemas/{identifier} 404s properly \"\"\" self.__membersList =",
"redfish from on_http_redfish_1_0 import rest from datetime import datetime from proboscis.asserts import assert_equal",
"self.__schemaList = None self.__membersList = None self.__locationUri = [] def __get_data(self): return loads(self.__client.last_response.data)",
"from config.redfish1_0_config import * from modules.logger import Log from on_http_redfish_1_0 import RedfishvApi as",
"assert_not_equal(0, len(schemas), message='Schema list was empty!') self.__schemaList = schemas @test(groups=['redfish.get_schema'], depends_on_groups=['redfish.list_schemas']) def test_get_schema(self):",
"self.__membersList) for member in self.__membersList: dataId = member.get('@odata.id') assert_not_equal(None,dataId) dataId = dataId.split('/redfish/v1/Schemas/')[1] redfish().get_schema(dataId)",
"import rest from datetime import datetime from proboscis.asserts import assert_equal from proboscis.asserts import",
"= schema_ref.get('Location')[0] assert_equal(type(location.get('Uri')), unicode, message='expected uri string not found') self.__locationUri.append(location.get('Uri')) @test(groups=['redfish.get_schema_invalid'], depends_on_groups=['redfish.list_schemas']) def",
"@test(groups=['redfish.schema.tests'], depends_on_groups=['obm.tests']) class SchemaTests(object): def __init__(self): self.__client = config.api_client self.__schemaList = None self.__membersList",
"Testing GET /Schemas/{identifier} 404s properly \"\"\" self.__membersList = self.__schemaList.get('Members') assert_not_equal(None, self.__membersList) for member",
"on_http_redfish_1_0 import RedfishvApi as redfish from on_http_redfish_1_0 import rest from datetime import datetime",
"message='unexpected id {0}, expected {1}'.format(id,dataId)) assert_equal(type(schema_ref.get('Location')), list, message='expected list not found') location =",
"redfish().get_schema(dataId + '-invalid') fail(message='did not raise exception') except rest.ApiException as e: assert_equal(404, e.status,",
"message='unexpected response {0}, expected 404'.format(e.status)) break @test(groups=['redfish.get_schema_content'], depends_on_groups=['redfish.get_schema']) def test_get_schema_content(self): \"\"\" Testing GET",
"self.__locationUri: assert_not_equal(None,member) dataId = member.split('/redfish/v1/SchemaStore/en/')[1] redfish().get_schema_content(dataId) schema_file_contents = self.__get_data() @test(groups=['redfish.get_schema_content_invalid'], depends_on_groups=['redfish.get_schema']) def test_get_schema_content_invalid(self):",
"redfish().get_schema_content(dataId + '-invalid') fail(message='did not raise exception') except rest.ApiException as e: assert_equal(404, e.status,",
"from proboscis import SkipTest from proboscis import test from json import loads,dumps LOG",
"self.__locationUri = [] def __get_data(self): return loads(self.__client.last_response.data) @test(groups=['redfish.list_schemas']) def test_list_schemas(self): \"\"\" Testing GET",
"\"\"\" Testing GET /Schemas/{identifier} 404s properly \"\"\" self.__membersList = self.__schemaList.get('Members') assert_not_equal(None, self.__membersList) for",
"\"\"\" assert_not_equal([], self.__locationUri) for member in self.__locationUri: assert_not_equal(None,member) dataId = member.split('/redfish/v1/SchemaStore/en/')[1] try: redfish().get_schema_content(dataId",
"= self.__schemaList.get('Members') assert_not_equal(None, self.__membersList) for member in self.__membersList: dataId = member.get('@odata.id') assert_not_equal(None,dataId) dataId",
"message='Schema list was empty!') self.__schemaList = schemas @test(groups=['redfish.get_schema'], depends_on_groups=['redfish.list_schemas']) def test_get_schema(self): \"\"\" Testing",
"import assert_not_equal from proboscis.asserts import assert_true from proboscis.asserts import fail from proboscis import",
"= self.__get_data() LOG.debug(schema_ref,json=True) id = schema_ref.get('Id') assert_equal(dataId, id, message='unexpected id {0}, expected {1}'.format(id,dataId))",
"= member.get('@odata.id') assert_not_equal(None,dataId) dataId = dataId.split('/redfish/v1/Schemas/')[1] try: redfish().get_schema(dataId + '-invalid') fail(message='did not raise",
"message='expected uri string not found') self.__locationUri.append(location.get('Uri')) @test(groups=['redfish.get_schema_invalid'], depends_on_groups=['redfish.list_schemas']) def test_get_schema_invalid(self): \"\"\" Testing GET",
"dataId.split('/redfish/v1/Schemas/')[1] try: redfish().get_schema(dataId + '-invalid') fail(message='did not raise exception') except rest.ApiException as e:",
"empty!') self.__schemaList = schemas @test(groups=['redfish.get_schema'], depends_on_groups=['redfish.list_schemas']) def test_get_schema(self): \"\"\" Testing GET /Schemas/{identifier} \"\"\"",
"LOG.debug(schema_ref,json=True) id = schema_ref.get('Id') assert_equal(dataId, id, message='unexpected id {0}, expected {1}'.format(id,dataId)) assert_equal(type(schema_ref.get('Location')), list,",
"\"\"\" self.__membersList = self.__schemaList.get('Members') assert_not_equal(None, self.__membersList) for member in self.__membersList: dataId = member.get('@odata.id')",
"assert_true from proboscis.asserts import fail from proboscis import SkipTest from proboscis import test",
"test_get_schema(self): \"\"\" Testing GET /Schemas/{identifier} \"\"\" self.__membersList = self.__schemaList.get('Members') assert_not_equal(None, self.__membersList) for member",
"GET /Schemas \"\"\" redfish().list_schemas() schemas = self.__get_data() LOG.debug(schemas,json=True) assert_not_equal(0, len(schemas), message='Schema list was",
"loads(self.__client.last_response.data) @test(groups=['redfish.list_schemas']) def test_list_schemas(self): \"\"\" Testing GET /Schemas \"\"\" redfish().list_schemas() schemas = self.__get_data()",
"self.__get_data() LOG.debug(schemas,json=True) assert_not_equal(0, len(schemas), message='Schema list was empty!') self.__schemaList = schemas @test(groups=['redfish.get_schema'], depends_on_groups=['redfish.list_schemas'])",
"dataId.split('/redfish/v1/Schemas/')[1] redfish().get_schema(dataId) schema_ref = self.__get_data() LOG.debug(schema_ref,json=True) id = schema_ref.get('Id') assert_equal(dataId, id, message='unexpected id",
"found') location = schema_ref.get('Location')[0] assert_equal(type(location.get('Uri')), unicode, message='expected uri string not found') self.__locationUri.append(location.get('Uri')) @test(groups=['redfish.get_schema_invalid'],",
"redfish().list_schemas() schemas = self.__get_data() LOG.debug(schemas,json=True) assert_not_equal(0, len(schemas), message='Schema list was empty!') self.__schemaList =",
"redfish().get_schema_content(dataId) schema_file_contents = self.__get_data() @test(groups=['redfish.get_schema_content_invalid'], depends_on_groups=['redfish.get_schema']) def test_get_schema_content_invalid(self): \"\"\" Testing GET /Schemas/en/{identifier} 404s",
"import * from modules.logger import Log from on_http_redfish_1_0 import RedfishvApi as redfish from",
"from proboscis import test from json import loads,dumps LOG = Log(__name__) @test(groups=['redfish.schema.tests'], depends_on_groups=['obm.tests'])",
"try: redfish().get_schema_content(dataId + '-invalid') fail(message='did not raise exception') except rest.ApiException as e: assert_equal(404,",
"as redfish from on_http_redfish_1_0 import rest from datetime import datetime from proboscis.asserts import",
"schema_ref = self.__get_data() LOG.debug(schema_ref,json=True) id = schema_ref.get('Id') assert_equal(dataId, id, message='unexpected id {0}, expected",
"GET /Schemas/en/{identifier} 404s properly \"\"\" assert_not_equal([], self.__locationUri) for member in self.__locationUri: assert_not_equal(None,member) dataId",
"LOG.debug(schemas,json=True) assert_not_equal(0, len(schemas), message='Schema list was empty!') self.__schemaList = schemas @test(groups=['redfish.get_schema'], depends_on_groups=['redfish.list_schemas']) def",
"Testing GET /Schemas/en/{identifier} 404s properly \"\"\" assert_not_equal([], self.__locationUri) for member in self.__locationUri: assert_not_equal(None,member)",
"schema_ref.get('Location')[0] assert_equal(type(location.get('Uri')), unicode, message='expected uri string not found') self.__locationUri.append(location.get('Uri')) @test(groups=['redfish.get_schema_invalid'], depends_on_groups=['redfish.list_schemas']) def test_get_schema_invalid(self):",
"proboscis.asserts import fail from proboscis import SkipTest from proboscis import test from json",
"GET /Schemas/{identifier} \"\"\" self.__membersList = self.__schemaList.get('Members') assert_not_equal(None, self.__membersList) for member in self.__membersList: dataId",
"schema_ref.get('Id') assert_equal(dataId, id, message='unexpected id {0}, expected {1}'.format(id,dataId)) assert_equal(type(schema_ref.get('Location')), list, message='expected list not",
"def test_list_schemas(self): \"\"\" Testing GET /Schemas \"\"\" redfish().list_schemas() schemas = self.__get_data() LOG.debug(schemas,json=True) assert_not_equal(0,",
"string not found') self.__locationUri.append(location.get('Uri')) @test(groups=['redfish.get_schema_invalid'], depends_on_groups=['redfish.list_schemas']) def test_get_schema_invalid(self): \"\"\" Testing GET /Schemas/{identifier} 404s",
"class SchemaTests(object): def __init__(self): self.__client = config.api_client self.__schemaList = None self.__membersList = None",
"rest from datetime import datetime from proboscis.asserts import assert_equal from proboscis.asserts import assert_false",
"for member in self.__membersList: dataId = member.get('@odata.id') assert_not_equal(None,dataId) dataId = dataId.split('/redfish/v1/Schemas/')[1] redfish().get_schema(dataId) schema_ref",
"for member in self.__locationUri: assert_not_equal(None,member) dataId = member.split('/redfish/v1/SchemaStore/en/')[1] redfish().get_schema_content(dataId) schema_file_contents = self.__get_data() @test(groups=['redfish.get_schema_content_invalid'],",
"= self.__get_data() @test(groups=['redfish.get_schema_content_invalid'], depends_on_groups=['redfish.get_schema']) def test_get_schema_content_invalid(self): \"\"\" Testing GET /Schemas/en/{identifier} 404s properly \"\"\"",
"SchemaTests(object): def __init__(self): self.__client = config.api_client self.__schemaList = None self.__membersList = None self.__locationUri",
"proboscis.asserts import assert_false from proboscis.asserts import assert_raises from proboscis.asserts import assert_not_equal from proboscis.asserts",
"found') self.__locationUri.append(location.get('Uri')) @test(groups=['redfish.get_schema_invalid'], depends_on_groups=['redfish.list_schemas']) def test_get_schema_invalid(self): \"\"\" Testing GET /Schemas/{identifier} 404s properly \"\"\"",
"return loads(self.__client.last_response.data) @test(groups=['redfish.list_schemas']) def test_list_schemas(self): \"\"\" Testing GET /Schemas \"\"\" redfish().list_schemas() schemas =",
"{0}, expected 404'.format(e.status)) break @test(groups=['redfish.get_schema_content'], depends_on_groups=['redfish.get_schema']) def test_get_schema_content(self): \"\"\" Testing GET /SchemaStore/en/{identifier} \"\"\"",
"import SkipTest from proboscis import test from json import loads,dumps LOG = Log(__name__)",
"test_get_schema_content_invalid(self): \"\"\" Testing GET /Schemas/en/{identifier} 404s properly \"\"\" assert_not_equal([], self.__locationUri) for member in",
"import Log from on_http_redfish_1_0 import RedfishvApi as redfish from on_http_redfish_1_0 import rest from",
"fail(message='did not raise exception') except rest.ApiException as e: assert_equal(404, e.status, message='unexpected response {0},",
"member in self.__locationUri: assert_not_equal(None,member) dataId = member.split('/redfish/v1/SchemaStore/en/')[1] try: redfish().get_schema_content(dataId + '-invalid') fail(message='did not",
"member.split('/redfish/v1/SchemaStore/en/')[1] try: redfish().get_schema_content(dataId + '-invalid') fail(message='did not raise exception') except rest.ApiException as e:",
"assert_equal(dataId, id, message='unexpected id {0}, expected {1}'.format(id,dataId)) assert_equal(type(schema_ref.get('Location')), list, message='expected list not found')",
"proboscis import SkipTest from proboscis import test from json import loads,dumps LOG =",
"dataId = member.split('/redfish/v1/SchemaStore/en/')[1] redfish().get_schema_content(dataId) schema_file_contents = self.__get_data() @test(groups=['redfish.get_schema_content_invalid'], depends_on_groups=['redfish.get_schema']) def test_get_schema_content_invalid(self): \"\"\" Testing",
"= [] def __get_data(self): return loads(self.__client.last_response.data) @test(groups=['redfish.list_schemas']) def test_list_schemas(self): \"\"\" Testing GET /Schemas",
"import test from json import loads,dumps LOG = Log(__name__) @test(groups=['redfish.schema.tests'], depends_on_groups=['obm.tests']) class SchemaTests(object):",
"from proboscis.asserts import assert_true from proboscis.asserts import fail from proboscis import SkipTest from",
"= None self.__membersList = None self.__locationUri = [] def __get_data(self): return loads(self.__client.last_response.data) @test(groups=['redfish.list_schemas'])",
"id, message='unexpected id {0}, expected {1}'.format(id,dataId)) assert_equal(type(schema_ref.get('Location')), list, message='expected list not found') location",
"self.__locationUri.append(location.get('Uri')) @test(groups=['redfish.get_schema_invalid'], depends_on_groups=['redfish.list_schemas']) def test_get_schema_invalid(self): \"\"\" Testing GET /Schemas/{identifier} 404s properly \"\"\" self.__membersList",
"modules.logger import Log from on_http_redfish_1_0 import RedfishvApi as redfish from on_http_redfish_1_0 import rest",
"assert_equal from proboscis.asserts import assert_false from proboscis.asserts import assert_raises from proboscis.asserts import assert_not_equal",
"list not found') location = schema_ref.get('Location')[0] assert_equal(type(location.get('Uri')), unicode, message='expected uri string not found')",
"from datetime import datetime from proboscis.asserts import assert_equal from proboscis.asserts import assert_false from",
"/Schemas/en/{identifier} 404s properly \"\"\" assert_not_equal([], self.__locationUri) for member in self.__locationUri: assert_not_equal(None,member) dataId =",
"from proboscis.asserts import assert_false from proboscis.asserts import assert_raises from proboscis.asserts import assert_not_equal from",
"= member.get('@odata.id') assert_not_equal(None,dataId) dataId = dataId.split('/redfish/v1/Schemas/')[1] redfish().get_schema(dataId) schema_ref = self.__get_data() LOG.debug(schema_ref,json=True) id =",
"assert_not_equal(None, self.__membersList) for member in self.__membersList: dataId = member.get('@odata.id') assert_not_equal(None,dataId) dataId = dataId.split('/redfish/v1/Schemas/')[1]",
"properly \"\"\" self.__membersList = self.__schemaList.get('Members') assert_not_equal(None, self.__membersList) for member in self.__membersList: dataId =",
"exception') except rest.ApiException as e: assert_equal(404, e.status, message='unexpected response {0}, expected 404'.format(e.status)) break",
"Testing GET /Schemas \"\"\" redfish().list_schemas() schemas = self.__get_data() LOG.debug(schemas,json=True) assert_not_equal(0, len(schemas), message='Schema list",
"message='expected list not found') location = schema_ref.get('Location')[0] assert_equal(type(location.get('Uri')), unicode, message='expected uri string not",
"self.__locationUri: assert_not_equal(None,member) dataId = member.split('/redfish/v1/SchemaStore/en/')[1] try: redfish().get_schema_content(dataId + '-invalid') fail(message='did not raise exception')",
"try: redfish().get_schema(dataId + '-invalid') fail(message='did not raise exception') except rest.ApiException as e: assert_equal(404,",
"self.__locationUri) for member in self.__locationUri: assert_not_equal(None,member) dataId = member.split('/redfish/v1/SchemaStore/en/')[1] redfish().get_schema_content(dataId) schema_file_contents = self.__get_data()",
"self.__locationUri) for member in self.__locationUri: assert_not_equal(None,member) dataId = member.split('/redfish/v1/SchemaStore/en/')[1] try: redfish().get_schema_content(dataId + '-invalid')",
"self.__membersList: dataId = member.get('@odata.id') assert_not_equal(None,dataId) dataId = dataId.split('/redfish/v1/Schemas/')[1] redfish().get_schema(dataId) schema_ref = self.__get_data() LOG.debug(schema_ref,json=True)",
"assert_false from proboscis.asserts import assert_raises from proboscis.asserts import assert_not_equal from proboscis.asserts import assert_true",
"from modules.logger import Log from on_http_redfish_1_0 import RedfishvApi as redfish from on_http_redfish_1_0 import",
"def __get_data(self): return loads(self.__client.last_response.data) @test(groups=['redfish.list_schemas']) def test_list_schemas(self): \"\"\" Testing GET /Schemas \"\"\" redfish().list_schemas()",
"datetime from proboscis.asserts import assert_equal from proboscis.asserts import assert_false from proboscis.asserts import assert_raises",
"test_list_schemas(self): \"\"\" Testing GET /Schemas \"\"\" redfish().list_schemas() schemas = self.__get_data() LOG.debug(schemas,json=True) assert_not_equal(0, len(schemas),",
"schemas @test(groups=['redfish.get_schema'], depends_on_groups=['redfish.list_schemas']) def test_get_schema(self): \"\"\" Testing GET /Schemas/{identifier} \"\"\" self.__membersList = self.__schemaList.get('Members')",
"proboscis import test from json import loads,dumps LOG = Log(__name__) @test(groups=['redfish.schema.tests'], depends_on_groups=['obm.tests']) class",
"id {0}, expected {1}'.format(id,dataId)) assert_equal(type(schema_ref.get('Location')), list, message='expected list not found') location = schema_ref.get('Location')[0]",
"= self.__get_data() LOG.debug(schemas,json=True) assert_not_equal(0, len(schemas), message='Schema list was empty!') self.__schemaList = schemas @test(groups=['redfish.get_schema'],",
"self.__membersList) for member in self.__membersList: dataId = member.get('@odata.id') assert_not_equal(None,dataId) dataId = dataId.split('/redfish/v1/Schemas/')[1] try:",
"= Log(__name__) @test(groups=['redfish.schema.tests'], depends_on_groups=['obm.tests']) class SchemaTests(object): def __init__(self): self.__client = config.api_client self.__schemaList =",
"test_get_schema_content(self): \"\"\" Testing GET /SchemaStore/en/{identifier} \"\"\" assert_not_equal([], self.__locationUri) for member in self.__locationUri: assert_not_equal(None,member)",
"assert_not_equal(None,member) dataId = member.split('/redfish/v1/SchemaStore/en/')[1] redfish().get_schema_content(dataId) schema_file_contents = self.__get_data() @test(groups=['redfish.get_schema_content_invalid'], depends_on_groups=['redfish.get_schema']) def test_get_schema_content_invalid(self): \"\"\"",
"dataId = member.split('/redfish/v1/SchemaStore/en/')[1] try: redfish().get_schema_content(dataId + '-invalid') fail(message='did not raise exception') except rest.ApiException",
"\"\"\" Testing GET /Schemas \"\"\" redfish().list_schemas() schemas = self.__get_data() LOG.debug(schemas,json=True) assert_not_equal(0, len(schemas), message='Schema",
"SkipTest from proboscis import test from json import loads,dumps LOG = Log(__name__) @test(groups=['redfish.schema.tests'],",
"import loads,dumps LOG = Log(__name__) @test(groups=['redfish.schema.tests'], depends_on_groups=['obm.tests']) class SchemaTests(object): def __init__(self): self.__client =",
"self.__client = config.api_client self.__schemaList = None self.__membersList = None self.__locationUri = [] def",
"\"\"\" assert_not_equal([], self.__locationUri) for member in self.__locationUri: assert_not_equal(None,member) dataId = member.split('/redfish/v1/SchemaStore/en/')[1] redfish().get_schema_content(dataId) schema_file_contents",
"on_http_redfish_1_0 import rest from datetime import datetime from proboscis.asserts import assert_equal from proboscis.asserts",
"Log(__name__) @test(groups=['redfish.schema.tests'], depends_on_groups=['obm.tests']) class SchemaTests(object): def __init__(self): self.__client = config.api_client self.__schemaList = None",
"assert_not_equal(None,member) dataId = member.split('/redfish/v1/SchemaStore/en/')[1] try: redfish().get_schema_content(dataId + '-invalid') fail(message='did not raise exception') except",
"= member.split('/redfish/v1/SchemaStore/en/')[1] redfish().get_schema_content(dataId) schema_file_contents = self.__get_data() @test(groups=['redfish.get_schema_content_invalid'], depends_on_groups=['redfish.get_schema']) def test_get_schema_content_invalid(self): \"\"\" Testing GET",
"from json import loads,dumps LOG = Log(__name__) @test(groups=['redfish.schema.tests'], depends_on_groups=['obm.tests']) class SchemaTests(object): def __init__(self):",
"response {0}, expected 404'.format(e.status)) break @test(groups=['redfish.get_schema_content'], depends_on_groups=['redfish.get_schema']) def test_get_schema_content(self): \"\"\" Testing GET /SchemaStore/en/{identifier}",
"rest.ApiException as e: assert_equal(404, e.status, message='unexpected response {0}, expected 404'.format(e.status)) break @test(groups=['redfish.get_schema_content'], depends_on_groups=['redfish.get_schema'])",
"assert_equal(404, e.status, message='unexpected response {0}, expected 404'.format(e.status)) break @test(groups=['redfish.get_schema_content'], depends_on_groups=['redfish.get_schema']) def test_get_schema_content(self): \"\"\"",
"def __init__(self): self.__client = config.api_client self.__schemaList = None self.__membersList = None self.__locationUri =",
"__init__(self): self.__client = config.api_client self.__schemaList = None self.__membersList = None self.__locationUri = []",
"schemas = self.__get_data() LOG.debug(schemas,json=True) assert_not_equal(0, len(schemas), message='Schema list was empty!') self.__schemaList = schemas",
"proboscis.asserts import assert_not_equal from proboscis.asserts import assert_true from proboscis.asserts import fail from proboscis",
"self.__membersList: dataId = member.get('@odata.id') assert_not_equal(None,dataId) dataId = dataId.split('/redfish/v1/Schemas/')[1] try: redfish().get_schema(dataId + '-invalid') fail(message='did",
"None self.__locationUri = [] def __get_data(self): return loads(self.__client.last_response.data) @test(groups=['redfish.list_schemas']) def test_list_schemas(self): \"\"\" Testing",
"location = schema_ref.get('Location')[0] assert_equal(type(location.get('Uri')), unicode, message='expected uri string not found') self.__locationUri.append(location.get('Uri')) @test(groups=['redfish.get_schema_invalid'], depends_on_groups=['redfish.list_schemas'])",
"\"\"\" Testing GET /Schemas/{identifier} \"\"\" self.__membersList = self.__schemaList.get('Members') assert_not_equal(None, self.__membersList) for member in",
"assert_not_equal([], self.__locationUri) for member in self.__locationUri: assert_not_equal(None,member) dataId = member.split('/redfish/v1/SchemaStore/en/')[1] try: redfish().get_schema_content(dataId +",
"= schema_ref.get('Id') assert_equal(dataId, id, message='unexpected id {0}, expected {1}'.format(id,dataId)) assert_equal(type(schema_ref.get('Location')), list, message='expected list",
"import assert_raises from proboscis.asserts import assert_not_equal from proboscis.asserts import assert_true from proboscis.asserts import",
"fail from proboscis import SkipTest from proboscis import test from json import loads,dumps",
"depends_on_groups=['obm.tests']) class SchemaTests(object): def __init__(self): self.__client = config.api_client self.__schemaList = None self.__membersList =",
"config.api_client self.__schemaList = None self.__membersList = None self.__locationUri = [] def __get_data(self): return",
"\"\"\" Testing GET /SchemaStore/en/{identifier} \"\"\" assert_not_equal([], self.__locationUri) for member in self.__locationUri: assert_not_equal(None,member) dataId",
"+ '-invalid') fail(message='did not raise exception') except rest.ApiException as e: assert_equal(404, e.status, message='unexpected",
"dataId = dataId.split('/redfish/v1/Schemas/')[1] redfish().get_schema(dataId) schema_ref = self.__get_data() LOG.debug(schema_ref,json=True) id = schema_ref.get('Id') assert_equal(dataId, id,",
"as e: assert_equal(404, e.status, message='unexpected response {0}, expected 404'.format(e.status)) break @test(groups=['redfish.get_schema_content'], depends_on_groups=['redfish.get_schema']) def",
"assert_raises from proboscis.asserts import assert_not_equal from proboscis.asserts import assert_true from proboscis.asserts import fail",
"404s properly \"\"\" self.__membersList = self.__schemaList.get('Members') assert_not_equal(None, self.__membersList) for member in self.__membersList: dataId",
"expected {1}'.format(id,dataId)) assert_equal(type(schema_ref.get('Location')), list, message='expected list not found') location = schema_ref.get('Location')[0] assert_equal(type(location.get('Uri')), unicode,",
"Log from on_http_redfish_1_0 import RedfishvApi as redfish from on_http_redfish_1_0 import rest from datetime",
"[] def __get_data(self): return loads(self.__client.last_response.data) @test(groups=['redfish.list_schemas']) def test_list_schemas(self): \"\"\" Testing GET /Schemas \"\"\"",
"self.__get_data() @test(groups=['redfish.get_schema_content_invalid'], depends_on_groups=['redfish.get_schema']) def test_get_schema_content_invalid(self): \"\"\" Testing GET /Schemas/en/{identifier} 404s properly \"\"\" assert_not_equal([],",
"dataId = dataId.split('/redfish/v1/Schemas/')[1] try: redfish().get_schema(dataId + '-invalid') fail(message='did not raise exception') except rest.ApiException",
"not found') self.__locationUri.append(location.get('Uri')) @test(groups=['redfish.get_schema_invalid'], depends_on_groups=['redfish.list_schemas']) def test_get_schema_invalid(self): \"\"\" Testing GET /Schemas/{identifier} 404s properly",
"self.__schemaList.get('Members') assert_not_equal(None, self.__membersList) for member in self.__membersList: dataId = member.get('@odata.id') assert_not_equal(None,dataId) dataId =",
"GET /Schemas/{identifier} 404s properly \"\"\" self.__membersList = self.__schemaList.get('Members') assert_not_equal(None, self.__membersList) for member in",
"\"\"\" Testing GET /Schemas/en/{identifier} 404s properly \"\"\" assert_not_equal([], self.__locationUri) for member in self.__locationUri:",
"Testing GET /SchemaStore/en/{identifier} \"\"\" assert_not_equal([], self.__locationUri) for member in self.__locationUri: assert_not_equal(None,member) dataId =",
"def test_get_schema(self): \"\"\" Testing GET /Schemas/{identifier} \"\"\" self.__membersList = self.__schemaList.get('Members') assert_not_equal(None, self.__membersList) for",
"depends_on_groups=['redfish.get_schema']) def test_get_schema_content(self): \"\"\" Testing GET /SchemaStore/en/{identifier} \"\"\" assert_not_equal([], self.__locationUri) for member in",
"import RedfishvApi as redfish from on_http_redfish_1_0 import rest from datetime import datetime from",
"RedfishvApi as redfish from on_http_redfish_1_0 import rest from datetime import datetime from proboscis.asserts",
"not raise exception') except rest.ApiException as e: assert_equal(404, e.status, message='unexpected response {0}, expected",
"properly \"\"\" assert_not_equal([], self.__locationUri) for member in self.__locationUri: assert_not_equal(None,member) dataId = member.split('/redfish/v1/SchemaStore/en/')[1] try:",
"json import loads,dumps LOG = Log(__name__) @test(groups=['redfish.schema.tests'], depends_on_groups=['obm.tests']) class SchemaTests(object): def __init__(self): self.__client",
"e: assert_equal(404, e.status, message='unexpected response {0}, expected 404'.format(e.status)) break @test(groups=['redfish.get_schema_content'], depends_on_groups=['redfish.get_schema']) def test_get_schema_content(self):",
"proboscis.asserts import assert_equal from proboscis.asserts import assert_false from proboscis.asserts import assert_raises from proboscis.asserts",
"import fail from proboscis import SkipTest from proboscis import test from json import",
"import assert_true from proboscis.asserts import fail from proboscis import SkipTest from proboscis import",
"import assert_false from proboscis.asserts import assert_raises from proboscis.asserts import assert_not_equal from proboscis.asserts import",
"GET /SchemaStore/en/{identifier} \"\"\" assert_not_equal([], self.__locationUri) for member in self.__locationUri: assert_not_equal(None,member) dataId = member.split('/redfish/v1/SchemaStore/en/')[1]",
"assert_equal(type(location.get('Uri')), unicode, message='expected uri string not found') self.__locationUri.append(location.get('Uri')) @test(groups=['redfish.get_schema_invalid'], depends_on_groups=['redfish.list_schemas']) def test_get_schema_invalid(self): \"\"\"",
"depends_on_groups=['redfish.list_schemas']) def test_get_schema_invalid(self): \"\"\" Testing GET /Schemas/{identifier} 404s properly \"\"\" self.__membersList = self.__schemaList.get('Members')",
"in self.__locationUri: assert_not_equal(None,member) dataId = member.split('/redfish/v1/SchemaStore/en/')[1] try: redfish().get_schema_content(dataId + '-invalid') fail(message='did not raise",
"self.__membersList = None self.__locationUri = [] def __get_data(self): return loads(self.__client.last_response.data) @test(groups=['redfish.list_schemas']) def test_list_schemas(self):",
"raise exception') except rest.ApiException as e: assert_equal(404, e.status, message='unexpected response {0}, expected 404'.format(e.status))",
"{0}, expected {1}'.format(id,dataId)) assert_equal(type(schema_ref.get('Location')), list, message='expected list not found') location = schema_ref.get('Location')[0] assert_equal(type(location.get('Uri')),",
"len(schemas), message='Schema list was empty!') self.__schemaList = schemas @test(groups=['redfish.get_schema'], depends_on_groups=['redfish.list_schemas']) def test_get_schema(self): \"\"\"",
"= config.api_client self.__schemaList = None self.__membersList = None self.__locationUri = [] def __get_data(self):",
"id = schema_ref.get('Id') assert_equal(dataId, id, message='unexpected id {0}, expected {1}'.format(id,dataId)) assert_equal(type(schema_ref.get('Location')), list, message='expected",
"def test_get_schema_content(self): \"\"\" Testing GET /SchemaStore/en/{identifier} \"\"\" assert_not_equal([], self.__locationUri) for member in self.__locationUri:"
] |
[
"pulumi_okta as okta example = okta.app.get_app(label=\"Example App\") ``` :param bool active_only: tells the",
"= pulumi.runtime.invoke('okta:app/getApp:getApp', __args__, opts=opts, typ=GetAppResult).value return AwaitableGetAppResult( active_only=__ret__.active_only, description=__ret__.description, id=__ret__.id, label=__ret__.label, label_prefix=__ret__.label_prefix, name=__ret__.name,",
"not edit by hand unless you're certain you know what you are doing!",
"name(self) -> str: \"\"\" `name` of application. \"\"\" return pulumi.get(self, \"name\") @property @pulumi.getter",
"active_only=self.active_only, description=self.description, id=self.id, label=self.label, label_prefix=self.label_prefix, name=self.name, status=self.status) def get_app(active_only: Optional[bool] = None, id:",
"\"\"\" __args__ = dict() __args__['activeOnly'] = active_only __args__['id'] = id __args__['label'] = label",
"@property @pulumi.getter def id(self) -> Optional[str]: \"\"\" `id` of application. \"\"\" return pulumi.get(self,",
"pulumi.set(__self__, \"status\", status) @property @pulumi.getter(name=\"activeOnly\") def active_only(self) -> Optional[bool]: return pulumi.get(self, \"active_only\") @property",
"@property @pulumi.getter(name=\"activeOnly\") def active_only(self) -> Optional[bool]: return pulumi.get(self, \"active_only\") @property @pulumi.getter def description(self)",
"and `label_prefix`. :param str label: The label of the app to retrieve, conflicts",
"def label(self) -> Optional[str]: \"\"\" `label` of application. \"\"\" return pulumi.get(self, \"label\") @property",
"\"active_only\", active_only) if description and not isinstance(description, str): raise TypeError(\"Expected argument 'description' to",
"data source to retrieve the collaborators for a given repository. ## Example Usage",
"-> str: \"\"\" `name` of application. \"\"\" return pulumi.get(self, \"name\") @property @pulumi.getter def",
"not isinstance(status, str): raise TypeError(\"Expected argument 'status' to be a str\") pulumi.set(__self__, \"status\",",
"pulumi.get(self, \"active_only\") @property @pulumi.getter def description(self) -> str: \"\"\" `description` of application. \"\"\"",
"str): raise TypeError(\"Expected argument 'status' to be a str\") pulumi.set(__self__, \"status\", status) @property",
"\"\"\" `id` of application. \"\"\" return pulumi.get(self, \"id\") @property @pulumi.getter def label(self) ->",
"be a str\") pulumi.set(__self__, \"status\", status) @property @pulumi.getter(name=\"activeOnly\") def active_only(self) -> Optional[bool]: return",
"__args__['id'] = id __args__['label'] = label __args__['labelPrefix'] = label_prefix if opts is None:",
"the app to retrieve, conflicts with `label` and `id`. This will tell the",
"*** # *** Do not edit by hand unless you're certain you know",
"label of the app to retrieve, conflicts with `label_prefix` and `id`. :param str",
"str): raise TypeError(\"Expected argument 'label_prefix' to be a str\") pulumi.set(__self__, \"label_prefix\", label_prefix) if",
"@pulumi.getter def id(self) -> Optional[str]: \"\"\" `id` of application. \"\"\" return pulumi.get(self, \"id\")",
"class AwaitableGetAppResult(GetAppResult): # pylint: disable=using-constant-test def __await__(self): if False: yield self return GetAppResult(",
"if False: yield self return GetAppResult( active_only=self.active_only, description=self.description, id=self.id, label=self.label, label_prefix=self.label_prefix, name=self.name, status=self.status)",
"not isinstance(active_only, bool): raise TypeError(\"Expected argument 'active_only' to be a bool\") pulumi.set(__self__, \"active_only\",",
"\"name\") @property @pulumi.getter def status(self) -> str: \"\"\" `status` of application. \"\"\" return",
"'GetAppResult', 'AwaitableGetAppResult', 'get_app', ] @pulumi.output_type class GetAppResult: \"\"\" A collection of values returned",
"None: opts = pulumi.InvokeOptions() if opts.version is None: opts.version = _utilities.get_version() __ret__ =",
"raise TypeError(\"Expected argument 'label' to be a str\") pulumi.set(__self__, \"label\", label) if label_prefix",
"\"\"\" return pulumi.get(self, \"description\") @property @pulumi.getter def id(self) -> Optional[str]: \"\"\" `id` of",
"None, label_prefix: Optional[str] = None, opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetAppResult: \"\"\" Use",
"] @pulumi.output_type class GetAppResult: \"\"\" A collection of values returned by getApp. \"\"\"",
"as okta example = okta.app.get_app(label=\"Example App\") ``` :param bool active_only: tells the provider",
"prefix of the app to retrieve, conflicts with `label` and `id`. This will",
"a given repository. ## Example Usage ```python import pulumi import pulumi_okta as okta",
"GetAppResult: \"\"\" A collection of values returned by getApp. \"\"\" def __init__(__self__, active_only=None,",
"okta example = okta.app.get_app(label=\"Example App\") ``` :param bool active_only: tells the provider to",
"if id and not isinstance(id, str): raise TypeError(\"Expected argument 'id' to be a",
"and `id`. :param str label_prefix: Label prefix of the app to retrieve, conflicts",
"id) if label and not isinstance(label, str): raise TypeError(\"Expected argument 'label' to be",
"description=self.description, id=self.id, label=self.label, label_prefix=self.label_prefix, name=self.name, status=self.status) def get_app(active_only: Optional[bool] = None, id: Optional[str]",
"str\") pulumi.set(__self__, \"label\", label) if label_prefix and not isinstance(label_prefix, str): raise TypeError(\"Expected argument",
"\"active_only\") @property @pulumi.getter def description(self) -> str: \"\"\" `description` of application. \"\"\" return",
"def name(self) -> str: \"\"\" `name` of application. \"\"\" return pulumi.get(self, \"name\") @property",
"`label` and `label_prefix`. :param str label: The label of the app to retrieve,",
"with `label_prefix` and `id`. :param str label_prefix: Label prefix of the app to",
"of application. \"\"\" return pulumi.get(self, \"id\") @property @pulumi.getter def label(self) -> Optional[str]: \"\"\"",
"warnings import pulumi import pulumi.runtime from typing import Any, Dict, List, Mapping, Optional,",
"disable=using-constant-test def __await__(self): if False: yield self return GetAppResult( active_only=self.active_only, description=self.description, id=self.id, label=self.label,",
"raise TypeError(\"Expected argument 'active_only' to be a bool\") pulumi.set(__self__, \"active_only\", active_only) if description",
"str): raise TypeError(\"Expected argument 'name' to be a str\") pulumi.set(__self__, \"name\", name) if",
"conflicts with `label` and `id`. This will tell the provider to do a",
"__ret__ = pulumi.runtime.invoke('okta:app/getApp:getApp', __args__, opts=opts, typ=GetAppResult).value return AwaitableGetAppResult( active_only=__ret__.active_only, description=__ret__.description, id=__ret__.id, label=__ret__.label, label_prefix=__ret__.label_prefix,",
"query as opposed to an `equals` query. \"\"\" __args__ = dict() __args__['activeOnly'] =",
"raise TypeError(\"Expected argument 'label_prefix' to be a str\") pulumi.set(__self__, \"label_prefix\", label_prefix) if name",
"@pulumi.getter def label(self) -> Optional[str]: \"\"\" `label` of application. \"\"\" return pulumi.get(self, \"label\")",
"(tfgen) Tool. *** # *** Do not edit by hand unless you're certain",
"`id` of application. \"\"\" return pulumi.get(self, \"id\") @property @pulumi.getter def label(self) -> Optional[str]:",
"\"\"\" Use this data source to retrieve the collaborators for a given repository.",
"query. \"\"\" __args__ = dict() __args__['activeOnly'] = active_only __args__['id'] = id __args__['label'] =",
"`label_prefix`. :param str label: The label of the app to retrieve, conflicts with",
"# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen)",
"be a str\") pulumi.set(__self__, \"description\", description) if id and not isinstance(id, str): raise",
"None, id: Optional[str] = None, label: Optional[str] = None, label_prefix: Optional[str] = None,",
"retrieve, conflicts with `label` and `id`. This will tell the provider to do",
"label_prefix and not isinstance(label_prefix, str): raise TypeError(\"Expected argument 'label_prefix' to be a str\")",
"isinstance(name, str): raise TypeError(\"Expected argument 'name' to be a str\") pulumi.set(__self__, \"name\", name)",
"label_prefix=self.label_prefix, name=self.name, status=self.status) def get_app(active_only: Optional[bool] = None, id: Optional[str] = None, label:",
"__args__['label'] = label __args__['labelPrefix'] = label_prefix if opts is None: opts = pulumi.InvokeOptions()",
"if opts.version is None: opts.version = _utilities.get_version() __ret__ = pulumi.runtime.invoke('okta:app/getApp:getApp', __args__, opts=opts, typ=GetAppResult).value",
"def status(self) -> str: \"\"\" `status` of application. \"\"\" return pulumi.get(self, \"status\") class",
"pulumi.set(__self__, \"description\", description) if id and not isinstance(id, str): raise TypeError(\"Expected argument 'id'",
"import pulumi import pulumi.runtime from typing import Any, Dict, List, Mapping, Optional, Tuple,",
"str: \"\"\" `status` of application. \"\"\" return pulumi.get(self, \"status\") class AwaitableGetAppResult(GetAppResult): # pylint:",
"a str\") pulumi.set(__self__, \"id\", id) if label and not isinstance(label, str): raise TypeError(\"Expected",
"not isinstance(name, str): raise TypeError(\"Expected argument 'name' to be a str\") pulumi.set(__self__, \"name\",",
"TypeError(\"Expected argument 'label_prefix' to be a str\") pulumi.set(__self__, \"label_prefix\", label_prefix) if name and",
"active_only) if description and not isinstance(description, str): raise TypeError(\"Expected argument 'description' to be",
"\"label_prefix\", label_prefix) if name and not isinstance(name, str): raise TypeError(\"Expected argument 'name' to",
"be a str\") pulumi.set(__self__, \"id\", id) if label and not isinstance(label, str): raise",
"\"\"\" return pulumi.get(self, \"id\") @property @pulumi.getter def label(self) -> Optional[str]: \"\"\" `label` of",
"query for only `ACTIVE` applications. :param str id: `id` of application to retrieve,",
"label_prefix) if name and not isinstance(name, str): raise TypeError(\"Expected argument 'name' to be",
"-> str: \"\"\" `status` of application. \"\"\" return pulumi.get(self, \"status\") class AwaitableGetAppResult(GetAppResult): #",
"for a given repository. ## Example Usage ```python import pulumi import pulumi_okta as",
"opts is None: opts = pulumi.InvokeOptions() if opts.version is None: opts.version = _utilities.get_version()",
"\"status\", status) @property @pulumi.getter(name=\"activeOnly\") def active_only(self) -> Optional[bool]: return pulumi.get(self, \"active_only\") @property @pulumi.getter",
"= active_only __args__['id'] = id __args__['label'] = label __args__['labelPrefix'] = label_prefix if opts",
"of values returned by getApp. \"\"\" def __init__(__self__, active_only=None, description=None, id=None, label=None, label_prefix=None,",
"to retrieve the collaborators for a given repository. ## Example Usage ```python import",
"raise TypeError(\"Expected argument 'description' to be a str\") pulumi.set(__self__, \"description\", description) if id",
"``` :param bool active_only: tells the provider to query for only `ACTIVE` applications.",
"an `equals` query. \"\"\" __args__ = dict() __args__['activeOnly'] = active_only __args__['id'] = id",
"app to retrieve, conflicts with `label` and `id`. This will tell the provider",
"be a str\") pulumi.set(__self__, \"name\", name) if status and not isinstance(status, str): raise",
"`label_prefix` and `id`. :param str label_prefix: Label prefix of the app to retrieve,",
"def id(self) -> Optional[str]: \"\"\" `id` of application. \"\"\" return pulumi.get(self, \"id\") @property",
"Terraform Bridge (tfgen) Tool. *** # *** Do not edit by hand unless",
"pulumi.set(__self__, \"name\", name) if status and not isinstance(status, str): raise TypeError(\"Expected argument 'status'",
"to retrieve, conflicts with `label` and `id`. This will tell the provider to",
"isinstance(label_prefix, str): raise TypeError(\"Expected argument 'label_prefix' to be a str\") pulumi.set(__self__, \"label_prefix\", label_prefix)",
"to retrieve, conflicts with `label` and `label_prefix`. :param str label: The label of",
"TypeError(\"Expected argument 'description' to be a str\") pulumi.set(__self__, \"description\", description) if id and",
"@property @pulumi.getter def name(self) -> str: \"\"\" `name` of application. \"\"\" return pulumi.get(self,",
"provider to do a `starts with` query as opposed to an `equals` query.",
"class GetAppResult: \"\"\" A collection of values returned by getApp. \"\"\" def __init__(__self__,",
"be a bool\") pulumi.set(__self__, \"active_only\", active_only) if description and not isinstance(description, str): raise",
"@pulumi.getter(name=\"labelPrefix\") def label_prefix(self) -> Optional[str]: return pulumi.get(self, \"label_prefix\") @property @pulumi.getter def name(self) ->",
"Optional[str] = None, label_prefix: Optional[str] = None, opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetAppResult:",
"example = okta.app.get_app(label=\"Example App\") ``` :param bool active_only: tells the provider to query",
"a str\") pulumi.set(__self__, \"status\", status) @property @pulumi.getter(name=\"activeOnly\") def active_only(self) -> Optional[bool]: return pulumi.get(self,",
"you're certain you know what you are doing! *** import warnings import pulumi",
"name=None, status=None): if active_only and not isinstance(active_only, bool): raise TypeError(\"Expected argument 'active_only' to",
"import _utilities, _tables __all__ = [ 'GetAppResult', 'AwaitableGetAppResult', 'get_app', ] @pulumi.output_type class GetAppResult:",
"def __await__(self): if False: yield self return GetAppResult( active_only=self.active_only, description=self.description, id=self.id, label=self.label, label_prefix=self.label_prefix,",
"unless you're certain you know what you are doing! *** import warnings import",
"if description and not isinstance(description, str): raise TypeError(\"Expected argument 'description' to be a",
"id: Optional[str] = None, label: Optional[str] = None, label_prefix: Optional[str] = None, opts:",
"`ACTIVE` applications. :param str id: `id` of application to retrieve, conflicts with `label`",
"status=self.status) def get_app(active_only: Optional[bool] = None, id: Optional[str] = None, label: Optional[str] =",
"@pulumi.getter(name=\"activeOnly\") def active_only(self) -> Optional[bool]: return pulumi.get(self, \"active_only\") @property @pulumi.getter def description(self) ->",
"GetAppResult( active_only=self.active_only, description=self.description, id=self.id, label=self.label, label_prefix=self.label_prefix, name=self.name, status=self.status) def get_app(active_only: Optional[bool] = None,",
"and not isinstance(id, str): raise TypeError(\"Expected argument 'id' to be a str\") pulumi.set(__self__,",
"return GetAppResult( active_only=self.active_only, description=self.description, id=self.id, label=self.label, label_prefix=self.label_prefix, name=self.name, status=self.status) def get_app(active_only: Optional[bool] =",
"typing import Any, Dict, List, Mapping, Optional, Tuple, Union from .. import _utilities,",
"the Pulumi Terraform Bridge (tfgen) Tool. *** # *** Do not edit by",
"Optional[str]: return pulumi.get(self, \"label_prefix\") @property @pulumi.getter def name(self) -> str: \"\"\" `name` of",
"`id`. :param str label_prefix: Label prefix of the app to retrieve, conflicts with",
"pulumi.set(__self__, \"active_only\", active_only) if description and not isinstance(description, str): raise TypeError(\"Expected argument 'description'",
"okta.app.get_app(label=\"Example App\") ``` :param bool active_only: tells the provider to query for only",
"\"\"\" `description` of application. \"\"\" return pulumi.get(self, \"description\") @property @pulumi.getter def id(self) ->",
"A collection of values returned by getApp. \"\"\" def __init__(__self__, active_only=None, description=None, id=None,",
"the provider to query for only `ACTIVE` applications. :param str id: `id` of",
"TypeError(\"Expected argument 'label' to be a str\") pulumi.set(__self__, \"label\", label) if label_prefix and",
"this data source to retrieve the collaborators for a given repository. ## Example",
"collaborators for a given repository. ## Example Usage ```python import pulumi import pulumi_okta",
"pulumi.set(__self__, \"label\", label) if label_prefix and not isinstance(label_prefix, str): raise TypeError(\"Expected argument 'label_prefix'",
"import pulumi_okta as okta example = okta.app.get_app(label=\"Example App\") ``` :param bool active_only: tells",
"@pulumi.getter def name(self) -> str: \"\"\" `name` of application. \"\"\" return pulumi.get(self, \"name\")",
"return pulumi.get(self, \"description\") @property @pulumi.getter def id(self) -> Optional[str]: \"\"\" `id` of application.",
"[ 'GetAppResult', 'AwaitableGetAppResult', 'get_app', ] @pulumi.output_type class GetAppResult: \"\"\" A collection of values",
"label_prefix(self) -> Optional[str]: return pulumi.get(self, \"label_prefix\") @property @pulumi.getter def name(self) -> str: \"\"\"",
"__args__['labelPrefix'] = label_prefix if opts is None: opts = pulumi.InvokeOptions() if opts.version is",
"to be a str\") pulumi.set(__self__, \"description\", description) if id and not isinstance(id, str):",
"str): raise TypeError(\"Expected argument 'label' to be a str\") pulumi.set(__self__, \"label\", label) if",
"by hand unless you're certain you know what you are doing! *** import",
"status and not isinstance(status, str): raise TypeError(\"Expected argument 'status' to be a str\")",
"@property @pulumi.getter def status(self) -> str: \"\"\" `status` of application. \"\"\" return pulumi.get(self,",
"you are doing! *** import warnings import pulumi import pulumi.runtime from typing import",
"\"description\") @property @pulumi.getter def id(self) -> Optional[str]: \"\"\" `id` of application. \"\"\" return",
"id: `id` of application to retrieve, conflicts with `label` and `label_prefix`. :param str",
"Bridge (tfgen) Tool. *** # *** Do not edit by hand unless you're",
":param bool active_only: tells the provider to query for only `ACTIVE` applications. :param",
"status=None): if active_only and not isinstance(active_only, bool): raise TypeError(\"Expected argument 'active_only' to be",
"bool active_only: tells the provider to query for only `ACTIVE` applications. :param str",
"with `label` and `label_prefix`. :param str label: The label of the app to",
"source to retrieve the collaborators for a given repository. ## Example Usage ```python",
"`status` of application. \"\"\" return pulumi.get(self, \"status\") class AwaitableGetAppResult(GetAppResult): # pylint: disable=using-constant-test def",
"import Any, Dict, List, Mapping, Optional, Tuple, Union from .. import _utilities, _tables",
"= label_prefix if opts is None: opts = pulumi.InvokeOptions() if opts.version is None:",
"def __init__(__self__, active_only=None, description=None, id=None, label=None, label_prefix=None, name=None, status=None): if active_only and not",
"given repository. ## Example Usage ```python import pulumi import pulumi_okta as okta example",
"Optional[bool] = None, id: Optional[str] = None, label: Optional[str] = None, label_prefix: Optional[str]",
"__init__(__self__, active_only=None, description=None, id=None, label=None, label_prefix=None, name=None, status=None): if active_only and not isinstance(active_only,",
"= None) -> AwaitableGetAppResult: \"\"\" Use this data source to retrieve the collaborators",
"and not isinstance(label, str): raise TypeError(\"Expected argument 'label' to be a str\") pulumi.set(__self__,",
"a str\") pulumi.set(__self__, \"label_prefix\", label_prefix) if name and not isinstance(name, str): raise TypeError(\"Expected",
"bool\") pulumi.set(__self__, \"active_only\", active_only) if description and not isinstance(description, str): raise TypeError(\"Expected argument",
"-> Optional[str]: \"\"\" `id` of application. \"\"\" return pulumi.get(self, \"id\") @property @pulumi.getter def",
"# *** Do not edit by hand unless you're certain you know what",
"coding=utf-8 # *** WARNING: this file was generated by the Pulumi Terraform Bridge",
"__args__['activeOnly'] = active_only __args__['id'] = id __args__['label'] = label __args__['labelPrefix'] = label_prefix if",
"= None, label: Optional[str] = None, label_prefix: Optional[str] = None, opts: Optional[pulumi.InvokeOptions] =",
"TypeError(\"Expected argument 'name' to be a str\") pulumi.set(__self__, \"name\", name) if status and",
"*** Do not edit by hand unless you're certain you know what you",
"= pulumi.InvokeOptions() if opts.version is None: opts.version = _utilities.get_version() __ret__ = pulumi.runtime.invoke('okta:app/getApp:getApp', __args__,",
"application. \"\"\" return pulumi.get(self, \"status\") class AwaitableGetAppResult(GetAppResult): # pylint: disable=using-constant-test def __await__(self): if",
"if label_prefix and not isinstance(label_prefix, str): raise TypeError(\"Expected argument 'label_prefix' to be a",
"return pulumi.get(self, \"label\") @property @pulumi.getter(name=\"labelPrefix\") def label_prefix(self) -> Optional[str]: return pulumi.get(self, \"label_prefix\") @property",
"with `label` and `id`. This will tell the provider to do a `starts",
"'get_app', ] @pulumi.output_type class GetAppResult: \"\"\" A collection of values returned by getApp.",
"= label __args__['labelPrefix'] = label_prefix if opts is None: opts = pulumi.InvokeOptions() if",
"pulumi.get(self, \"label\") @property @pulumi.getter(name=\"labelPrefix\") def label_prefix(self) -> Optional[str]: return pulumi.get(self, \"label_prefix\") @property @pulumi.getter",
"pulumi.get(self, \"id\") @property @pulumi.getter def label(self) -> Optional[str]: \"\"\" `label` of application. \"\"\"",
"Tuple, Union from .. import _utilities, _tables __all__ = [ 'GetAppResult', 'AwaitableGetAppResult', 'get_app',",
"if status and not isinstance(status, str): raise TypeError(\"Expected argument 'status' to be a",
"= _utilities.get_version() __ret__ = pulumi.runtime.invoke('okta:app/getApp:getApp', __args__, opts=opts, typ=GetAppResult).value return AwaitableGetAppResult( active_only=__ret__.active_only, description=__ret__.description, id=__ret__.id,",
"isinstance(description, str): raise TypeError(\"Expected argument 'description' to be a str\") pulumi.set(__self__, \"description\", description)",
"the collaborators for a given repository. ## Example Usage ```python import pulumi import",
"`label` and `id`. This will tell the provider to do a `starts with`",
"to retrieve, conflicts with `label_prefix` and `id`. :param str label_prefix: Label prefix of",
"pylint: disable=using-constant-test def __await__(self): if False: yield self return GetAppResult( active_only=self.active_only, description=self.description, id=self.id,",
"label=None, label_prefix=None, name=None, status=None): if active_only and not isinstance(active_only, bool): raise TypeError(\"Expected argument",
"Tool. *** # *** Do not edit by hand unless you're certain you",
"## Example Usage ```python import pulumi import pulumi_okta as okta example = okta.app.get_app(label=\"Example",
"pulumi.set(__self__, \"id\", id) if label and not isinstance(label, str): raise TypeError(\"Expected argument 'label'",
"active_only=None, description=None, id=None, label=None, label_prefix=None, name=None, status=None): if active_only and not isinstance(active_only, bool):",
"str id: `id` of application to retrieve, conflicts with `label` and `label_prefix`. :param",
"returned by getApp. \"\"\" def __init__(__self__, active_only=None, description=None, id=None, label=None, label_prefix=None, name=None, status=None):",
"List, Mapping, Optional, Tuple, Union from .. import _utilities, _tables __all__ = [",
"label=self.label, label_prefix=self.label_prefix, name=self.name, status=self.status) def get_app(active_only: Optional[bool] = None, id: Optional[str] = None,",
"active_only __args__['id'] = id __args__['label'] = label __args__['labelPrefix'] = label_prefix if opts is",
"id=self.id, label=self.label, label_prefix=self.label_prefix, name=self.name, status=self.status) def get_app(active_only: Optional[bool] = None, id: Optional[str] =",
"`starts with` query as opposed to an `equals` query. \"\"\" __args__ = dict()",
"edit by hand unless you're certain you know what you are doing! ***",
"to be a str\") pulumi.set(__self__, \"label_prefix\", label_prefix) if name and not isinstance(name, str):",
"and not isinstance(description, str): raise TypeError(\"Expected argument 'description' to be a str\") pulumi.set(__self__,",
"description(self) -> str: \"\"\" `description` of application. \"\"\" return pulumi.get(self, \"description\") @property @pulumi.getter",
"\"status\") class AwaitableGetAppResult(GetAppResult): # pylint: disable=using-constant-test def __await__(self): if False: yield self return",
"\"id\", id) if label and not isinstance(label, str): raise TypeError(\"Expected argument 'label' to",
"active_only: tells the provider to query for only `ACTIVE` applications. :param str id:",
"and not isinstance(label_prefix, str): raise TypeError(\"Expected argument 'label_prefix' to be a str\") pulumi.set(__self__,",
"and not isinstance(active_only, bool): raise TypeError(\"Expected argument 'active_only' to be a bool\") pulumi.set(__self__,",
"if label and not isinstance(label, str): raise TypeError(\"Expected argument 'label' to be a",
"label_prefix: Optional[str] = None, opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetAppResult: \"\"\" Use this",
"from .. import _utilities, _tables __all__ = [ 'GetAppResult', 'AwaitableGetAppResult', 'get_app', ] @pulumi.output_type",
"-> str: \"\"\" `description` of application. \"\"\" return pulumi.get(self, \"description\") @property @pulumi.getter def",
"and not isinstance(name, str): raise TypeError(\"Expected argument 'name' to be a str\") pulumi.set(__self__,",
"is None: opts.version = _utilities.get_version() __ret__ = pulumi.runtime.invoke('okta:app/getApp:getApp', __args__, opts=opts, typ=GetAppResult).value return AwaitableGetAppResult(",
"\"\"\" return pulumi.get(self, \"name\") @property @pulumi.getter def status(self) -> str: \"\"\" `status` of",
"'id' to be a str\") pulumi.set(__self__, \"id\", id) if label and not isinstance(label,",
"and not isinstance(status, str): raise TypeError(\"Expected argument 'status' to be a str\") pulumi.set(__self__,",
"return pulumi.get(self, \"name\") @property @pulumi.getter def status(self) -> str: \"\"\" `status` of application.",
"Optional[str] = None, label: Optional[str] = None, label_prefix: Optional[str] = None, opts: Optional[pulumi.InvokeOptions]",
"pulumi.set(__self__, \"label_prefix\", label_prefix) if name and not isinstance(name, str): raise TypeError(\"Expected argument 'name'",
":param str label_prefix: Label prefix of the app to retrieve, conflicts with `label`",
"Dict, List, Mapping, Optional, Tuple, Union from .. import _utilities, _tables __all__ =",
"TypeError(\"Expected argument 'active_only' to be a bool\") pulumi.set(__self__, \"active_only\", active_only) if description and",
"_tables __all__ = [ 'GetAppResult', 'AwaitableGetAppResult', 'get_app', ] @pulumi.output_type class GetAppResult: \"\"\" A",
"label) if label_prefix and not isinstance(label_prefix, str): raise TypeError(\"Expected argument 'label_prefix' to be",
"tell the provider to do a `starts with` query as opposed to an",
"import pulumi.runtime from typing import Any, Dict, List, Mapping, Optional, Tuple, Union from",
"repository. ## Example Usage ```python import pulumi import pulumi_okta as okta example =",
"app to retrieve, conflicts with `label_prefix` and `id`. :param str label_prefix: Label prefix",
"pulumi.runtime.invoke('okta:app/getApp:getApp', __args__, opts=opts, typ=GetAppResult).value return AwaitableGetAppResult( active_only=__ret__.active_only, description=__ret__.description, id=__ret__.id, label=__ret__.label, label_prefix=__ret__.label_prefix, name=__ret__.name, status=__ret__.status)",
"Label prefix of the app to retrieve, conflicts with `label` and `id`. This",
"label __args__['labelPrefix'] = label_prefix if opts is None: opts = pulumi.InvokeOptions() if opts.version",
"return pulumi.get(self, \"label_prefix\") @property @pulumi.getter def name(self) -> str: \"\"\" `name` of application.",
"pulumi.get(self, \"name\") @property @pulumi.getter def status(self) -> str: \"\"\" `status` of application. \"\"\"",
"name and not isinstance(name, str): raise TypeError(\"Expected argument 'name' to be a str\")",
"`id`. This will tell the provider to do a `starts with` query as",
"\"\"\" return pulumi.get(self, \"status\") class AwaitableGetAppResult(GetAppResult): # pylint: disable=using-constant-test def __await__(self): if False:",
"pulumi.runtime from typing import Any, Dict, List, Mapping, Optional, Tuple, Union from ..",
"raise TypeError(\"Expected argument 'status' to be a str\") pulumi.set(__self__, \"status\", status) @property @pulumi.getter(name=\"activeOnly\")",
"and `id`. This will tell the provider to do a `starts with` query",
"opts.version is None: opts.version = _utilities.get_version() __ret__ = pulumi.runtime.invoke('okta:app/getApp:getApp', __args__, opts=opts, typ=GetAppResult).value return",
"'description' to be a str\") pulumi.set(__self__, \"description\", description) if id and not isinstance(id,",
"argument 'description' to be a str\") pulumi.set(__self__, \"description\", description) if id and not",
"\"\"\" def __init__(__self__, active_only=None, description=None, id=None, label=None, label_prefix=None, name=None, status=None): if active_only and",
"```python import pulumi import pulumi_okta as okta example = okta.app.get_app(label=\"Example App\") ``` :param",
"conflicts with `label_prefix` and `id`. :param str label_prefix: Label prefix of the app",
"Union from .. import _utilities, _tables __all__ = [ 'GetAppResult', 'AwaitableGetAppResult', 'get_app', ]",
"active_only(self) -> Optional[bool]: return pulumi.get(self, \"active_only\") @property @pulumi.getter def description(self) -> str: \"\"\"",
"of the app to retrieve, conflicts with `label_prefix` and `id`. :param str label_prefix:",
"`label` of application. \"\"\" return pulumi.get(self, \"label\") @property @pulumi.getter(name=\"labelPrefix\") def label_prefix(self) -> Optional[str]:",
"if opts is None: opts = pulumi.InvokeOptions() if opts.version is None: opts.version =",
"label_prefix=None, name=None, status=None): if active_only and not isinstance(active_only, bool): raise TypeError(\"Expected argument 'active_only'",
"*** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool.",
"AwaitableGetAppResult(GetAppResult): # pylint: disable=using-constant-test def __await__(self): if False: yield self return GetAppResult( active_only=self.active_only,",
"This will tell the provider to do a `starts with` query as opposed",
"= dict() __args__['activeOnly'] = active_only __args__['id'] = id __args__['label'] = label __args__['labelPrefix'] =",
"application. \"\"\" return pulumi.get(self, \"description\") @property @pulumi.getter def id(self) -> Optional[str]: \"\"\" `id`",
"-> Optional[str]: return pulumi.get(self, \"label_prefix\") @property @pulumi.getter def name(self) -> str: \"\"\" `name`",
"by the Pulumi Terraform Bridge (tfgen) Tool. *** # *** Do not edit",
"id(self) -> Optional[str]: \"\"\" `id` of application. \"\"\" return pulumi.get(self, \"id\") @property @pulumi.getter",
"pulumi.get(self, \"status\") class AwaitableGetAppResult(GetAppResult): # pylint: disable=using-constant-test def __await__(self): if False: yield self",
"pulumi.get(self, \"description\") @property @pulumi.getter def id(self) -> Optional[str]: \"\"\" `id` of application. \"\"\"",
"'status' to be a str\") pulumi.set(__self__, \"status\", status) @property @pulumi.getter(name=\"activeOnly\") def active_only(self) ->",
"from typing import Any, Dict, List, Mapping, Optional, Tuple, Union from .. import",
"-> AwaitableGetAppResult: \"\"\" Use this data source to retrieve the collaborators for a",
"App\") ``` :param bool active_only: tells the provider to query for only `ACTIVE`",
"retrieve, conflicts with `label` and `label_prefix`. :param str label: The label of the",
"label(self) -> Optional[str]: \"\"\" `label` of application. \"\"\" return pulumi.get(self, \"label\") @property @pulumi.getter(name=\"labelPrefix\")",
"Optional[pulumi.InvokeOptions] = None) -> AwaitableGetAppResult: \"\"\" Use this data source to retrieve the",
"will tell the provider to do a `starts with` query as opposed to",
"str: \"\"\" `description` of application. \"\"\" return pulumi.get(self, \"description\") @property @pulumi.getter def id(self)",
"import pulumi import pulumi_okta as okta example = okta.app.get_app(label=\"Example App\") ``` :param bool",
"if active_only and not isinstance(active_only, bool): raise TypeError(\"Expected argument 'active_only' to be a",
"raise TypeError(\"Expected argument 'name' to be a str\") pulumi.set(__self__, \"name\", name) if status",
"of application. \"\"\" return pulumi.get(self, \"status\") class AwaitableGetAppResult(GetAppResult): # pylint: disable=using-constant-test def __await__(self):",
"Pulumi Terraform Bridge (tfgen) Tool. *** # *** Do not edit by hand",
"None) -> AwaitableGetAppResult: \"\"\" Use this data source to retrieve the collaborators for",
"of application. \"\"\" return pulumi.get(self, \"label\") @property @pulumi.getter(name=\"labelPrefix\") def label_prefix(self) -> Optional[str]: return",
"description and not isinstance(description, str): raise TypeError(\"Expected argument 'description' to be a str\")",
"argument 'id' to be a str\") pulumi.set(__self__, \"id\", id) if label and not",
"Mapping, Optional, Tuple, Union from .. import _utilities, _tables __all__ = [ 'GetAppResult',",
"The label of the app to retrieve, conflicts with `label_prefix` and `id`. :param",
"opposed to an `equals` query. \"\"\" __args__ = dict() __args__['activeOnly'] = active_only __args__['id']",
"TypeError(\"Expected argument 'id' to be a str\") pulumi.set(__self__, \"id\", id) if label and",
"raise TypeError(\"Expected argument 'id' to be a str\") pulumi.set(__self__, \"id\", id) if label",
"# coding=utf-8 # *** WARNING: this file was generated by the Pulumi Terraform",
"return pulumi.get(self, \"status\") class AwaitableGetAppResult(GetAppResult): # pylint: disable=using-constant-test def __await__(self): if False: yield",
"label and not isinstance(label, str): raise TypeError(\"Expected argument 'label' to be a str\")",
"# pylint: disable=using-constant-test def __await__(self): if False: yield self return GetAppResult( active_only=self.active_only, description=self.description,",
"certain you know what you are doing! *** import warnings import pulumi import",
".. import _utilities, _tables __all__ = [ 'GetAppResult', 'AwaitableGetAppResult', 'get_app', ] @pulumi.output_type class",
"argument 'active_only' to be a bool\") pulumi.set(__self__, \"active_only\", active_only) if description and not",
"'label_prefix' to be a str\") pulumi.set(__self__, \"label_prefix\", label_prefix) if name and not isinstance(name,",
"application. \"\"\" return pulumi.get(self, \"name\") @property @pulumi.getter def status(self) -> str: \"\"\" `status`",
"`equals` query. \"\"\" __args__ = dict() __args__['activeOnly'] = active_only __args__['id'] = id __args__['label']",
"\"\"\" `name` of application. \"\"\" return pulumi.get(self, \"name\") @property @pulumi.getter def status(self) ->",
"yield self return GetAppResult( active_only=self.active_only, description=self.description, id=self.id, label=self.label, label_prefix=self.label_prefix, name=self.name, status=self.status) def get_app(active_only:",
"to do a `starts with` query as opposed to an `equals` query. \"\"\"",
"label_prefix if opts is None: opts = pulumi.InvokeOptions() if opts.version is None: opts.version",
"@pulumi.getter def description(self) -> str: \"\"\" `description` of application. \"\"\" return pulumi.get(self, \"description\")",
"values returned by getApp. \"\"\" def __init__(__self__, active_only=None, description=None, id=None, label=None, label_prefix=None, name=None,",
"str\") pulumi.set(__self__, \"id\", id) if label and not isinstance(label, str): raise TypeError(\"Expected argument",
"argument 'label_prefix' to be a str\") pulumi.set(__self__, \"label_prefix\", label_prefix) if name and not",
"a str\") pulumi.set(__self__, \"description\", description) if id and not isinstance(id, str): raise TypeError(\"Expected",
"description=None, id=None, label=None, label_prefix=None, name=None, status=None): if active_only and not isinstance(active_only, bool): raise",
"\"label\") @property @pulumi.getter(name=\"labelPrefix\") def label_prefix(self) -> Optional[str]: return pulumi.get(self, \"label_prefix\") @property @pulumi.getter def",
"provider to query for only `ACTIVE` applications. :param str id: `id` of application",
"retrieve the collaborators for a given repository. ## Example Usage ```python import pulumi",
"'label' to be a str\") pulumi.set(__self__, \"label\", label) if label_prefix and not isinstance(label_prefix,",
"def get_app(active_only: Optional[bool] = None, id: Optional[str] = None, label: Optional[str] = None,",
"Optional[bool]: return pulumi.get(self, \"active_only\") @property @pulumi.getter def description(self) -> str: \"\"\" `description` of",
"isinstance(status, str): raise TypeError(\"Expected argument 'status' to be a str\") pulumi.set(__self__, \"status\", status)",
"a `starts with` query as opposed to an `equals` query. \"\"\" __args__ =",
"Use this data source to retrieve the collaborators for a given repository. ##",
"str): raise TypeError(\"Expected argument 'id' to be a str\") pulumi.set(__self__, \"id\", id) if",
"know what you are doing! *** import warnings import pulumi import pulumi.runtime from",
"return pulumi.get(self, \"id\") @property @pulumi.getter def label(self) -> Optional[str]: \"\"\" `label` of application.",
"@property @pulumi.getter(name=\"labelPrefix\") def label_prefix(self) -> Optional[str]: return pulumi.get(self, \"label_prefix\") @property @pulumi.getter def name(self)",
":param str label: The label of the app to retrieve, conflicts with `label_prefix`",
"bool): raise TypeError(\"Expected argument 'active_only' to be a bool\") pulumi.set(__self__, \"active_only\", active_only) if",
"*** import warnings import pulumi import pulumi.runtime from typing import Any, Dict, List,",
"to be a str\") pulumi.set(__self__, \"label\", label) if label_prefix and not isinstance(label_prefix, str):",
"str label: The label of the app to retrieve, conflicts with `label_prefix` and",
"pulumi import pulumi_okta as okta example = okta.app.get_app(label=\"Example App\") ``` :param bool active_only:",
"= [ 'GetAppResult', 'AwaitableGetAppResult', 'get_app', ] @pulumi.output_type class GetAppResult: \"\"\" A collection of",
"applications. :param str id: `id` of application to retrieve, conflicts with `label` and",
"_utilities.get_version() __ret__ = pulumi.runtime.invoke('okta:app/getApp:getApp', __args__, opts=opts, typ=GetAppResult).value return AwaitableGetAppResult( active_only=__ret__.active_only, description=__ret__.description, id=__ret__.id, label=__ret__.label,",
"Optional, Tuple, Union from .. import _utilities, _tables __all__ = [ 'GetAppResult', 'AwaitableGetAppResult',",
"label_prefix: Label prefix of the app to retrieve, conflicts with `label` and `id`.",
"None: opts.version = _utilities.get_version() __ret__ = pulumi.runtime.invoke('okta:app/getApp:getApp', __args__, opts=opts, typ=GetAppResult).value return AwaitableGetAppResult( active_only=__ret__.active_only,",
"status) @property @pulumi.getter(name=\"activeOnly\") def active_only(self) -> Optional[bool]: return pulumi.get(self, \"active_only\") @property @pulumi.getter def",
"only `ACTIVE` applications. :param str id: `id` of application to retrieve, conflicts with",
"isinstance(label, str): raise TypeError(\"Expected argument 'label' to be a str\") pulumi.set(__self__, \"label\", label)",
"to query for only `ACTIVE` applications. :param str id: `id` of application to",
"str): raise TypeError(\"Expected argument 'description' to be a str\") pulumi.set(__self__, \"description\", description) if",
"label: Optional[str] = None, label_prefix: Optional[str] = None, opts: Optional[pulumi.InvokeOptions] = None) ->",
"conflicts with `label` and `label_prefix`. :param str label: The label of the app",
"def label_prefix(self) -> Optional[str]: return pulumi.get(self, \"label_prefix\") @property @pulumi.getter def name(self) -> str:",
"return pulumi.get(self, \"active_only\") @property @pulumi.getter def description(self) -> str: \"\"\" `description` of application.",
"def description(self) -> str: \"\"\" `description` of application. \"\"\" return pulumi.get(self, \"description\") @property",
"application to retrieve, conflicts with `label` and `label_prefix`. :param str label: The label",
"'AwaitableGetAppResult', 'get_app', ] @pulumi.output_type class GetAppResult: \"\"\" A collection of values returned by",
"to be a str\") pulumi.set(__self__, \"status\", status) @property @pulumi.getter(name=\"activeOnly\") def active_only(self) -> Optional[bool]:",
"id and not isinstance(id, str): raise TypeError(\"Expected argument 'id' to be a str\")",
"_utilities, _tables __all__ = [ 'GetAppResult', 'AwaitableGetAppResult', 'get_app', ] @pulumi.output_type class GetAppResult: \"\"\"",
"\"label_prefix\") @property @pulumi.getter def name(self) -> str: \"\"\" `name` of application. \"\"\" return",
"opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetAppResult: \"\"\" Use this data source to retrieve",
"Do not edit by hand unless you're certain you know what you are",
"import warnings import pulumi import pulumi.runtime from typing import Any, Dict, List, Mapping,",
"description) if id and not isinstance(id, str): raise TypeError(\"Expected argument 'id' to be",
"False: yield self return GetAppResult( active_only=self.active_only, description=self.description, id=self.id, label=self.label, label_prefix=self.label_prefix, name=self.name, status=self.status) def",
"to be a bool\") pulumi.set(__self__, \"active_only\", active_only) if description and not isinstance(description, str):",
"by getApp. \"\"\" def __init__(__self__, active_only=None, description=None, id=None, label=None, label_prefix=None, name=None, status=None): if",
"of application. \"\"\" return pulumi.get(self, \"description\") @property @pulumi.getter def id(self) -> Optional[str]: \"\"\"",
"opts = pulumi.InvokeOptions() if opts.version is None: opts.version = _utilities.get_version() __ret__ = pulumi.runtime.invoke('okta:app/getApp:getApp',",
"be a str\") pulumi.set(__self__, \"label\", label) if label_prefix and not isinstance(label_prefix, str): raise",
"\"\"\" `label` of application. \"\"\" return pulumi.get(self, \"label\") @property @pulumi.getter(name=\"labelPrefix\") def label_prefix(self) ->",
"are doing! *** import warnings import pulumi import pulumi.runtime from typing import Any,",
"generated by the Pulumi Terraform Bridge (tfgen) Tool. *** # *** Do not",
"WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***",
"a bool\") pulumi.set(__self__, \"active_only\", active_only) if description and not isinstance(description, str): raise TypeError(\"Expected",
"`id` of application to retrieve, conflicts with `label` and `label_prefix`. :param str label:",
"`name` of application. \"\"\" return pulumi.get(self, \"name\") @property @pulumi.getter def status(self) -> str:",
"id=None, label=None, label_prefix=None, name=None, status=None): if active_only and not isinstance(active_only, bool): raise TypeError(\"Expected",
"pulumi.get(self, \"label_prefix\") @property @pulumi.getter def name(self) -> str: \"\"\" `name` of application. \"\"\"",
"not isinstance(label, str): raise TypeError(\"Expected argument 'label' to be a str\") pulumi.set(__self__, \"label\",",
"is None: opts = pulumi.InvokeOptions() if opts.version is None: opts.version = _utilities.get_version() __ret__",
"not isinstance(description, str): raise TypeError(\"Expected argument 'description' to be a str\") pulumi.set(__self__, \"description\",",
"Any, Dict, List, Mapping, Optional, Tuple, Union from .. import _utilities, _tables __all__",
"the provider to do a `starts with` query as opposed to an `equals`",
"Optional[str]: \"\"\" `id` of application. \"\"\" return pulumi.get(self, \"id\") @property @pulumi.getter def label(self)",
"self return GetAppResult( active_only=self.active_only, description=self.description, id=self.id, label=self.label, label_prefix=self.label_prefix, name=self.name, status=self.status) def get_app(active_only: Optional[bool]",
"do a `starts with` query as opposed to an `equals` query. \"\"\" __args__",
"= None, id: Optional[str] = None, label: Optional[str] = None, label_prefix: Optional[str] =",
"str\") pulumi.set(__self__, \"label_prefix\", label_prefix) if name and not isinstance(name, str): raise TypeError(\"Expected argument",
"active_only and not isinstance(active_only, bool): raise TypeError(\"Expected argument 'active_only' to be a bool\")",
"AwaitableGetAppResult: \"\"\" Use this data source to retrieve the collaborators for a given",
"= None, label_prefix: Optional[str] = None, opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetAppResult: \"\"\"",
"id __args__['label'] = label __args__['labelPrefix'] = label_prefix if opts is None: opts =",
"the app to retrieve, conflicts with `label_prefix` and `id`. :param str label_prefix: Label",
"Optional[str]: \"\"\" `label` of application. \"\"\" return pulumi.get(self, \"label\") @property @pulumi.getter(name=\"labelPrefix\") def label_prefix(self)",
"= None, opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetAppResult: \"\"\" Use this data source",
"a str\") pulumi.set(__self__, \"name\", name) if status and not isinstance(status, str): raise TypeError(\"Expected",
"@property @pulumi.getter def description(self) -> str: \"\"\" `description` of application. \"\"\" return pulumi.get(self,",
"doing! *** import warnings import pulumi import pulumi.runtime from typing import Any, Dict,",
"to be a str\") pulumi.set(__self__, \"name\", name) if status and not isinstance(status, str):",
"status(self) -> str: \"\"\" `status` of application. \"\"\" return pulumi.get(self, \"status\") class AwaitableGetAppResult(GetAppResult):",
"argument 'name' to be a str\") pulumi.set(__self__, \"name\", name) if status and not",
"application. \"\"\" return pulumi.get(self, \"id\") @property @pulumi.getter def label(self) -> Optional[str]: \"\"\" `label`",
"= okta.app.get_app(label=\"Example App\") ``` :param bool active_only: tells the provider to query for",
"a str\") pulumi.set(__self__, \"label\", label) if label_prefix and not isinstance(label_prefix, str): raise TypeError(\"Expected",
"argument 'label' to be a str\") pulumi.set(__self__, \"label\", label) if label_prefix and not",
"hand unless you're certain you know what you are doing! *** import warnings",
"not isinstance(label_prefix, str): raise TypeError(\"Expected argument 'label_prefix' to be a str\") pulumi.set(__self__, \"label_prefix\",",
"Usage ```python import pulumi import pulumi_okta as okta example = okta.app.get_app(label=\"Example App\") ```",
"this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. *** #",
"\"\"\" `status` of application. \"\"\" return pulumi.get(self, \"status\") class AwaitableGetAppResult(GetAppResult): # pylint: disable=using-constant-test",
"as opposed to an `equals` query. \"\"\" __args__ = dict() __args__['activeOnly'] = active_only",
"to be a str\") pulumi.set(__self__, \"id\", id) if label and not isinstance(label, str):",
"str\") pulumi.set(__self__, \"name\", name) if status and not isinstance(status, str): raise TypeError(\"Expected argument",
"of application to retrieve, conflicts with `label` and `label_prefix`. :param str label: The",
"\"\"\" A collection of values returned by getApp. \"\"\" def __init__(__self__, active_only=None, description=None,",
"if name and not isinstance(name, str): raise TypeError(\"Expected argument 'name' to be a",
"of the app to retrieve, conflicts with `label` and `id`. This will tell",
"None, opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetAppResult: \"\"\" Use this data source to",
"'name' to be a str\") pulumi.set(__self__, \"name\", name) if status and not isinstance(status,",
"application. \"\"\" return pulumi.get(self, \"label\") @property @pulumi.getter(name=\"labelPrefix\") def label_prefix(self) -> Optional[str]: return pulumi.get(self,",
"`description` of application. \"\"\" return pulumi.get(self, \"description\") @property @pulumi.getter def id(self) -> Optional[str]:",
"\"label\", label) if label_prefix and not isinstance(label_prefix, str): raise TypeError(\"Expected argument 'label_prefix' to",
"str label_prefix: Label prefix of the app to retrieve, conflicts with `label` and",
"TypeError(\"Expected argument 'status' to be a str\") pulumi.set(__self__, \"status\", status) @property @pulumi.getter(name=\"activeOnly\") def",
"dict() __args__['activeOnly'] = active_only __args__['id'] = id __args__['label'] = label __args__['labelPrefix'] = label_prefix",
"__all__ = [ 'GetAppResult', 'AwaitableGetAppResult', 'get_app', ] @pulumi.output_type class GetAppResult: \"\"\" A collection",
"what you are doing! *** import warnings import pulumi import pulumi.runtime from typing",
"tells the provider to query for only `ACTIVE` applications. :param str id: `id`",
"@pulumi.output_type class GetAppResult: \"\"\" A collection of values returned by getApp. \"\"\" def",
"Example Usage ```python import pulumi import pulumi_okta as okta example = okta.app.get_app(label=\"Example App\")",
"__args__ = dict() __args__['activeOnly'] = active_only __args__['id'] = id __args__['label'] = label __args__['labelPrefix']",
"you know what you are doing! *** import warnings import pulumi import pulumi.runtime",
"\"description\", description) if id and not isinstance(id, str): raise TypeError(\"Expected argument 'id' to",
"str: \"\"\" `name` of application. \"\"\" return pulumi.get(self, \"name\") @property @pulumi.getter def status(self)",
"get_app(active_only: Optional[bool] = None, id: Optional[str] = None, label: Optional[str] = None, label_prefix:",
"str\") pulumi.set(__self__, \"description\", description) if id and not isinstance(id, str): raise TypeError(\"Expected argument",
"\"name\", name) if status and not isinstance(status, str): raise TypeError(\"Expected argument 'status' to",
"def active_only(self) -> Optional[bool]: return pulumi.get(self, \"active_only\") @property @pulumi.getter def description(self) -> str:",
"'active_only' to be a bool\") pulumi.set(__self__, \"active_only\", active_only) if description and not isinstance(description,",
"isinstance(active_only, bool): raise TypeError(\"Expected argument 'active_only' to be a bool\") pulumi.set(__self__, \"active_only\", active_only)",
"to an `equals` query. \"\"\" __args__ = dict() __args__['activeOnly'] = active_only __args__['id'] =",
"for only `ACTIVE` applications. :param str id: `id` of application to retrieve, conflicts",
"__await__(self): if False: yield self return GetAppResult( active_only=self.active_only, description=self.description, id=self.id, label=self.label, label_prefix=self.label_prefix, name=self.name,",
"\"id\") @property @pulumi.getter def label(self) -> Optional[str]: \"\"\" `label` of application. \"\"\" return",
":param str id: `id` of application to retrieve, conflicts with `label` and `label_prefix`.",
"None, label: Optional[str] = None, label_prefix: Optional[str] = None, opts: Optional[pulumi.InvokeOptions] = None)",
"argument 'status' to be a str\") pulumi.set(__self__, \"status\", status) @property @pulumi.getter(name=\"activeOnly\") def active_only(self)",
"@pulumi.getter def status(self) -> str: \"\"\" `status` of application. \"\"\" return pulumi.get(self, \"status\")",
"getApp. \"\"\" def __init__(__self__, active_only=None, description=None, id=None, label=None, label_prefix=None, name=None, status=None): if active_only",
"file was generated by the Pulumi Terraform Bridge (tfgen) Tool. *** # ***",
"Optional[str] = None, opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetAppResult: \"\"\" Use this data",
"name=self.name, status=self.status) def get_app(active_only: Optional[bool] = None, id: Optional[str] = None, label: Optional[str]",
"not isinstance(id, str): raise TypeError(\"Expected argument 'id' to be a str\") pulumi.set(__self__, \"id\",",
"retrieve, conflicts with `label_prefix` and `id`. :param str label_prefix: Label prefix of the",
"pulumi.InvokeOptions() if opts.version is None: opts.version = _utilities.get_version() __ret__ = pulumi.runtime.invoke('okta:app/getApp:getApp', __args__, opts=opts,",
"pulumi import pulumi.runtime from typing import Any, Dict, List, Mapping, Optional, Tuple, Union",
"collection of values returned by getApp. \"\"\" def __init__(__self__, active_only=None, description=None, id=None, label=None,",
"isinstance(id, str): raise TypeError(\"Expected argument 'id' to be a str\") pulumi.set(__self__, \"id\", id)",
"label: The label of the app to retrieve, conflicts with `label_prefix` and `id`.",
"was generated by the Pulumi Terraform Bridge (tfgen) Tool. *** # *** Do",
"-> Optional[str]: \"\"\" `label` of application. \"\"\" return pulumi.get(self, \"label\") @property @pulumi.getter(name=\"labelPrefix\") def",
"be a str\") pulumi.set(__self__, \"label_prefix\", label_prefix) if name and not isinstance(name, str): raise",
"opts.version = _utilities.get_version() __ret__ = pulumi.runtime.invoke('okta:app/getApp:getApp', __args__, opts=opts, typ=GetAppResult).value return AwaitableGetAppResult( active_only=__ret__.active_only, description=__ret__.description,",
"@property @pulumi.getter def label(self) -> Optional[str]: \"\"\" `label` of application. \"\"\" return pulumi.get(self,",
"name) if status and not isinstance(status, str): raise TypeError(\"Expected argument 'status' to be",
"= id __args__['label'] = label __args__['labelPrefix'] = label_prefix if opts is None: opts",
"of application. \"\"\" return pulumi.get(self, \"name\") @property @pulumi.getter def status(self) -> str: \"\"\"",
"with` query as opposed to an `equals` query. \"\"\" __args__ = dict() __args__['activeOnly']",
"\"\"\" return pulumi.get(self, \"label\") @property @pulumi.getter(name=\"labelPrefix\") def label_prefix(self) -> Optional[str]: return pulumi.get(self, \"label_prefix\")",
"-> Optional[bool]: return pulumi.get(self, \"active_only\") @property @pulumi.getter def description(self) -> str: \"\"\" `description`",
"str\") pulumi.set(__self__, \"status\", status) @property @pulumi.getter(name=\"activeOnly\") def active_only(self) -> Optional[bool]: return pulumi.get(self, \"active_only\")"
] |
[
"= v[step-1] + dt/tau * (el - v[step-1] + r*i) with plt.xkcd(): #",
"= el * np.ones(step_end) syn = i_mean * (1 + 0.1*(t_max/dt)**(0.5)*(2*np.random.random(step_end)-1)) # loop",
"* np.ones(step_end) syn = i_mean * (1 + 0.1*(t_max/dt)**(0.5)*(2*np.random.random(step_end)-1)) # loop for step_end",
"# initialize the figure plt.figure() plt.title('$V_m$ with random I(t)') plt.xlabel('time (s)') plt.ylabel(r'$V_m$ (V)')",
"t_range = np.linspace(0, t_max, num=step_end) v = el * np.ones(step_end) syn = i_mean",
"<gh_stars>1-10 # set random number generator np.random.seed(2020) # initialize step_end, t_range, v and",
"for step_end values of syn for step, i in enumerate(syn): # skip first",
"# skip first iteration if step==0: continue v[step] = v[step-1] + dt/tau *",
"figure plt.figure() plt.title('$V_m$ with random I(t)') plt.xlabel('time (s)') plt.ylabel(r'$V_m$ (V)') plt.plot(t_range, v, 'k')",
"step==0: continue v[step] = v[step-1] + dt/tau * (el - v[step-1] + r*i)",
"= i_mean * (1 + 0.1*(t_max/dt)**(0.5)*(2*np.random.random(step_end)-1)) # loop for step_end values of syn",
"# loop for step_end values of syn for step, i in enumerate(syn): #",
"v[step-1] + dt/tau * (el - v[step-1] + r*i) with plt.xkcd(): # initialize",
"v[step-1] + r*i) with plt.xkcd(): # initialize the figure plt.figure() plt.title('$V_m$ with random",
"plt.figure() plt.title('$V_m$ with random I(t)') plt.xlabel('time (s)') plt.ylabel(r'$V_m$ (V)') plt.plot(t_range, v, 'k') plt.show()",
"v[step] = v[step-1] + dt/tau * (el - v[step-1] + r*i) with plt.xkcd():",
"step, i in enumerate(syn): # skip first iteration if step==0: continue v[step] =",
"= np.linspace(0, t_max, num=step_end) v = el * np.ones(step_end) syn = i_mean *",
"of syn for step, i in enumerate(syn): # skip first iteration if step==0:",
"if step==0: continue v[step] = v[step-1] + dt/tau * (el - v[step-1] +",
"initialize step_end, t_range, v and syn step_end = int(t_max/dt) t_range = np.linspace(0, t_max,",
"dt/tau * (el - v[step-1] + r*i) with plt.xkcd(): # initialize the figure",
"plt.xkcd(): # initialize the figure plt.figure() plt.title('$V_m$ with random I(t)') plt.xlabel('time (s)') plt.ylabel(r'$V_m$",
"el * np.ones(step_end) syn = i_mean * (1 + 0.1*(t_max/dt)**(0.5)*(2*np.random.random(step_end)-1)) # loop for",
"enumerate(syn): # skip first iteration if step==0: continue v[step] = v[step-1] + dt/tau",
"number generator np.random.seed(2020) # initialize step_end, t_range, v and syn step_end = int(t_max/dt)",
"v and syn step_end = int(t_max/dt) t_range = np.linspace(0, t_max, num=step_end) v =",
"syn step_end = int(t_max/dt) t_range = np.linspace(0, t_max, num=step_end) v = el *",
"skip first iteration if step==0: continue v[step] = v[step-1] + dt/tau * (el",
"t_max, num=step_end) v = el * np.ones(step_end) syn = i_mean * (1 +",
"loop for step_end values of syn for step, i in enumerate(syn): # skip",
"+ dt/tau * (el - v[step-1] + r*i) with plt.xkcd(): # initialize the",
"generator np.random.seed(2020) # initialize step_end, t_range, v and syn step_end = int(t_max/dt) t_range",
"with plt.xkcd(): # initialize the figure plt.figure() plt.title('$V_m$ with random I(t)') plt.xlabel('time (s)')",
"in enumerate(syn): # skip first iteration if step==0: continue v[step] = v[step-1] +",
"set random number generator np.random.seed(2020) # initialize step_end, t_range, v and syn step_end",
"first iteration if step==0: continue v[step] = v[step-1] + dt/tau * (el -",
"- v[step-1] + r*i) with plt.xkcd(): # initialize the figure plt.figure() plt.title('$V_m$ with",
"iteration if step==0: continue v[step] = v[step-1] + dt/tau * (el - v[step-1]",
"for step, i in enumerate(syn): # skip first iteration if step==0: continue v[step]",
"i in enumerate(syn): # skip first iteration if step==0: continue v[step] = v[step-1]",
"syn = i_mean * (1 + 0.1*(t_max/dt)**(0.5)*(2*np.random.random(step_end)-1)) # loop for step_end values of",
"step_end values of syn for step, i in enumerate(syn): # skip first iteration",
"= int(t_max/dt) t_range = np.linspace(0, t_max, num=step_end) v = el * np.ones(step_end) syn",
"+ r*i) with plt.xkcd(): # initialize the figure plt.figure() plt.title('$V_m$ with random I(t)')",
"syn for step, i in enumerate(syn): # skip first iteration if step==0: continue",
"# set random number generator np.random.seed(2020) # initialize step_end, t_range, v and syn",
"values of syn for step, i in enumerate(syn): # skip first iteration if",
"continue v[step] = v[step-1] + dt/tau * (el - v[step-1] + r*i) with",
"t_range, v and syn step_end = int(t_max/dt) t_range = np.linspace(0, t_max, num=step_end) v",
"i_mean * (1 + 0.1*(t_max/dt)**(0.5)*(2*np.random.random(step_end)-1)) # loop for step_end values of syn for",
"random number generator np.random.seed(2020) # initialize step_end, t_range, v and syn step_end =",
"* (1 + 0.1*(t_max/dt)**(0.5)*(2*np.random.random(step_end)-1)) # loop for step_end values of syn for step,",
"v = el * np.ones(step_end) syn = i_mean * (1 + 0.1*(t_max/dt)**(0.5)*(2*np.random.random(step_end)-1)) #",
"step_end, t_range, v and syn step_end = int(t_max/dt) t_range = np.linspace(0, t_max, num=step_end)",
"* (el - v[step-1] + r*i) with plt.xkcd(): # initialize the figure plt.figure()",
"(1 + 0.1*(t_max/dt)**(0.5)*(2*np.random.random(step_end)-1)) # loop for step_end values of syn for step, i",
"# initialize step_end, t_range, v and syn step_end = int(t_max/dt) t_range = np.linspace(0,",
"the figure plt.figure() plt.title('$V_m$ with random I(t)') plt.xlabel('time (s)') plt.ylabel(r'$V_m$ (V)') plt.plot(t_range, v,",
"np.linspace(0, t_max, num=step_end) v = el * np.ones(step_end) syn = i_mean * (1",
"initialize the figure plt.figure() plt.title('$V_m$ with random I(t)') plt.xlabel('time (s)') plt.ylabel(r'$V_m$ (V)') plt.plot(t_range,",
"+ 0.1*(t_max/dt)**(0.5)*(2*np.random.random(step_end)-1)) # loop for step_end values of syn for step, i in",
"(el - v[step-1] + r*i) with plt.xkcd(): # initialize the figure plt.figure() plt.title('$V_m$",
"0.1*(t_max/dt)**(0.5)*(2*np.random.random(step_end)-1)) # loop for step_end values of syn for step, i in enumerate(syn):",
"r*i) with plt.xkcd(): # initialize the figure plt.figure() plt.title('$V_m$ with random I(t)') plt.xlabel('time",
"num=step_end) v = el * np.ones(step_end) syn = i_mean * (1 + 0.1*(t_max/dt)**(0.5)*(2*np.random.random(step_end)-1))",
"and syn step_end = int(t_max/dt) t_range = np.linspace(0, t_max, num=step_end) v = el",
"step_end = int(t_max/dt) t_range = np.linspace(0, t_max, num=step_end) v = el * np.ones(step_end)",
"np.ones(step_end) syn = i_mean * (1 + 0.1*(t_max/dt)**(0.5)*(2*np.random.random(step_end)-1)) # loop for step_end values",
"int(t_max/dt) t_range = np.linspace(0, t_max, num=step_end) v = el * np.ones(step_end) syn =",
"np.random.seed(2020) # initialize step_end, t_range, v and syn step_end = int(t_max/dt) t_range ="
] |
[
"(see below). contrib_name.append(name) contrib_value.append(float(energy)) # Save the new subset. ds.save() # # Adding",
"rxns: # Datapoint's name. name = row[0] # Datapoint's reference energy. energy =",
"The encoding flag is optional, # but necessary if the csv is generated",
"reactions in the following lists: contrib_name = [] contrib_value = [] for row",
"store the values to add in the \"Contributed value\" dictionary (see below). contrib_name.append(name)",
"handle: rxns = [x.split(\",\") for x in handle.read().splitlines()] # Where to find the",
"of Chemistry} } \"\"\", acs_citation=\"<NAME>. & <NAME>. Statistically representative databases for density functional",
"\"Benchmark\", \"theory_level\": \"CCSD(T), CASPT2, Experiment (see ref)\", \"values\": contrib_value, \"index\": contrib_name, \"theory_level_details\": {\"driver\":",
"= args.dry_run if SNOWFLAKE: snowflake = FractalSnowflake() client = snowflake.client() else: client =",
"ptl.models.Citation( bibtex=\"\"\" @article{morgante2019statistically, title={Statistically representative databases for density functional theory via data science},",
"\"ASCDB.csv\" # We read the ASCDB.csv file. The encoding flag is optional, #",
"len(rxn) // 2 molecules = rxn[:half] coefs = rxn[half:] rxn_data = [] #",
"number={35}, pages={19092--19103}, year={2019}, publisher={Royal Society of Chemistry} } \"\"\", acs_citation=\"<NAME>. & <NAME>. Statistically",
"dictionary (see below). contrib_name.append(name) contrib_value.append(float(energy)) # Save the new subset. ds.save() # #",
"handles the definition of a reaction, putting together molecules # and stoichiometric coefficients.",
"Phys., </em><b>2019</b><i>, 21</i>, 19092-19103.\", url=\"https://pubs.rsc.org/en/content/articlehtml/2019/cp/c9cp03211h\", doi=\"10.1039/C9CP03211H\", ) ] # The .csv file needed",
"= [ ptl.models.Citation( bibtex=\"\"\" @article{morgante2019statistically, title={Statistically representative databases for density functional theory via",
"+ \".xyz\") coef = float(coef) rxn_data.append((mol, coef)) rxn = {\"default\": rxn_data} # We",
"[] contrib_value = [] for row in rxns: # Datapoint's name. name =",
"as pd import argparse parser = argparse.ArgumentParser() parser.add_argument(\"-d\", \"--dry-run\", action=\"store_true\") args = parser.parse_args()",
"file. The encoding flag is optional, # but necessary if the csv is",
"= [x.split(\",\") for x in handle.read().splitlines()] # Where to find the geometry files",
"of a reaction, putting together molecules # and stoichiometric coefficients. # for mol_name,",
"\"r\", encoding=\"utf-8-sig\") as handle: rxns = [x.split(\",\") for x in handle.read().splitlines()] # Where",
"csv is generated (for example) with Microsoft Excel. # with open(filename, \"r\", encoding=\"utf-8-sig\")",
"is used to handle the list. half = len(rxn) // 2 molecules =",
"# March 2020. # import qcportal as ptl from qcfractal import FractalSnowflake import",
"import argparse parser = argparse.ArgumentParser() parser.add_argument(\"-d\", \"--dry-run\", action=\"store_true\") args = parser.parse_args() SNOWFLAKE =",
"ptl.FractalClient.from_file() print(client) # The new subset you want to add. dataset_name = \"ASCDB\"",
"publisher={Royal Society of Chemistry} } \"\"\", acs_citation=\"<NAME>. & <NAME>. Statistically representative databases for",
"science}, author={<NAME> and <NAME>}, journal={Physical Chemistry Chemical Physics}, volume={21}, number={35}, pages={19092--19103}, year={2019}, publisher={Royal",
"rxn_data} # We add the reaction to the dataset. ds.add_rxn(name, rxn) # We",
"19092-19103.\", url=\"https://pubs.rsc.org/en/content/articlehtml/2019/cp/c9cp03211h\", doi=\"10.1039/C9CP03211H\", ) ] # The .csv file needed to build everything.",
"mol = ptl.Molecule.from_file(gpath + \"/\" + mol_name + \".xyz\") coef = float(coef) rxn_data.append((mol,",
"from qcfractal import FractalSnowflake import pandas as pd import argparse parser = argparse.ArgumentParser()",
"in rxns: # Datapoint's name. name = row[0] # Datapoint's reference energy. energy",
"<NAME>, <NAME>. # March 2020. # import qcportal as ptl from qcfractal import",
"in the \"Contributed value\" dictionary (see below). contrib_name.append(name) contrib_value.append(float(energy)) # Save the new",
"handled above. # contrib = { \"name\": \"Benchmark\", \"theory_level\": \"CCSD(T), CASPT2, Experiment (see",
"SNOWFLAKE = args.dry_run if SNOWFLAKE: snowflake = FractalSnowflake() client = snowflake.client() else: client",
"pd import argparse parser = argparse.ArgumentParser() parser.add_argument(\"-d\", \"--dry-run\", action=\"store_true\") args = parser.parse_args() SNOWFLAKE",
"= ptl.FractalClient.from_file() print(client) # The new subset you want to add. dataset_name =",
"parser.add_argument(\"-d\", \"--dry-run\", action=\"store_true\") args = parser.parse_args() SNOWFLAKE = args.dry_run if SNOWFLAKE: snowflake =",
"data science}, author={<NAME> and <NAME>}, journal={Physical Chemistry Chemical Physics}, volume={21}, number={35}, pages={19092--19103}, year={2019},",
"# We store the values to add in the \"Contributed value\" dictionary (see",
"= rxn[half:] rxn_data = [] # This loop handles the definition of a",
"# handled above. # contrib = { \"name\": \"Benchmark\", \"theory_level\": \"CCSD(T), CASPT2, Experiment",
"= ptl.collections.ReactionDataset(dataset_name, client=client) # Add the paper ds.data.metadata[\"citations\"] = [ ptl.models.Citation( bibtex=\"\"\" @article{morgante2019statistically,",
"stoichiometric coefficients. # for mol_name, coef in zip(molecules, coefs): mol = ptl.Molecule.from_file(gpath +",
"reaction to the dataset. ds.add_rxn(name, rxn) # We store the values to add",
"by <NAME>, <NAME>, <NAME>. # March 2020. # import qcportal as ptl from",
"rxns list. rxn = row[2:] # This is used to handle the list.",
"x in handle.read().splitlines()] # Where to find the geometry files (in .xyz) gpath",
"SNOWFLAKE: snowflake = FractalSnowflake() client = snowflake.client() else: client = ptl.FractalClient.from_file() print(client) #",
"[] # This loop handles the definition of a reaction, putting together molecules",
"example) with Microsoft Excel. # with open(filename, \"r\", encoding=\"utf-8-sig\") as handle: rxns =",
"parser.parse_args() SNOWFLAKE = args.dry_run if SNOWFLAKE: snowflake = FractalSnowflake() client = snowflake.client() else:",
"FractalSnowflake import pandas as pd import argparse parser = argparse.ArgumentParser() parser.add_argument(\"-d\", \"--dry-run\", action=\"store_true\")",
"contrib_name, \"theory_level_details\": {\"driver\": \"energy\"}, \"units\": \"kcal / mol\", } ds.units = \"kcal/mol\" ds.set_default_benchmark(\"Benchmark\")",
"is needed only for unix-based systems. # Written by <NAME>, <NAME>, <NAME>. #",
"# Adding a contributed value based on the ASCDB csv file and the",
"in the following lists: contrib_name = [] contrib_value = [] for row in",
"add the reaction to the dataset. ds.add_rxn(name, rxn) # We store the values",
"theory via data science}, author={<NAME> and <NAME>}, journal={Physical Chemistry Chemical Physics}, volume={21}, number={35},",
".xyz) gpath = \"ACCDB/Geometries\" # We put names and reactions in the following",
"new subset you want to add. dataset_name = \"ASCDB\" ds = ptl.collections.ReactionDataset(dataset_name, client=client)",
"= { \"name\": \"Benchmark\", \"theory_level\": \"CCSD(T), CASPT2, Experiment (see ref)\", \"values\": contrib_value, \"index\":",
"geometry files (in .xyz) gpath = \"ACCDB/Geometries\" # We put names and reactions",
"open(filename, \"r\", encoding=\"utf-8-sig\") as handle: rxns = [x.split(\",\") for x in handle.read().splitlines()] #",
"is optional, # but necessary if the csv is generated (for example) with",
"energy = row[1] # Datapoint's reaction: from 2 to the end of the",
"{\"default\": rxn_data} # We add the reaction to the dataset. ds.add_rxn(name, rxn) #",
"find the geometry files (in .xyz) gpath = \"ACCDB/Geometries\" # We put names",
"the paper ds.data.metadata[\"citations\"] = [ ptl.models.Citation( bibtex=\"\"\" @article{morgante2019statistically, title={Statistically representative databases for density",
"as handle: rxns = [x.split(\",\") for x in handle.read().splitlines()] # Where to find",
"\"ACCDB/Geometries\" # We put names and reactions in the following lists: contrib_name =",
"rxns = [x.split(\",\") for x in handle.read().splitlines()] # Where to find the geometry",
"ref)\", \"values\": contrib_value, \"index\": contrib_name, \"theory_level_details\": {\"driver\": \"energy\"}, \"units\": \"kcal / mol\", }",
"= float(coef) rxn_data.append((mol, coef)) rxn = {\"default\": rxn_data} # We add the reaction",
"optional, # but necessary if the csv is generated (for example) with Microsoft",
"the new subset. ds.save() # # Adding a contributed value based on the",
"mol_name, coef in zip(molecules, coefs): mol = ptl.Molecule.from_file(gpath + \"/\" + mol_name +",
"float(coef) rxn_data.append((mol, coef)) rxn = {\"default\": rxn_data} # We add the reaction to",
"contrib_value = [] for row in rxns: # Datapoint's name. name = row[0]",
"handle the list. half = len(rxn) // 2 molecules = rxn[:half] coefs =",
"qcportal as ptl from qcfractal import FractalSnowflake import pandas as pd import argparse",
"Python # This line is needed only for unix-based systems. # Written by",
"\"theory_level_details\": {\"driver\": \"energy\"}, \"units\": \"kcal / mol\", } ds.units = \"kcal/mol\" ds.set_default_benchmark(\"Benchmark\") ds.add_contributed_values(contrib)",
"on the ASCDB csv file and the molecules # handled above. # contrib",
"& <NAME>. Statistically representative databases for density functional theory via data science. <em>Phys.",
"(see ref)\", \"values\": contrib_value, \"index\": contrib_name, \"theory_level_details\": {\"driver\": \"energy\"}, \"units\": \"kcal / mol\",",
"print(client) # The new subset you want to add. dataset_name = \"ASCDB\" ds",
"molecules = rxn[:half] coefs = rxn[half:] rxn_data = [] # This loop handles",
"for density functional theory via data science. <em>Phys. Chem. Chem. Phys., </em><b>2019</b><i>, 21</i>,",
"\"energy\"}, \"units\": \"kcal / mol\", } ds.units = \"kcal/mol\" ds.set_default_benchmark(\"Benchmark\") ds.add_contributed_values(contrib) ds.save() #",
"zip(molecules, coefs): mol = ptl.Molecule.from_file(gpath + \"/\" + mol_name + \".xyz\") coef =",
"# Add the paper ds.data.metadata[\"citations\"] = [ ptl.models.Citation( bibtex=\"\"\" @article{morgante2019statistically, title={Statistically representative databases",
"to the end of the rxns list. rxn = row[2:] # This is",
"value\" dictionary (see below). contrib_name.append(name) contrib_value.append(float(energy)) # Save the new subset. ds.save() #",
"the geometry files (in .xyz) gpath = \"ACCDB/Geometries\" # We put names and",
"add in the \"Contributed value\" dictionary (see below). contrib_name.append(name) contrib_value.append(float(energy)) # Save the",
"<NAME>. # March 2020. # import qcportal as ptl from qcfractal import FractalSnowflake",
"Chemistry} } \"\"\", acs_citation=\"<NAME>. & <NAME>. Statistically representative databases for density functional theory",
"We read the ASCDB.csv file. The encoding flag is optional, # but necessary",
"<NAME>, <NAME>, <NAME>. # March 2020. # import qcportal as ptl from qcfractal",
"based on the ASCDB csv file and the molecules # handled above. #",
"everything. filename = \"ASCDB.csv\" # We read the ASCDB.csv file. The encoding flag",
"lists: contrib_name = [] contrib_value = [] for row in rxns: # Datapoint's",
"args.dry_run if SNOWFLAKE: snowflake = FractalSnowflake() client = snowflake.client() else: client = ptl.FractalClient.from_file()",
"\".xyz\") coef = float(coef) rxn_data.append((mol, coef)) rxn = {\"default\": rxn_data} # We add",
"# We read the ASCDB.csv file. The encoding flag is optional, # but",
"Chem. Chem. Phys., </em><b>2019</b><i>, 21</i>, 19092-19103.\", url=\"https://pubs.rsc.org/en/content/articlehtml/2019/cp/c9cp03211h\", doi=\"10.1039/C9CP03211H\", ) ] # The .csv",
"coef)) rxn = {\"default\": rxn_data} # We add the reaction to the dataset.",
"reaction, putting together molecules # and stoichiometric coefficients. # for mol_name, coef in",
"# Written by <NAME>, <NAME>, <NAME>. # March 2020. # import qcportal as",
"ptl.collections.ReactionDataset(dataset_name, client=client) # Add the paper ds.data.metadata[\"citations\"] = [ ptl.models.Citation( bibtex=\"\"\" @article{morgante2019statistically, title={Statistically",
"representative databases for density functional theory via data science}, author={<NAME> and <NAME>}, journal={Physical",
"= ptl.Molecule.from_file(gpath + \"/\" + mol_name + \".xyz\") coef = float(coef) rxn_data.append((mol, coef))",
"</em><b>2019</b><i>, 21</i>, 19092-19103.\", url=\"https://pubs.rsc.org/en/content/articlehtml/2019/cp/c9cp03211h\", doi=\"10.1039/C9CP03211H\", ) ] # The .csv file needed to",
"Society of Chemistry} } \"\"\", acs_citation=\"<NAME>. & <NAME>. Statistically representative databases for density",
"contrib = { \"name\": \"Benchmark\", \"theory_level\": \"CCSD(T), CASPT2, Experiment (see ref)\", \"values\": contrib_value,",
"[x.split(\",\") for x in handle.read().splitlines()] # Where to find the geometry files (in",
"to the dataset. ds.add_rxn(name, rxn) # We store the values to add in",
"science. <em>Phys. Chem. Chem. Phys., </em><b>2019</b><i>, 21</i>, 19092-19103.\", url=\"https://pubs.rsc.org/en/content/articlehtml/2019/cp/c9cp03211h\", doi=\"10.1039/C9CP03211H\", ) ] #",
"Where to find the geometry files (in .xyz) gpath = \"ACCDB/Geometries\" # We",
"want to add. dataset_name = \"ASCDB\" ds = ptl.collections.ReactionDataset(dataset_name, client=client) # Add the",
"snowflake = FractalSnowflake() client = snowflake.client() else: client = ptl.FractalClient.from_file() print(client) # The",
"ds.data.metadata[\"citations\"] = [ ptl.models.Citation( bibtex=\"\"\" @article{morgante2019statistically, title={Statistically representative databases for density functional theory",
"Datapoint's name. name = row[0] # Datapoint's reference energy. energy = row[1] #",
"files (in .xyz) gpath = \"ACCDB/Geometries\" # We put names and reactions in",
"= FractalSnowflake() client = snowflake.client() else: client = ptl.FractalClient.from_file() print(client) # The new",
"the following lists: contrib_name = [] contrib_value = [] for row in rxns:",
"author={<NAME> and <NAME>}, journal={Physical Chemistry Chemical Physics}, volume={21}, number={35}, pages={19092--19103}, year={2019}, publisher={Royal Society",
"and reactions in the following lists: contrib_name = [] contrib_value = [] for",
"Written by <NAME>, <NAME>, <NAME>. # March 2020. # import qcportal as ptl",
"together molecules # and stoichiometric coefficients. # for mol_name, coef in zip(molecules, coefs):",
"url=\"https://pubs.rsc.org/en/content/articlehtml/2019/cp/c9cp03211h\", doi=\"10.1039/C9CP03211H\", ) ] # The .csv file needed to build everything. filename",
"molecules # and stoichiometric coefficients. # for mol_name, coef in zip(molecules, coefs): mol",
"for mol_name, coef in zip(molecules, coefs): mol = ptl.Molecule.from_file(gpath + \"/\" + mol_name",
"\"units\": \"kcal / mol\", } ds.units = \"kcal/mol\" ds.set_default_benchmark(\"Benchmark\") ds.add_contributed_values(contrib) ds.save() # Test",
"# The new subset you want to add. dataset_name = \"ASCDB\" ds =",
"\"\"\", acs_citation=\"<NAME>. & <NAME>. Statistically representative databases for density functional theory via data",
"import FractalSnowflake import pandas as pd import argparse parser = argparse.ArgumentParser() parser.add_argument(\"-d\", \"--dry-run\",",
"subset. ds.save() # # Adding a contributed value based on the ASCDB csv",
"ptl.Molecule.from_file(gpath + \"/\" + mol_name + \".xyz\") coef = float(coef) rxn_data.append((mol, coef)) rxn",
"of the rxns list. rxn = row[2:] # This is used to handle",
"in zip(molecules, coefs): mol = ptl.Molecule.from_file(gpath + \"/\" + mol_name + \".xyz\") coef",
"= row[1] # Datapoint's reaction: from 2 to the end of the rxns",
"ds.save() # # Adding a contributed value based on the ASCDB csv file",
"# Datapoint's reaction: from 2 to the end of the rxns list. rxn",
"volume={21}, number={35}, pages={19092--19103}, year={2019}, publisher={Royal Society of Chemistry} } \"\"\", acs_citation=\"<NAME>. & <NAME>.",
"used to handle the list. half = len(rxn) // 2 molecules = rxn[:half]",
"= len(rxn) // 2 molecules = rxn[:half] coefs = rxn[half:] rxn_data = []",
"contrib_name.append(name) contrib_value.append(float(energy)) # Save the new subset. ds.save() # # Adding a contributed",
"Chemical Physics}, volume={21}, number={35}, pages={19092--19103}, year={2019}, publisher={Royal Society of Chemistry} } \"\"\", acs_citation=\"<NAME>.",
"{\"driver\": \"energy\"}, \"units\": \"kcal / mol\", } ds.units = \"kcal/mol\" ds.set_default_benchmark(\"Benchmark\") ds.add_contributed_values(contrib) ds.save()",
"mol_name + \".xyz\") coef = float(coef) rxn_data.append((mol, coef)) rxn = {\"default\": rxn_data} #",
"contrib_value, \"index\": contrib_name, \"theory_level_details\": {\"driver\": \"energy\"}, \"units\": \"kcal / mol\", } ds.units =",
"\"values\": contrib_value, \"index\": contrib_name, \"theory_level_details\": {\"driver\": \"energy\"}, \"units\": \"kcal / mol\", } ds.units",
"and the molecules # handled above. # contrib = { \"name\": \"Benchmark\", \"theory_level\":",
"qcfractal import FractalSnowflake import pandas as pd import argparse parser = argparse.ArgumentParser() parser.add_argument(\"-d\",",
"row in rxns: # Datapoint's name. name = row[0] # Datapoint's reference energy.",
"21</i>, 19092-19103.\", url=\"https://pubs.rsc.org/en/content/articlehtml/2019/cp/c9cp03211h\", doi=\"10.1039/C9CP03211H\", ) ] # The .csv file needed to build",
"new subset. ds.save() # # Adding a contributed value based on the ASCDB",
"databases for density functional theory via data science}, author={<NAME> and <NAME>}, journal={Physical Chemistry",
"March 2020. # import qcportal as ptl from qcfractal import FractalSnowflake import pandas",
"else: client = ptl.FractalClient.from_file() print(client) # The new subset you want to add.",
"snowflake.client() else: client = ptl.FractalClient.from_file() print(client) # The new subset you want to",
"rxn = {\"default\": rxn_data} # We add the reaction to the dataset. ds.add_rxn(name,",
"needed to build everything. filename = \"ASCDB.csv\" # We read the ASCDB.csv file.",
"and <NAME>}, journal={Physical Chemistry Chemical Physics}, volume={21}, number={35}, pages={19092--19103}, year={2019}, publisher={Royal Society of",
"file and the molecules # handled above. # contrib = { \"name\": \"Benchmark\",",
"coef = float(coef) rxn_data.append((mol, coef)) rxn = {\"default\": rxn_data} # We add the",
"to add. dataset_name = \"ASCDB\" ds = ptl.collections.ReactionDataset(dataset_name, client=client) # Add the paper",
"Physics}, volume={21}, number={35}, pages={19092--19103}, year={2019}, publisher={Royal Society of Chemistry} } \"\"\", acs_citation=\"<NAME>. &",
"CASPT2, Experiment (see ref)\", \"values\": contrib_value, \"index\": contrib_name, \"theory_level_details\": {\"driver\": \"energy\"}, \"units\": \"kcal",
"Datapoint's reaction: from 2 to the end of the rxns list. rxn =",
"args = parser.parse_args() SNOWFLAKE = args.dry_run if SNOWFLAKE: snowflake = FractalSnowflake() client =",
"FractalSnowflake() client = snowflake.client() else: client = ptl.FractalClient.from_file() print(client) # The new subset",
"if SNOWFLAKE: snowflake = FractalSnowflake() client = snowflake.client() else: client = ptl.FractalClient.from_file() print(client)",
"from 2 to the end of the rxns list. rxn = row[2:] #",
"the ASCDB.csv file. The encoding flag is optional, # but necessary if the",
"Add the paper ds.data.metadata[\"citations\"] = [ ptl.models.Citation( bibtex=\"\"\" @article{morgante2019statistically, title={Statistically representative databases for",
"density functional theory via data science. <em>Phys. Chem. Chem. Phys., </em><b>2019</b><i>, 21</i>, 19092-19103.\",",
"representative databases for density functional theory via data science. <em>Phys. Chem. Chem. Phys.,",
"client = ptl.FractalClient.from_file() print(client) # The new subset you want to add. dataset_name",
"#!/usr/bin/env Python # This line is needed only for unix-based systems. # Written",
"Save the new subset. ds.save() # # Adding a contributed value based on",
"loop handles the definition of a reaction, putting together molecules # and stoichiometric",
"row[1] # Datapoint's reaction: from 2 to the end of the rxns list.",
"# contrib = { \"name\": \"Benchmark\", \"theory_level\": \"CCSD(T), CASPT2, Experiment (see ref)\", \"values\":",
"We store the values to add in the \"Contributed value\" dictionary (see below).",
"# Datapoint's name. name = row[0] # Datapoint's reference energy. energy = row[1]",
"row[2:] # This is used to handle the list. half = len(rxn) //",
"the reaction to the dataset. ds.add_rxn(name, rxn) # We store the values to",
"= [] for row in rxns: # Datapoint's name. name = row[0] #",
"<em>Phys. Chem. Chem. Phys., </em><b>2019</b><i>, 21</i>, 19092-19103.\", url=\"https://pubs.rsc.org/en/content/articlehtml/2019/cp/c9cp03211h\", doi=\"10.1039/C9CP03211H\", ) ] # The",
"# import qcportal as ptl from qcfractal import FractalSnowflake import pandas as pd",
"The .csv file needed to build everything. filename = \"ASCDB.csv\" # We read",
"energy. energy = row[1] # Datapoint's reaction: from 2 to the end of",
"add. dataset_name = \"ASCDB\" ds = ptl.collections.ReactionDataset(dataset_name, client=client) # Add the paper ds.data.metadata[\"citations\"]",
"= snowflake.client() else: client = ptl.FractalClient.from_file() print(client) # The new subset you want",
"= row[0] # Datapoint's reference energy. energy = row[1] # Datapoint's reaction: from",
"name. name = row[0] # Datapoint's reference energy. energy = row[1] # Datapoint's",
"functional theory via data science}, author={<NAME> and <NAME>}, journal={Physical Chemistry Chemical Physics}, volume={21},",
"gpath = \"ACCDB/Geometries\" # We put names and reactions in the following lists:",
"We put names and reactions in the following lists: contrib_name = [] contrib_value",
"# for mol_name, coef in zip(molecules, coefs): mol = ptl.Molecule.from_file(gpath + \"/\" +",
"import qcportal as ptl from qcfractal import FractalSnowflake import pandas as pd import",
"rxn[half:] rxn_data = [] # This loop handles the definition of a reaction,",
") ] # The .csv file needed to build everything. filename = \"ASCDB.csv\"",
"# We put names and reactions in the following lists: contrib_name = []",
"data science. <em>Phys. Chem. Chem. Phys., </em><b>2019</b><i>, 21</i>, 19092-19103.\", url=\"https://pubs.rsc.org/en/content/articlehtml/2019/cp/c9cp03211h\", doi=\"10.1039/C9CP03211H\", ) ]",
"\"CCSD(T), CASPT2, Experiment (see ref)\", \"values\": contrib_value, \"index\": contrib_name, \"theory_level_details\": {\"driver\": \"energy\"}, \"units\":",
"+ \"/\" + mol_name + \".xyz\") coef = float(coef) rxn_data.append((mol, coef)) rxn =",
"= rxn[:half] coefs = rxn[half:] rxn_data = [] # This loop handles the",
"put names and reactions in the following lists: contrib_name = [] contrib_value =",
"doi=\"10.1039/C9CP03211H\", ) ] # The .csv file needed to build everything. filename =",
"as ptl from qcfractal import FractalSnowflake import pandas as pd import argparse parser",
"for x in handle.read().splitlines()] # Where to find the geometry files (in .xyz)",
"ptl from qcfractal import FractalSnowflake import pandas as pd import argparse parser =",
".csv file needed to build everything. filename = \"ASCDB.csv\" # We read the",
"import pandas as pd import argparse parser = argparse.ArgumentParser() parser.add_argument(\"-d\", \"--dry-run\", action=\"store_true\") args",
"<NAME>}, journal={Physical Chemistry Chemical Physics}, volume={21}, number={35}, pages={19092--19103}, year={2019}, publisher={Royal Society of Chemistry}",
"= \"ACCDB/Geometries\" # We put names and reactions in the following lists: contrib_name",
"rxn) # We store the values to add in the \"Contributed value\" dictionary",
"coefs = rxn[half:] rxn_data = [] # This loop handles the definition of",
"/ mol\", } ds.units = \"kcal/mol\" ds.set_default_benchmark(\"Benchmark\") ds.add_contributed_values(contrib) ds.save() # Test ds =",
"[] for row in rxns: # Datapoint's name. name = row[0] # Datapoint's",
"theory via data science. <em>Phys. Chem. Chem. Phys., </em><b>2019</b><i>, 21</i>, 19092-19103.\", url=\"https://pubs.rsc.org/en/content/articlehtml/2019/cp/c9cp03211h\", doi=\"10.1039/C9CP03211H\",",
"= parser.parse_args() SNOWFLAKE = args.dry_run if SNOWFLAKE: snowflake = FractalSnowflake() client = snowflake.client()",
"argparse.ArgumentParser() parser.add_argument(\"-d\", \"--dry-run\", action=\"store_true\") args = parser.parse_args() SNOWFLAKE = args.dry_run if SNOWFLAKE: snowflake",
"Chemistry Chemical Physics}, volume={21}, number={35}, pages={19092--19103}, year={2019}, publisher={Royal Society of Chemistry} } \"\"\",",
"= \"ASCDB\" ds = ptl.collections.ReactionDataset(dataset_name, client=client) # Add the paper ds.data.metadata[\"citations\"] = [",
"= \"ASCDB.csv\" # We read the ASCDB.csv file. The encoding flag is optional,",
"The new subset you want to add. dataset_name = \"ASCDB\" ds = ptl.collections.ReactionDataset(dataset_name,",
"list. half = len(rxn) // 2 molecules = rxn[:half] coefs = rxn[half:] rxn_data",
"Chem. Phys., </em><b>2019</b><i>, 21</i>, 19092-19103.\", url=\"https://pubs.rsc.org/en/content/articlehtml/2019/cp/c9cp03211h\", doi=\"10.1039/C9CP03211H\", ) ] # The .csv file",
"below). contrib_name.append(name) contrib_value.append(float(energy)) # Save the new subset. ds.save() # # Adding a",
"= [] contrib_value = [] for row in rxns: # Datapoint's name. name",
"necessary if the csv is generated (for example) with Microsoft Excel. # with",
"2 to the end of the rxns list. rxn = row[2:] # This",
"<NAME>. Statistically representative databases for density functional theory via data science. <em>Phys. Chem.",
"the \"Contributed value\" dictionary (see below). contrib_name.append(name) contrib_value.append(float(energy)) # Save the new subset.",
"a reaction, putting together molecules # and stoichiometric coefficients. # for mol_name, coef",
"contrib_value.append(float(energy)) # Save the new subset. ds.save() # # Adding a contributed value",
"putting together molecules # and stoichiometric coefficients. # for mol_name, coef in zip(molecules,",
"the definition of a reaction, putting together molecules # and stoichiometric coefficients. #",
"We add the reaction to the dataset. ds.add_rxn(name, rxn) # We store the",
"to find the geometry files (in .xyz) gpath = \"ACCDB/Geometries\" # We put",
"# The .csv file needed to build everything. filename = \"ASCDB.csv\" # We",
"molecules # handled above. # contrib = { \"name\": \"Benchmark\", \"theory_level\": \"CCSD(T), CASPT2,",
"mol\", } ds.units = \"kcal/mol\" ds.set_default_benchmark(\"Benchmark\") ds.add_contributed_values(contrib) ds.save() # Test ds = client.get_collection(\"ReactionDataset\",",
"[ ptl.models.Citation( bibtex=\"\"\" @article{morgante2019statistically, title={Statistically representative databases for density functional theory via data",
"density functional theory via data science}, author={<NAME> and <NAME>}, journal={Physical Chemistry Chemical Physics},",
"with Microsoft Excel. # with open(filename, \"r\", encoding=\"utf-8-sig\") as handle: rxns = [x.split(\",\")",
"Microsoft Excel. # with open(filename, \"r\", encoding=\"utf-8-sig\") as handle: rxns = [x.split(\",\") for",
"\"kcal/mol\" ds.set_default_benchmark(\"Benchmark\") ds.add_contributed_values(contrib) ds.save() # Test ds = client.get_collection(\"ReactionDataset\", dataset_name) print(ds.list_values()) ds._ensure_contributed_values() print(ds.get_values(native=False))",
"rxn[:half] coefs = rxn[half:] rxn_data = [] # This loop handles the definition",
"} ds.units = \"kcal/mol\" ds.set_default_benchmark(\"Benchmark\") ds.add_contributed_values(contrib) ds.save() # Test ds = client.get_collection(\"ReactionDataset\", dataset_name)",
"# This line is needed only for unix-based systems. # Written by <NAME>,",
"acs_citation=\"<NAME>. & <NAME>. Statistically representative databases for density functional theory via data science.",
"to handle the list. half = len(rxn) // 2 molecules = rxn[:half] coefs",
"dataset. ds.add_rxn(name, rxn) # We store the values to add in the \"Contributed",
"parser = argparse.ArgumentParser() parser.add_argument(\"-d\", \"--dry-run\", action=\"store_true\") args = parser.parse_args() SNOWFLAKE = args.dry_run if",
"dataset_name = \"ASCDB\" ds = ptl.collections.ReactionDataset(dataset_name, client=client) # Add the paper ds.data.metadata[\"citations\"] =",
"ds.units = \"kcal/mol\" ds.set_default_benchmark(\"Benchmark\") ds.add_contributed_values(contrib) ds.save() # Test ds = client.get_collection(\"ReactionDataset\", dataset_name) print(ds.list_values())",
"encoding flag is optional, # but necessary if the csv is generated (for",
"bibtex=\"\"\" @article{morgante2019statistically, title={Statistically representative databases for density functional theory via data science}, author={<NAME>",
"to build everything. filename = \"ASCDB.csv\" # We read the ASCDB.csv file. The",
"coefficients. # for mol_name, coef in zip(molecules, coefs): mol = ptl.Molecule.from_file(gpath + \"/\"",
"{ \"name\": \"Benchmark\", \"theory_level\": \"CCSD(T), CASPT2, Experiment (see ref)\", \"values\": contrib_value, \"index\": contrib_name,",
"Statistically representative databases for density functional theory via data science. <em>Phys. Chem. Chem.",
"rxn_data.append((mol, coef)) rxn = {\"default\": rxn_data} # We add the reaction to the",
"end of the rxns list. rxn = row[2:] # This is used to",
"ds = ptl.collections.ReactionDataset(dataset_name, client=client) # Add the paper ds.data.metadata[\"citations\"] = [ ptl.models.Citation( bibtex=\"\"\"",
"# Save the new subset. ds.save() # # Adding a contributed value based",
"pandas as pd import argparse parser = argparse.ArgumentParser() parser.add_argument(\"-d\", \"--dry-run\", action=\"store_true\") args =",
"\"theory_level\": \"CCSD(T), CASPT2, Experiment (see ref)\", \"values\": contrib_value, \"index\": contrib_name, \"theory_level_details\": {\"driver\": \"energy\"},",
"reaction: from 2 to the end of the rxns list. rxn = row[2:]",
"with open(filename, \"r\", encoding=\"utf-8-sig\") as handle: rxns = [x.split(\",\") for x in handle.read().splitlines()]",
"rxn_data = [] # This loop handles the definition of a reaction, putting",
"This is used to handle the list. half = len(rxn) // 2 molecules",
"# Datapoint's reference energy. energy = row[1] # Datapoint's reaction: from 2 to",
"\"/\" + mol_name + \".xyz\") coef = float(coef) rxn_data.append((mol, coef)) rxn = {\"default\":",
"a contributed value based on the ASCDB csv file and the molecules #",
"\"index\": contrib_name, \"theory_level_details\": {\"driver\": \"energy\"}, \"units\": \"kcal / mol\", } ds.units = \"kcal/mol\"",
"read the ASCDB.csv file. The encoding flag is optional, # but necessary if",
"\"kcal / mol\", } ds.units = \"kcal/mol\" ds.set_default_benchmark(\"Benchmark\") ds.add_contributed_values(contrib) ds.save() # Test ds",
"# with open(filename, \"r\", encoding=\"utf-8-sig\") as handle: rxns = [x.split(\",\") for x in",
"definition of a reaction, putting together molecules # and stoichiometric coefficients. # for",
"via data science. <em>Phys. Chem. Chem. Phys., </em><b>2019</b><i>, 21</i>, 19092-19103.\", url=\"https://pubs.rsc.org/en/content/articlehtml/2019/cp/c9cp03211h\", doi=\"10.1039/C9CP03211H\", )",
"argparse parser = argparse.ArgumentParser() parser.add_argument(\"-d\", \"--dry-run\", action=\"store_true\") args = parser.parse_args() SNOWFLAKE = args.dry_run",
"unix-based systems. # Written by <NAME>, <NAME>, <NAME>. # March 2020. # import",
"# # Adding a contributed value based on the ASCDB csv file and",
"(for example) with Microsoft Excel. # with open(filename, \"r\", encoding=\"utf-8-sig\") as handle: rxns",
"action=\"store_true\") args = parser.parse_args() SNOWFLAKE = args.dry_run if SNOWFLAKE: snowflake = FractalSnowflake() client",
"rxn = row[2:] # This is used to handle the list. half =",
"reference energy. energy = row[1] # Datapoint's reaction: from 2 to the end",
"systems. # Written by <NAME>, <NAME>, <NAME>. # March 2020. # import qcportal",
"encoding=\"utf-8-sig\") as handle: rxns = [x.split(\",\") for x in handle.read().splitlines()] # Where to",
"flag is optional, # but necessary if the csv is generated (for example)",
"Experiment (see ref)\", \"values\": contrib_value, \"index\": contrib_name, \"theory_level_details\": {\"driver\": \"energy\"}, \"units\": \"kcal /",
"] # The .csv file needed to build everything. filename = \"ASCDB.csv\" #",
"= row[2:] # This is used to handle the list. half = len(rxn)",
"Adding a contributed value based on the ASCDB csv file and the molecules",
"subset you want to add. dataset_name = \"ASCDB\" ds = ptl.collections.ReactionDataset(dataset_name, client=client) #",
"\"Contributed value\" dictionary (see below). contrib_name.append(name) contrib_value.append(float(energy)) # Save the new subset. ds.save()",
"the list. half = len(rxn) // 2 molecules = rxn[:half] coefs = rxn[half:]",
"the rxns list. rxn = row[2:] # This is used to handle the",
"# This loop handles the definition of a reaction, putting together molecules #",
"# We add the reaction to the dataset. ds.add_rxn(name, rxn) # We store",
"filename = \"ASCDB.csv\" # We read the ASCDB.csv file. The encoding flag is",
"\"ASCDB\" ds = ptl.collections.ReactionDataset(dataset_name, client=client) # Add the paper ds.data.metadata[\"citations\"] = [ ptl.models.Citation(",
"ds.set_default_benchmark(\"Benchmark\") ds.add_contributed_values(contrib) ds.save() # Test ds = client.get_collection(\"ReactionDataset\", dataset_name) print(ds.list_values()) ds._ensure_contributed_values() print(ds.get_values(native=False)) print(ds.data.metadata['citations'])",
"following lists: contrib_name = [] contrib_value = [] for row in rxns: #",
"for density functional theory via data science}, author={<NAME> and <NAME>}, journal={Physical Chemistry Chemical",
"Datapoint's reference energy. energy = row[1] # Datapoint's reaction: from 2 to the",
"# but necessary if the csv is generated (for example) with Microsoft Excel.",
"line is needed only for unix-based systems. # Written by <NAME>, <NAME>, <NAME>.",
"@article{morgante2019statistically, title={Statistically representative databases for density functional theory via data science}, author={<NAME> and",
"in handle.read().splitlines()] # Where to find the geometry files (in .xyz) gpath =",
"contributed value based on the ASCDB csv file and the molecules # handled",
"file needed to build everything. filename = \"ASCDB.csv\" # We read the ASCDB.csv",
"# This is used to handle the list. half = len(rxn) // 2",
"databases for density functional theory via data science. <em>Phys. Chem. Chem. Phys., </em><b>2019</b><i>,",
"for row in rxns: # Datapoint's name. name = row[0] # Datapoint's reference",
"but necessary if the csv is generated (for example) with Microsoft Excel. #",
"= {\"default\": rxn_data} # We add the reaction to the dataset. ds.add_rxn(name, rxn)",
"names and reactions in the following lists: contrib_name = [] contrib_value = []",
"for unix-based systems. # Written by <NAME>, <NAME>, <NAME>. # March 2020. #",
"client=client) # Add the paper ds.data.metadata[\"citations\"] = [ ptl.models.Citation( bibtex=\"\"\" @article{morgante2019statistically, title={Statistically representative",
"half = len(rxn) // 2 molecules = rxn[:half] coefs = rxn[half:] rxn_data =",
"if the csv is generated (for example) with Microsoft Excel. # with open(filename,",
"row[0] # Datapoint's reference energy. energy = row[1] # Datapoint's reaction: from 2",
"journal={Physical Chemistry Chemical Physics}, volume={21}, number={35}, pages={19092--19103}, year={2019}, publisher={Royal Society of Chemistry} }",
"This loop handles the definition of a reaction, putting together molecules # and",
"ASCDB.csv file. The encoding flag is optional, # but necessary if the csv",
"paper ds.data.metadata[\"citations\"] = [ ptl.models.Citation( bibtex=\"\"\" @article{morgante2019statistically, title={Statistically representative databases for density functional",
"via data science}, author={<NAME> and <NAME>}, journal={Physical Chemistry Chemical Physics}, volume={21}, number={35}, pages={19092--19103},",
"# and stoichiometric coefficients. # for mol_name, coef in zip(molecules, coefs): mol =",
"= [] # This loop handles the definition of a reaction, putting together",
"= argparse.ArgumentParser() parser.add_argument(\"-d\", \"--dry-run\", action=\"store_true\") args = parser.parse_args() SNOWFLAKE = args.dry_run if SNOWFLAKE:",
"coefs): mol = ptl.Molecule.from_file(gpath + \"/\" + mol_name + \".xyz\") coef = float(coef)",
"the end of the rxns list. rxn = row[2:] # This is used",
"client = snowflake.client() else: client = ptl.FractalClient.from_file() print(client) # The new subset you",
"functional theory via data science. <em>Phys. Chem. Chem. Phys., </em><b>2019</b><i>, 21</i>, 19092-19103.\", url=\"https://pubs.rsc.org/en/content/articlehtml/2019/cp/c9cp03211h\",",
"handle.read().splitlines()] # Where to find the geometry files (in .xyz) gpath = \"ACCDB/Geometries\"",
"name = row[0] # Datapoint's reference energy. energy = row[1] # Datapoint's reaction:",
"year={2019}, publisher={Royal Society of Chemistry} } \"\"\", acs_citation=\"<NAME>. & <NAME>. Statistically representative databases",
"+ mol_name + \".xyz\") coef = float(coef) rxn_data.append((mol, coef)) rxn = {\"default\": rxn_data}",
"// 2 molecules = rxn[:half] coefs = rxn[half:] rxn_data = [] # This",
"ASCDB csv file and the molecules # handled above. # contrib = {",
"the molecules # handled above. # contrib = { \"name\": \"Benchmark\", \"theory_level\": \"CCSD(T),",
"value based on the ASCDB csv file and the molecules # handled above.",
"This line is needed only for unix-based systems. # Written by <NAME>, <NAME>,",
"# Where to find the geometry files (in .xyz) gpath = \"ACCDB/Geometries\" #",
"the ASCDB csv file and the molecules # handled above. # contrib =",
"you want to add. dataset_name = \"ASCDB\" ds = ptl.collections.ReactionDataset(dataset_name, client=client) # Add",
"2020. # import qcportal as ptl from qcfractal import FractalSnowflake import pandas as",
"\"name\": \"Benchmark\", \"theory_level\": \"CCSD(T), CASPT2, Experiment (see ref)\", \"values\": contrib_value, \"index\": contrib_name, \"theory_level_details\":",
"coef in zip(molecules, coefs): mol = ptl.Molecule.from_file(gpath + \"/\" + mol_name + \".xyz\")",
"\"--dry-run\", action=\"store_true\") args = parser.parse_args() SNOWFLAKE = args.dry_run if SNOWFLAKE: snowflake = FractalSnowflake()",
"the dataset. ds.add_rxn(name, rxn) # We store the values to add in the",
"ds.add_rxn(name, rxn) # We store the values to add in the \"Contributed value\"",
"above. # contrib = { \"name\": \"Benchmark\", \"theory_level\": \"CCSD(T), CASPT2, Experiment (see ref)\",",
"2 molecules = rxn[:half] coefs = rxn[half:] rxn_data = [] # This loop",
"= \"kcal/mol\" ds.set_default_benchmark(\"Benchmark\") ds.add_contributed_values(contrib) ds.save() # Test ds = client.get_collection(\"ReactionDataset\", dataset_name) print(ds.list_values()) ds._ensure_contributed_values()",
"pages={19092--19103}, year={2019}, publisher={Royal Society of Chemistry} } \"\"\", acs_citation=\"<NAME>. & <NAME>. Statistically representative",
"needed only for unix-based systems. # Written by <NAME>, <NAME>, <NAME>. # March",
"(in .xyz) gpath = \"ACCDB/Geometries\" # We put names and reactions in the",
"and stoichiometric coefficients. # for mol_name, coef in zip(molecules, coefs): mol = ptl.Molecule.from_file(gpath",
"build everything. filename = \"ASCDB.csv\" # We read the ASCDB.csv file. The encoding",
"Excel. # with open(filename, \"r\", encoding=\"utf-8-sig\") as handle: rxns = [x.split(\",\") for x",
"} \"\"\", acs_citation=\"<NAME>. & <NAME>. Statistically representative databases for density functional theory via",
"the values to add in the \"Contributed value\" dictionary (see below). contrib_name.append(name) contrib_value.append(float(energy))",
"values to add in the \"Contributed value\" dictionary (see below). contrib_name.append(name) contrib_value.append(float(energy)) #",
"only for unix-based systems. # Written by <NAME>, <NAME>, <NAME>. # March 2020.",
"title={Statistically representative databases for density functional theory via data science}, author={<NAME> and <NAME>},",
"the csv is generated (for example) with Microsoft Excel. # with open(filename, \"r\",",
"csv file and the molecules # handled above. # contrib = { \"name\":",
"contrib_name = [] contrib_value = [] for row in rxns: # Datapoint's name.",
"is generated (for example) with Microsoft Excel. # with open(filename, \"r\", encoding=\"utf-8-sig\") as",
"generated (for example) with Microsoft Excel. # with open(filename, \"r\", encoding=\"utf-8-sig\") as handle:",
"list. rxn = row[2:] # This is used to handle the list. half",
"to add in the \"Contributed value\" dictionary (see below). contrib_name.append(name) contrib_value.append(float(energy)) # Save"
] |
[
"candidate) # In ModelFormMixin.form_valid, form.save() and its parent's form_valid will be called #",
"return color def has_permission_to_manage_resource(self, event): return self.request.user.has_perm(self.resource_approval_permission, event.resource) class ApproveRequestView(View, RequestApprovalMixin): model =",
"here candidate.save() response = super(AjaxableBookingRequestCreateView, self).form_valid(form) return response class RequestApprovalMixin(object): def is_request_can_be_approved(self, approval_request):",
"self.get_color(event) event = {\"id\": \"%d\" % event.pk, \"resourceId\": \"%d\" % event.resource.pk, \"start\": str(event.start),",
"response class ResourceApproverUpdater(object): create_resource_permission = 'change_bookableresource' def form_valid(self, form): candidate = form.save(commit=False) candidate.approver",
"self.has_permission_to_manage_resource(event) if event.is_canceled: color = self.COLOR_7_CANCELED elif event.is_completed: color = self.COLOR_6_COMPLETED elif event.is_ongoing:",
"import retrieve_param from guardian.shortcuts import assign_perm from resource_daily_scheduler.models import BookingRequest, get_timezone_aware_datetime_from_date_str class BookingRequestForm(forms.ModelForm):",
"AjaxableBookingRequestUpdateView(AjaxableResponseMixin, AjaxableFormContextUpdateMixin, RequestApprovalMixin, UpdateView): form_class = BookingRequestUpdateForm model = BookingRequest ajax_form_id = \"bookingReqEditForm\"",
"colors[attr_name.capitalize()] = (index, value) return colors class GetScheduleView(View, ColorSchema, RequestApprovalMixin): model = BookingRequest",
"self.request.user: color = self.COLOR_0_YOUR_REQUEST return color def has_permission_to_manage_resource(self, event): return self.request.user.has_perm(self.resource_approval_permission, event.resource) class",
"template_name = \"form_view_base_template.html\" submit_button_text = \"Update\" success_url = \"../\" def get_form_kwargs(self): \"\"\" Used",
"def form_valid(self, form): candidate = form.save(commit=False) if self.is_valid_approval(candidate): candidate.approver = self.request.user candidate.save() else:",
"in data) and (\"resourceId\" in data): kwargs[\"initial\"] = {\"start\": data[\"start\"], \"resource\": int(data[\"resourceId\"])} return",
"= form.save(commit=False) candidate.requester = self.request.user # use your own profile here candidate.save() response",
"candidate = form.save(commit=False) candidate.approver = self.request.user candidate.save() assign_perm(self.create_resource_permission, self.request.user, candidate) # In ModelFormMixin.form_valid,",
"= super(ResourceApproverUpdater, self).form_valid(form) return response class ColorSchema(object): COLOR_0_YOUR_REQUEST = \"tomato\" COLOR_1_WAITING_FOR_YOUR_APPROVAL = \"yellow\"",
"False for i in conflicts_filter: return False return True def is_valid_approval(self, approval_request): return",
"reservation :return: \"\"\" kwargs = super(AjaxableBookingRequestUpdateView, self).get_form_kwargs() kwargs.update({\"prefix\": \"update\"}) tz = pytz.timezone(\"Asia/Shanghai\") kwargs[\"instance\"].start",
"any(conflicts_filter): # return False for i in conflicts_filter: return False return True def",
"self.is_valid_approval(candidate): candidate.approver = self.request.user candidate.save() else: candidate.is_approved = False # In ModelFormMixin.form_valid, form.save()",
"\"blue\" COLOR_5_ONGOING = \"green\" # COLOR_CONFLICT = \"DarkGray\" # \"black\" COLOR_6_COMPLETED = \"aqua\"",
"getattr(ColorSchema, attr) index = int(attr[6]) attr_name = attr[8:] attr_name = attr_name.replace(\"_COMMA\", \",\") attr_name",
"success_url = \"../\" def get_form_kwargs(self): \"\"\" Used to update end date in UI,",
"def get(self, request, *args, **kwargs): data = retrieve_param(request) tz = pytz.timezone(\"Asia/Shanghai\") start =",
"color in [self.COLOR_1_WAITING_FOR_YOUR_APPROVAL, self.COLOR_5_ONGOING, self.COLOR_3_APPROVED_COMMA_YOU_CAN_CHANGE, self.COLOR_0_YOUR_REQUEST]: event[\"className\"] = \"todo\" res.append(event) return HttpResponse(json.dumps(res), content_type=\"application/json\")",
"has_perm: color = self.COLOR_3_APPROVED_COMMA_YOU_CAN_CHANGE else: color = self.COLOR_4_APPROVED_COMMA_YOU_CANNOT_CHANGE elif has_perm: if self.is_request_can_be_approved(event): color",
"is included in the reservation :return: \"\"\" kwargs = super(AjaxableBookingRequestCreateView, self).get_form_kwargs() # kwargs.update({\"prefix\":",
"\"Update\" success_url = \"../\" def get_form_kwargs(self): \"\"\" Used to update end date in",
"(\"start\" in data) and (\"resourceId\" in data): kwargs[\"initial\"] = {\"start\": data[\"start\"], \"resource\": int(data[\"resourceId\"])}",
"= attr_name.replace(\"_COMMA\", \",\") attr_name = attr_name.lower() attr_name = attr_name.replace(\"_\", \" \") colors[attr_name.capitalize()] =",
"\"is_canceled\"] class BookingRequestUpdateForm(BookingRequestForm): class Meta: model = BookingRequest exclude = [\"requester\", \"approver\"] class",
"= self.COLOR_7_CANCELED elif event.is_completed: color = self.COLOR_6_COMPLETED elif event.is_ongoing: # tz = pytz.timezone(\"Asia/Shanghai\")",
"candidate.is_approved = False # In ModelFormMixin.form_valid, form.save() and its parent's form_valid will be",
"AjaxableFormContextUpdateMixin from djangoautoconf.django_utils import retrieve_param from guardian.shortcuts import assign_perm from resource_daily_scheduler.models import BookingRequest,",
"'class': 'datepicker' })) end = forms.DateField( required=False, widget=forms.TextInput(attrs={ 'class': 'datepicker' })) class Meta:",
"from djangoautoconf.class_based_views.create_view_factory import AjaxableFormContextUpdateMixin from djangoautoconf.django_utils import retrieve_param from guardian.shortcuts import assign_perm from",
"self.COLOR_7_CANCELED elif event.is_completed: color = self.COLOR_6_COMPLETED elif event.is_ongoing: # tz = pytz.timezone(\"Asia/Shanghai\") #",
"GetScheduleView(View, ColorSchema, RequestApprovalMixin): model = BookingRequest resource_approval_permission = \"change_bookableresource\" def get(self, request, *args,",
"model = BookingRequest def get(self, request, *args, **kwargs): data = retrieve_param(request) req_id =",
"import CreateView, UpdateView import pytz from djangoautoconf.class_based_views.ajax_views import AjaxableResponseMixin from djangoautoconf.class_based_views.create_view_factory import AjaxableFormContextUpdateMixin",
"= super(AjaxableBookingRequestUpdateView, self).form_valid(form) return response class ResourceApproverUpdater(object): create_resource_permission = 'change_bookableresource' def form_valid(self, form):",
"= self.COLOR_5_ONGOING color = self.COLOR_5_ONGOING elif event.is_approved: if has_perm: color = self.COLOR_3_APPROVED_COMMA_YOU_CAN_CHANGE else:",
"\"false\" else: r.is_approved = True result = \"true\" r.save() return HttpResponse(json.dumps({\"result\": result}), content_type=\"application/json\")",
"colors = {} for attr in dir(ColorSchema): if attr != attr.upper(): continue if",
"approval_request): return (approval_request.approver is None) and approval_request.is_approved and \\ self.is_request_can_be_approved(approval_request) class AjaxableBookingRequestUpdateView(AjaxableResponseMixin, AjaxableFormContextUpdateMixin,",
"super(AjaxableBookingRequestUpdateView, self).get_form_kwargs() kwargs.update({\"prefix\": \"update\"}) tz = pytz.timezone(\"Asia/Shanghai\") kwargs[\"instance\"].start = kwargs[\"instance\"].start.astimezone(tz).strftime(\"%m/%d/%Y\") kwargs[\"instance\"].end = (kwargs[\"instance\"].end",
"\"aqua\" COLOR_7_CANCELED = \"grey\" def get_colors(self): colors = {} for attr in dir(ColorSchema):",
"= attr[8:] attr_name = attr_name.replace(\"_COMMA\", \",\") attr_name = attr_name.lower() attr_name = attr_name.replace(\"_\", \"",
"= self.request.user # use your own profile here candidate.save() response = super(AjaxableBookingRequestCreateView, self).form_valid(form)",
"event.end # if event.end < end_datetime.astimezone(tz): # color = self.COLOR_5_ONGOING color = self.COLOR_5_ONGOING",
"event.resource) class ApproveRequestView(View, RequestApprovalMixin): model = BookingRequest def get(self, request, *args, **kwargs): data",
"from resource_daily_scheduler.models import BookingRequest, get_timezone_aware_datetime_from_date_str class BookingRequestForm(forms.ModelForm): start = forms.DateField( required=False, widget=forms.TextInput(attrs={ 'class':",
"= BookingRequest def get(self, request, *args, **kwargs): data = retrieve_param(request) req_id = data[\"requestId\"]",
"pytz.timezone(\"Asia/Shanghai\") start = get_timezone_aware_datetime_from_date_str(data[\"start\"]) end = get_timezone_aware_datetime_from_date_str(data[\"end\"]) start_query = Q(end__lt=start) end_query = Q(start__gt=end)",
"start = get_timezone_aware_datetime_from_date_str(data[\"start\"]) end = get_timezone_aware_datetime_from_date_str(data[\"end\"]) start_query = Q(end__lt=start) end_query = Q(start__gt=end) res_query",
"import AjaxableResponseMixin from djangoautoconf.class_based_views.create_view_factory import AjaxableFormContextUpdateMixin from djangoautoconf.django_utils import retrieve_param from guardian.shortcuts import",
"# In ModelFormMixin.form_valid, form.save() and its parent's form_valid will be called # And",
"from django.db.models import Q from django.http import HttpResponse from django.views.generic.edit import CreateView, UpdateView",
"event in res_query: color = self.get_color(event) event = {\"id\": \"%d\" % event.pk, \"resourceId\":",
"self).get_form_kwargs() # kwargs.update({\"prefix\": \"update\"}) # tz = pytz.timezone(\"Asia/Shanghai\") # kwargs[\"instance\"].start = kwargs[\"instance\"].start.astimezone(tz).strftime(\"%m/%d/%Y\") #",
"'datepicker' })) end = forms.DateField( required=False, widget=forms.TextInput(attrs={ 'class': 'datepicker' })) class Meta: model",
"if any(conflicts_filter): # return False for i in conflicts_filter: return False return True",
"[\"is_approved\", \"requester\", \"approver\", \"is_ongoing\", \"is_completed\", \"is_canceled\"] class BookingRequestUpdateForm(BookingRequestForm): class Meta: model = BookingRequest",
"return (approval_request.approver is None) and approval_request.is_approved and \\ self.is_request_can_be_approved(approval_request) class AjaxableBookingRequestUpdateView(AjaxableResponseMixin, AjaxableFormContextUpdateMixin, RequestApprovalMixin,",
"class AjaxableBookingRequestUpdateView(AjaxableResponseMixin, AjaxableFormContextUpdateMixin, RequestApprovalMixin, UpdateView): form_class = BookingRequestUpdateForm model = BookingRequest ajax_form_id =",
"kwargs[\"instance\"].end = (kwargs[\"instance\"].end - datetime.timedelta( days=1)).astimezone(tz).strftime(\"%m/%d/%Y\") return kwargs def form_valid(self, form): candidate =",
"end_query = Q(start__gt=end) res_query = self.model.objects.filter(~(end_query | start_query)) res = [] for event",
"continue if attr[:6] != \"COLOR_\": continue value = getattr(ColorSchema, attr) index = int(attr[6])",
"end_datetime = event.end # if event.end < end_datetime.astimezone(tz): # color = self.COLOR_5_ONGOING color",
"in UI, as the end date in UI is included in the reservation",
"def has_permission_to_manage_resource(self, event): return self.request.user.has_perm(self.resource_approval_permission, event.resource) class ApproveRequestView(View, RequestApprovalMixin): model = BookingRequest def",
"False return True def is_valid_approval(self, approval_request): return (approval_request.approver is None) and approval_request.is_approved and",
"candidate.approver = self.request.user candidate.save() assign_perm(self.create_resource_permission, self.request.user, candidate) # In ModelFormMixin.form_valid, form.save() and its",
"class ColorSchema(object): COLOR_0_YOUR_REQUEST = \"tomato\" COLOR_1_WAITING_FOR_YOUR_APPROVAL = \"yellow\" COLOR_2_WAITING_FOR_APPROVAL_FROM_OTHERS = \"limegreen\" COLOR_3_APPROVED_COMMA_YOU_CAN_CHANGE =",
"class RequestApprovalMixin(object): def is_request_can_be_approved(self, approval_request): conflicts = self.model.objects.filter( start__lt=approval_request.end, end__gte=approval_request.start, resource=approval_request.resource, ) conflicts_filter",
"UpdateView import pytz from djangoautoconf.class_based_views.ajax_views import AjaxableResponseMixin from djangoautoconf.class_based_views.create_view_factory import AjaxableFormContextUpdateMixin from djangoautoconf.django_utils",
"to update end date in UI, as the end date in UI is",
"ColorSchema(object): COLOR_0_YOUR_REQUEST = \"tomato\" COLOR_1_WAITING_FOR_YOUR_APPROVAL = \"yellow\" COLOR_2_WAITING_FOR_APPROVAL_FROM_OTHERS = \"limegreen\" COLOR_3_APPROVED_COMMA_YOU_CAN_CHANGE = \"DeepPink\"",
"its parent's form_valid will be called # And in FormMixin (ModelFormMixin's parent) HttpResponseRedirect(self.get_success_url())",
"= event.end # if event.end < end_datetime.astimezone(tz): # color = self.COLOR_5_ONGOING color =",
"conflicts_filter = conflicts.filter(~Q(id=approval_request.pk) & (Q(is_approved=True) | Q(is_ongoing=True))) # if any(conflicts_filter): # return False",
"RequestApprovalMixin(object): def is_request_can_be_approved(self, approval_request): conflicts = self.model.objects.filter( start__lt=approval_request.end, end__gte=approval_request.start, resource=approval_request.resource, ) conflicts_filter =",
"# kwargs[\"instance\"].start = kwargs[\"instance\"].start.astimezone(tz).strftime(\"%m/%d/%Y\") # kwargs[\"instance\"].end = (kwargs[\"instance\"].end-datetime.timedelta( # days=1)).astimezone(tz).strftime(\"%m/%d/%Y\") data = retrieve_param(self.request)",
"if self.is_valid_approval(candidate): candidate.approver = self.request.user candidate.save() else: candidate.is_approved = False # In ModelFormMixin.form_valid,",
"your own profile here candidate.save() response = super(AjaxableBookingRequestCreateView, self).form_valid(form) return response class RequestApprovalMixin(object):",
"\"title\": event.project, \"color\": color} if color in [self.COLOR_1_WAITING_FOR_YOUR_APPROVAL, self.COLOR_5_ONGOING, self.COLOR_3_APPROVED_COMMA_YOU_CAN_CHANGE, self.COLOR_0_YOUR_REQUEST]: event[\"className\"] =",
"use your own profile here candidate.save() response = super(AjaxableBookingRequestCreateView, self).form_valid(form) return response class",
"= self.COLOR_6_COMPLETED elif event.is_ongoing: # tz = pytz.timezone(\"Asia/Shanghai\") # end_datetime = event.end #",
"content_type=\"application/json\") def get_color(self, event): color = self.COLOR_2_WAITING_FOR_APPROVAL_FROM_OTHERS has_perm = self.has_permission_to_manage_resource(event) if event.is_canceled: color",
"AjaxableBookingRequestCreateView(AjaxableResponseMixin, AjaxableFormContextUpdateMixin, CreateView): form_class = BookingRequestForm template_name = \"form_view_base_template.html\" submit_button_text = \"Create\" def",
"= \"Update\" success_url = \"../\" def get_form_kwargs(self): \"\"\" Used to update end date",
"self).form_valid(form) return response class ColorSchema(object): COLOR_0_YOUR_REQUEST = \"tomato\" COLOR_1_WAITING_FOR_YOUR_APPROVAL = \"yellow\" COLOR_2_WAITING_FOR_APPROVAL_FROM_OTHERS =",
"COLOR_6_COMPLETED = \"aqua\" COLOR_7_CANCELED = \"grey\" def get_colors(self): colors = {} for attr",
"get_form_kwargs(self): \"\"\" Used to update end date in UI, as the end date",
"continue value = getattr(ColorSchema, attr) index = int(attr[6]) attr_name = attr[8:] attr_name =",
"is_request_can_be_approved(self, approval_request): conflicts = self.model.objects.filter( start__lt=approval_request.end, end__gte=approval_request.start, resource=approval_request.resource, ) conflicts_filter = conflicts.filter(~Q(id=approval_request.pk) &",
"\"update\"}) tz = pytz.timezone(\"Asia/Shanghai\") kwargs[\"instance\"].start = kwargs[\"instance\"].start.astimezone(tz).strftime(\"%m/%d/%Y\") kwargs[\"instance\"].end = (kwargs[\"instance\"].end - datetime.timedelta( days=1)).astimezone(tz).strftime(\"%m/%d/%Y\")",
"in FormMixin (ModelFormMixin's parent) HttpResponseRedirect(self.get_success_url()) will be called response = super(AjaxableBookingRequestUpdateView, self).form_valid(form) return",
"forms.DateField( required=False, widget=forms.TextInput(attrs={ 'class': 'datepicker' })) class Meta: model = BookingRequest exclude =",
"return self.request.user.has_perm(self.resource_approval_permission, event.resource) class ApproveRequestView(View, RequestApprovalMixin): model = BookingRequest def get(self, request, *args,",
"import BookingRequest, get_timezone_aware_datetime_from_date_str class BookingRequestForm(forms.ModelForm): start = forms.DateField( required=False, widget=forms.TextInput(attrs={ 'class': 'datepicker' }))",
"response = super(AjaxableBookingRequestCreateView, self).form_valid(form) return response class RequestApprovalMixin(object): def is_request_can_be_approved(self, approval_request): conflicts =",
"from djangoautoconf.django_utils import retrieve_param from guardian.shortcuts import assign_perm from resource_daily_scheduler.models import BookingRequest, get_timezone_aware_datetime_from_date_str",
"= self.COLOR_2_WAITING_FOR_APPROVAL_FROM_OTHERS has_perm = self.has_permission_to_manage_resource(event) if event.is_canceled: color = self.COLOR_7_CANCELED elif event.is_completed: color",
"{\"start\": data[\"start\"], \"resource\": int(data[\"resourceId\"])} return kwargs def form_valid(self, form): candidate = form.save(commit=False) candidate.requester",
"self.COLOR_4_APPROVED_COMMA_YOU_CANNOT_CHANGE elif has_perm: if self.is_request_can_be_approved(event): color = self.COLOR_1_WAITING_FOR_YOUR_APPROVAL # else: # color =",
"import AjaxableFormContextUpdateMixin from djangoautoconf.django_utils import retrieve_param from guardian.shortcuts import assign_perm from resource_daily_scheduler.models import",
"BookingRequest ajax_form_id = \"bookingReqEditForm\" template_name = \"form_view_base_template.html\" submit_button_text = \"Update\" success_url = \"../\"",
"else: color = self.COLOR_4_APPROVED_COMMA_YOU_CANNOT_CHANGE elif has_perm: if self.is_request_can_be_approved(event): color = self.COLOR_1_WAITING_FOR_YOUR_APPROVAL # else:",
"# kwargs[\"instance\"].end = (kwargs[\"instance\"].end-datetime.timedelta( # days=1)).astimezone(tz).strftime(\"%m/%d/%Y\") data = retrieve_param(self.request) if (\"start\" in data)",
"self).form_valid(form) return response class ResourceApproverUpdater(object): create_resource_permission = 'change_bookableresource' def form_valid(self, form): candidate =",
"djangoautoconf.class_based_views.ajax_views import AjaxableResponseMixin from djangoautoconf.class_based_views.create_view_factory import AjaxableFormContextUpdateMixin from djangoautoconf.django_utils import retrieve_param from guardian.shortcuts",
"included in the reservation :return: \"\"\" kwargs = super(AjaxableBookingRequestCreateView, self).get_form_kwargs() # kwargs.update({\"prefix\": \"update\"})",
"int(data[\"resourceId\"])} return kwargs def form_valid(self, form): candidate = form.save(commit=False) candidate.requester = self.request.user #",
"And in FormMixin (ModelFormMixin's parent) HttpResponseRedirect(self.get_success_url()) will be called response = super(ResourceApproverUpdater, self).form_valid(form)",
"Meta: model = BookingRequest exclude = [\"requester\", \"approver\"] class AjaxableBookingRequestCreateView(AjaxableResponseMixin, AjaxableFormContextUpdateMixin, CreateView): form_class",
"super(AjaxableBookingRequestCreateView, self).form_valid(form) return response class RequestApprovalMixin(object): def is_request_can_be_approved(self, approval_request): conflicts = self.model.objects.filter( start__lt=approval_request.end,",
"conflicts.filter(~Q(id=approval_request.pk) & (Q(is_approved=True) | Q(is_ongoing=True))) # if any(conflicts_filter): # return False for i",
"in conflicts_filter: return False return True def is_valid_approval(self, approval_request): return (approval_request.approver is None)",
"event.requester == self.request.user: color = self.COLOR_0_YOUR_REQUEST return color def has_permission_to_manage_resource(self, event): return self.request.user.has_perm(self.resource_approval_permission,",
"in the reservation :return: \"\"\" kwargs = super(AjaxableBookingRequestCreateView, self).get_form_kwargs() # kwargs.update({\"prefix\": \"update\"}) #",
"create_resource_permission = 'change_bookableresource' def form_valid(self, form): candidate = form.save(commit=False) candidate.approver = self.request.user candidate.save()",
"widget=forms.TextInput(attrs={ 'class': 'datepicker' })) class Meta: model = BookingRequest exclude = [\"is_approved\", \"requester\",",
"date in UI is included in the reservation :return: \"\"\" kwargs = super(AjaxableBookingRequestUpdateView,",
"self.is_request_can_be_approved(approval_request) class AjaxableBookingRequestUpdateView(AjaxableResponseMixin, AjaxableFormContextUpdateMixin, RequestApprovalMixin, UpdateView): form_class = BookingRequestUpdateForm model = BookingRequest ajax_form_id",
"approval_request.is_approved and \\ self.is_request_can_be_approved(approval_request) class AjaxableBookingRequestUpdateView(AjaxableResponseMixin, AjaxableFormContextUpdateMixin, RequestApprovalMixin, UpdateView): form_class = BookingRequestUpdateForm model",
"(Q(is_approved=True) | Q(is_ongoing=True))) # if any(conflicts_filter): # return False for i in conflicts_filter:",
"data = retrieve_param(self.request) if (\"start\" in data) and (\"resourceId\" in data): kwargs[\"initial\"] =",
"(ModelFormMixin's parent) HttpResponseRedirect(self.get_success_url()) will be called response = super(AjaxableBookingRequestUpdateView, self).form_valid(form) return response class",
"BookingRequestForm template_name = \"form_view_base_template.html\" submit_button_text = \"Create\" def get_form_kwargs(self): \"\"\" Used to update",
"from compat import View import datetime from django import forms from django.db.models import",
"profile here candidate.save() response = super(AjaxableBookingRequestCreateView, self).form_valid(form) return response class RequestApprovalMixin(object): def is_request_can_be_approved(self,",
"= (index, value) return colors class GetScheduleView(View, ColorSchema, RequestApprovalMixin): model = BookingRequest resource_approval_permission",
"form_valid(self, form): candidate = form.save(commit=False) candidate.requester = self.request.user # use your own profile",
"\"approver\"] class AjaxableBookingRequestCreateView(AjaxableResponseMixin, AjaxableFormContextUpdateMixin, CreateView): form_class = BookingRequestForm template_name = \"form_view_base_template.html\" submit_button_text =",
"'class': 'datepicker' })) class Meta: model = BookingRequest exclude = [\"is_approved\", \"requester\", \"approver\",",
"= retrieve_param(request) req_id = data[\"requestId\"] r = self.model.objects.get(pk=int(req_id)) if r.is_approved: r.is_approved = False",
"candidate.save() response = super(AjaxableBookingRequestCreateView, self).form_valid(form) return response class RequestApprovalMixin(object): def is_request_can_be_approved(self, approval_request): conflicts",
"event.project, \"color\": color} if color in [self.COLOR_1_WAITING_FOR_YOUR_APPROVAL, self.COLOR_5_ONGOING, self.COLOR_3_APPROVED_COMMA_YOU_CAN_CHANGE, self.COLOR_0_YOUR_REQUEST]: event[\"className\"] = \"todo\"",
"django.db.models import Q from django.http import HttpResponse from django.views.generic.edit import CreateView, UpdateView import",
"= get_timezone_aware_datetime_from_date_str(data[\"start\"]) end = get_timezone_aware_datetime_from_date_str(data[\"end\"]) start_query = Q(end__lt=start) end_query = Q(start__gt=end) res_query =",
"and its parent's form_valid will be called # And in FormMixin (ModelFormMixin's parent)",
"from django.views.generic.edit import CreateView, UpdateView import pytz from djangoautoconf.class_based_views.ajax_views import AjaxableResponseMixin from djangoautoconf.class_based_views.create_view_factory",
"\"tomato\" COLOR_1_WAITING_FOR_YOUR_APPROVAL = \"yellow\" COLOR_2_WAITING_FOR_APPROVAL_FROM_OTHERS = \"limegreen\" COLOR_3_APPROVED_COMMA_YOU_CAN_CHANGE = \"DeepPink\" COLOR_4_APPROVED_COMMA_YOU_CANNOT_CHANGE = \"blue\"",
"\"green\" # COLOR_CONFLICT = \"DarkGray\" # \"black\" COLOR_6_COMPLETED = \"aqua\" COLOR_7_CANCELED = \"grey\"",
"from djangoautoconf.class_based_views.ajax_views import AjaxableResponseMixin from djangoautoconf.class_based_views.create_view_factory import AjaxableFormContextUpdateMixin from djangoautoconf.django_utils import retrieve_param from",
"ResourceApproverUpdater(object): create_resource_permission = 'change_bookableresource' def form_valid(self, form): candidate = form.save(commit=False) candidate.approver = self.request.user",
"COLOR_0_YOUR_REQUEST = \"tomato\" COLOR_1_WAITING_FOR_YOUR_APPROVAL = \"yellow\" COLOR_2_WAITING_FOR_APPROVAL_FROM_OTHERS = \"limegreen\" COLOR_3_APPROVED_COMMA_YOU_CAN_CHANGE = \"DeepPink\" COLOR_4_APPROVED_COMMA_YOU_CANNOT_CHANGE",
"import Q from django.http import HttpResponse from django.views.generic.edit import CreateView, UpdateView import pytz",
"\") colors[attr_name.capitalize()] = (index, value) return colors class GetScheduleView(View, ColorSchema, RequestApprovalMixin): model =",
"resource=approval_request.resource, ) conflicts_filter = conflicts.filter(~Q(id=approval_request.pk) & (Q(is_approved=True) | Q(is_ongoing=True))) # if any(conflicts_filter): #",
"CreateView): form_class = BookingRequestForm template_name = \"form_view_base_template.html\" submit_button_text = \"Create\" def get_form_kwargs(self): \"\"\"",
"BookingRequest resource_approval_permission = \"change_bookableresource\" def get(self, request, *args, **kwargs): data = retrieve_param(request) tz",
"days=1)).astimezone(tz).strftime(\"%m/%d/%Y\") data = retrieve_param(self.request) if (\"start\" in data) and (\"resourceId\" in data): kwargs[\"initial\"]",
"import datetime from django import forms from django.db.models import Q from django.http import",
"exclude = [\"requester\", \"approver\"] class AjaxableBookingRequestCreateView(AjaxableResponseMixin, AjaxableFormContextUpdateMixin, CreateView): form_class = BookingRequestForm template_name =",
"COLOR_7_CANCELED = \"grey\" def get_colors(self): colors = {} for attr in dir(ColorSchema): if",
"and (\"resourceId\" in data): kwargs[\"initial\"] = {\"start\": data[\"start\"], \"resource\": int(data[\"resourceId\"])} return kwargs def",
"AjaxableFormContextUpdateMixin, CreateView): form_class = BookingRequestForm template_name = \"form_view_base_template.html\" submit_button_text = \"Create\" def get_form_kwargs(self):",
"kwargs[\"instance\"].start = kwargs[\"instance\"].start.astimezone(tz).strftime(\"%m/%d/%Y\") # kwargs[\"instance\"].end = (kwargs[\"instance\"].end-datetime.timedelta( # days=1)).astimezone(tz).strftime(\"%m/%d/%Y\") data = retrieve_param(self.request) if",
"retrieve_param(request) tz = pytz.timezone(\"Asia/Shanghai\") start = get_timezone_aware_datetime_from_date_str(data[\"start\"]) end = get_timezone_aware_datetime_from_date_str(data[\"end\"]) start_query = Q(end__lt=start)",
"HttpResponse from django.views.generic.edit import CreateView, UpdateView import pytz from djangoautoconf.class_based_views.ajax_views import AjaxableResponseMixin from",
"class Meta: model = BookingRequest exclude = [\"is_approved\", \"requester\", \"approver\", \"is_ongoing\", \"is_completed\", \"is_canceled\"]",
"value) return colors class GetScheduleView(View, ColorSchema, RequestApprovalMixin): model = BookingRequest resource_approval_permission = \"change_bookableresource\"",
"COLOR_5_ONGOING = \"green\" # COLOR_CONFLICT = \"DarkGray\" # \"black\" COLOR_6_COMPLETED = \"aqua\" COLOR_7_CANCELED",
"attr_name.lower() attr_name = attr_name.replace(\"_\", \" \") colors[attr_name.capitalize()] = (index, value) return colors class",
"# COLOR_CONFLICT = \"DarkGray\" # \"black\" COLOR_6_COMPLETED = \"aqua\" COLOR_7_CANCELED = \"grey\" def",
"= forms.DateField( required=False, widget=forms.TextInput(attrs={ 'class': 'datepicker' })) end = forms.DateField( required=False, widget=forms.TextInput(attrs={ 'class':",
"= {\"id\": \"%d\" % event.pk, \"resourceId\": \"%d\" % event.resource.pk, \"start\": str(event.start), \"end\": str(event.end),",
"djangoautoconf.class_based_views.create_view_factory import AjaxableFormContextUpdateMixin from djangoautoconf.django_utils import retrieve_param from guardian.shortcuts import assign_perm from resource_daily_scheduler.models",
"# days=1)).astimezone(tz).strftime(\"%m/%d/%Y\") data = retrieve_param(self.request) if (\"start\" in data) and (\"resourceId\" in data):",
"kwargs[\"instance\"].start.astimezone(tz).strftime(\"%m/%d/%Y\") # kwargs[\"instance\"].end = (kwargs[\"instance\"].end-datetime.timedelta( # days=1)).astimezone(tz).strftime(\"%m/%d/%Y\") data = retrieve_param(self.request) if (\"start\" in",
"\"%d\" % event.resource.pk, \"start\": str(event.start), \"end\": str(event.end), \"title\": event.project, \"color\": color} if color",
"data = retrieve_param(request) tz = pytz.timezone(\"Asia/Shanghai\") start = get_timezone_aware_datetime_from_date_str(data[\"start\"]) end = get_timezone_aware_datetime_from_date_str(data[\"end\"]) start_query",
"index = int(attr[6]) attr_name = attr[8:] attr_name = attr_name.replace(\"_COMMA\", \",\") attr_name = attr_name.lower()",
"= conflicts.filter(~Q(id=approval_request.pk) & (Q(is_approved=True) | Q(is_ongoing=True))) # if any(conflicts_filter): # return False for",
"get_timezone_aware_datetime_from_date_str(data[\"start\"]) end = get_timezone_aware_datetime_from_date_str(data[\"end\"]) start_query = Q(end__lt=start) end_query = Q(start__gt=end) res_query = self.model.objects.filter(~(end_query",
"has_perm: if self.is_request_can_be_approved(event): color = self.COLOR_1_WAITING_FOR_YOUR_APPROVAL # else: # color = self.COLOR_CONFLICT elif",
"return False return True def is_valid_approval(self, approval_request): return (approval_request.approver is None) and approval_request.is_approved",
"tz = pytz.timezone(\"Asia/Shanghai\") # kwargs[\"instance\"].start = kwargs[\"instance\"].start.astimezone(tz).strftime(\"%m/%d/%Y\") # kwargs[\"instance\"].end = (kwargs[\"instance\"].end-datetime.timedelta( # days=1)).astimezone(tz).strftime(\"%m/%d/%Y\")",
"return response class ColorSchema(object): COLOR_0_YOUR_REQUEST = \"tomato\" COLOR_1_WAITING_FOR_YOUR_APPROVAL = \"yellow\" COLOR_2_WAITING_FOR_APPROVAL_FROM_OTHERS = \"limegreen\"",
"class Meta: model = BookingRequest exclude = [\"requester\", \"approver\"] class AjaxableBookingRequestCreateView(AjaxableResponseMixin, AjaxableFormContextUpdateMixin, CreateView):",
"UI, as the end date in UI is included in the reservation :return:",
"= \"blue\" COLOR_5_ONGOING = \"green\" # COLOR_CONFLICT = \"DarkGray\" # \"black\" COLOR_6_COMPLETED =",
"color = self.COLOR_6_COMPLETED elif event.is_ongoing: # tz = pytz.timezone(\"Asia/Shanghai\") # end_datetime = event.end",
"res_query = self.model.objects.filter(~(end_query | start_query)) res = [] for event in res_query: color",
"# if event.end < end_datetime.astimezone(tz): # color = self.COLOR_5_ONGOING color = self.COLOR_5_ONGOING elif",
"event.pk, \"resourceId\": \"%d\" % event.resource.pk, \"start\": str(event.start), \"end\": str(event.end), \"title\": event.project, \"color\": color}",
"self.request.user candidate.save() else: candidate.is_approved = False # In ModelFormMixin.form_valid, form.save() and its parent's",
"form_class = BookingRequestUpdateForm model = BookingRequest ajax_form_id = \"bookingReqEditForm\" template_name = \"form_view_base_template.html\" submit_button_text",
"import forms from django.db.models import Q from django.http import HttpResponse from django.views.generic.edit import",
"return colors class GetScheduleView(View, ColorSchema, RequestApprovalMixin): model = BookingRequest resource_approval_permission = \"change_bookableresource\" def",
"kwargs.update({\"prefix\": \"update\"}) # tz = pytz.timezone(\"Asia/Shanghai\") # kwargs[\"instance\"].start = kwargs[\"instance\"].start.astimezone(tz).strftime(\"%m/%d/%Y\") # kwargs[\"instance\"].end =",
"= \"DarkGray\" # \"black\" COLOR_6_COMPLETED = \"aqua\" COLOR_7_CANCELED = \"grey\" def get_colors(self): colors",
"be called response = super(ResourceApproverUpdater, self).form_valid(form) return response class ColorSchema(object): COLOR_0_YOUR_REQUEST = \"tomato\"",
"event.is_approved: if has_perm: color = self.COLOR_3_APPROVED_COMMA_YOU_CAN_CHANGE else: color = self.COLOR_4_APPROVED_COMMA_YOU_CANNOT_CHANGE elif has_perm: if",
"self).get_form_kwargs() kwargs.update({\"prefix\": \"update\"}) tz = pytz.timezone(\"Asia/Shanghai\") kwargs[\"instance\"].start = kwargs[\"instance\"].start.astimezone(tz).strftime(\"%m/%d/%Y\") kwargs[\"instance\"].end = (kwargs[\"instance\"].end -",
"\"bookingReqEditForm\" template_name = \"form_view_base_template.html\" submit_button_text = \"Update\" success_url = \"../\" def get_form_kwargs(self): \"\"\"",
"be called response = super(AjaxableBookingRequestUpdateView, self).form_valid(form) return response class ResourceApproverUpdater(object): create_resource_permission = 'change_bookableresource'",
"response class ColorSchema(object): COLOR_0_YOUR_REQUEST = \"tomato\" COLOR_1_WAITING_FOR_YOUR_APPROVAL = \"yellow\" COLOR_2_WAITING_FOR_APPROVAL_FROM_OTHERS = \"limegreen\" COLOR_3_APPROVED_COMMA_YOU_CAN_CHANGE",
"parent) HttpResponseRedirect(self.get_success_url()) will be called response = super(ResourceApproverUpdater, self).form_valid(form) return response class ColorSchema(object):",
"self.COLOR_0_YOUR_REQUEST return color def has_permission_to_manage_resource(self, event): return self.request.user.has_perm(self.resource_approval_permission, event.resource) class ApproveRequestView(View, RequestApprovalMixin): model",
"retrieve_param(self.request) if (\"start\" in data) and (\"resourceId\" in data): kwargs[\"initial\"] = {\"start\": data[\"start\"],",
"json from compat import View import datetime from django import forms from django.db.models",
"in UI is included in the reservation :return: \"\"\" kwargs = super(AjaxableBookingRequestUpdateView, self).get_form_kwargs()",
"form_valid will be called # And in FormMixin (ModelFormMixin's parent) HttpResponseRedirect(self.get_success_url()) will be",
"event.resource.pk, \"start\": str(event.start), \"end\": str(event.end), \"title\": event.project, \"color\": color} if color in [self.COLOR_1_WAITING_FOR_YOUR_APPROVAL,",
"class ResourceApproverUpdater(object): create_resource_permission = 'change_bookableresource' def form_valid(self, form): candidate = form.save(commit=False) candidate.approver =",
"= super(AjaxableBookingRequestCreateView, self).get_form_kwargs() # kwargs.update({\"prefix\": \"update\"}) # tz = pytz.timezone(\"Asia/Shanghai\") # kwargs[\"instance\"].start =",
"class AjaxableBookingRequestCreateView(AjaxableResponseMixin, AjaxableFormContextUpdateMixin, CreateView): form_class = BookingRequestForm template_name = \"form_view_base_template.html\" submit_button_text = \"Create\"",
"data = retrieve_param(request) req_id = data[\"requestId\"] r = self.model.objects.get(pk=int(req_id)) if r.is_approved: r.is_approved =",
"= self.request.user candidate.save() else: candidate.is_approved = False # In ModelFormMixin.form_valid, form.save() and its",
"\\ self.is_request_can_be_approved(approval_request) class AjaxableBookingRequestUpdateView(AjaxableResponseMixin, AjaxableFormContextUpdateMixin, RequestApprovalMixin, UpdateView): form_class = BookingRequestUpdateForm model = BookingRequest",
"def get(self, request, *args, **kwargs): data = retrieve_param(request) req_id = data[\"requestId\"] r =",
"BookingRequestForm(forms.ModelForm): start = forms.DateField( required=False, widget=forms.TextInput(attrs={ 'class': 'datepicker' })) end = forms.DateField( required=False,",
"conflicts_filter: return False return True def is_valid_approval(self, approval_request): return (approval_request.approver is None) and",
"# tz = pytz.timezone(\"Asia/Shanghai\") # end_datetime = event.end # if event.end < end_datetime.astimezone(tz):",
"= \"form_view_base_template.html\" submit_button_text = \"Create\" def get_form_kwargs(self): \"\"\" Used to update end date",
"date in UI is included in the reservation :return: \"\"\" kwargs = super(AjaxableBookingRequestCreateView,",
"\"todo\" res.append(event) return HttpResponse(json.dumps(res), content_type=\"application/json\") def get_color(self, event): color = self.COLOR_2_WAITING_FOR_APPROVAL_FROM_OTHERS has_perm =",
"approval_request): conflicts = self.model.objects.filter( start__lt=approval_request.end, end__gte=approval_request.start, resource=approval_request.resource, ) conflicts_filter = conflicts.filter(~Q(id=approval_request.pk) & (Q(is_approved=True)",
"BookingRequestUpdateForm(BookingRequestForm): class Meta: model = BookingRequest exclude = [\"requester\", \"approver\"] class AjaxableBookingRequestCreateView(AjaxableResponseMixin, AjaxableFormContextUpdateMixin,",
"= self.COLOR_4_APPROVED_COMMA_YOU_CANNOT_CHANGE elif has_perm: if self.is_request_can_be_approved(event): color = self.COLOR_1_WAITING_FOR_YOUR_APPROVAL # else: # color",
"\"form_view_base_template.html\" submit_button_text = \"Create\" def get_form_kwargs(self): \"\"\" Used to update end date in",
"if attr[:6] != \"COLOR_\": continue value = getattr(ColorSchema, attr) index = int(attr[6]) attr_name",
"attr.upper(): continue if attr[:6] != \"COLOR_\": continue value = getattr(ColorSchema, attr) index =",
"attr_name = attr_name.lower() attr_name = attr_name.replace(\"_\", \" \") colors[attr_name.capitalize()] = (index, value) return",
"% event.pk, \"resourceId\": \"%d\" % event.resource.pk, \"start\": str(event.start), \"end\": str(event.end), \"title\": event.project, \"color\":",
"= form.save(commit=False) candidate.approver = self.request.user candidate.save() assign_perm(self.create_resource_permission, self.request.user, candidate) # In ModelFormMixin.form_valid, form.save()",
"candidate.save() assign_perm(self.create_resource_permission, self.request.user, candidate) # In ModelFormMixin.form_valid, form.save() and its parent's form_valid will",
"# And in FormMixin (ModelFormMixin's parent) HttpResponseRedirect(self.get_success_url()) will be called response = super(AjaxableBookingRequestUpdateView,",
"= self.COLOR_0_YOUR_REQUEST return color def has_permission_to_manage_resource(self, event): return self.request.user.has_perm(self.resource_approval_permission, event.resource) class ApproveRequestView(View, RequestApprovalMixin):",
"= BookingRequestForm template_name = \"form_view_base_template.html\" submit_button_text = \"Create\" def get_form_kwargs(self): \"\"\" Used to",
"color = self.COLOR_5_ONGOING elif event.is_approved: if has_perm: color = self.COLOR_3_APPROVED_COMMA_YOU_CAN_CHANGE else: color =",
"None) and approval_request.is_approved and \\ self.is_request_can_be_approved(approval_request) class AjaxableBookingRequestUpdateView(AjaxableResponseMixin, AjaxableFormContextUpdateMixin, RequestApprovalMixin, UpdateView): form_class =",
"for attr in dir(ColorSchema): if attr != attr.upper(): continue if attr[:6] != \"COLOR_\":",
"data[\"start\"], \"resource\": int(data[\"resourceId\"])} return kwargs def form_valid(self, form): candidate = form.save(commit=False) candidate.requester =",
"compat import View import datetime from django import forms from django.db.models import Q",
"**kwargs): data = retrieve_param(request) req_id = data[\"requestId\"] r = self.model.objects.get(pk=int(req_id)) if r.is_approved: r.is_approved",
"required=False, widget=forms.TextInput(attrs={ 'class': 'datepicker' })) end = forms.DateField( required=False, widget=forms.TextInput(attrs={ 'class': 'datepicker' }))",
"kwargs def form_valid(self, form): candidate = form.save(commit=False) if self.is_valid_approval(candidate): candidate.approver = self.request.user candidate.save()",
"'change_bookableresource' def form_valid(self, form): candidate = form.save(commit=False) candidate.approver = self.request.user candidate.save() assign_perm(self.create_resource_permission, self.request.user,",
"own profile here candidate.save() response = super(AjaxableBookingRequestCreateView, self).form_valid(form) return response class RequestApprovalMixin(object): def",
"})) class Meta: model = BookingRequest exclude = [\"is_approved\", \"requester\", \"approver\", \"is_ongoing\", \"is_completed\",",
"def is_valid_approval(self, approval_request): return (approval_request.approver is None) and approval_request.is_approved and \\ self.is_request_can_be_approved(approval_request) class",
"!= \"COLOR_\": continue value = getattr(ColorSchema, attr) index = int(attr[6]) attr_name = attr[8:]",
"model = BookingRequest resource_approval_permission = \"change_bookableresource\" def get(self, request, *args, **kwargs): data =",
"and approval_request.is_approved and \\ self.is_request_can_be_approved(approval_request) class AjaxableBookingRequestUpdateView(AjaxableResponseMixin, AjaxableFormContextUpdateMixin, RequestApprovalMixin, UpdateView): form_class = BookingRequestUpdateForm",
"will be called # And in FormMixin (ModelFormMixin's parent) HttpResponseRedirect(self.get_success_url()) will be called",
"BookingRequest exclude = [\"is_approved\", \"requester\", \"approver\", \"is_ongoing\", \"is_completed\", \"is_canceled\"] class BookingRequestUpdateForm(BookingRequestForm): class Meta:",
"if (\"start\" in data) and (\"resourceId\" in data): kwargs[\"initial\"] = {\"start\": data[\"start\"], \"resource\":",
"form): candidate = form.save(commit=False) candidate.requester = self.request.user # use your own profile here",
"is None) and approval_request.is_approved and \\ self.is_request_can_be_approved(approval_request) class AjaxableBookingRequestUpdateView(AjaxableResponseMixin, AjaxableFormContextUpdateMixin, RequestApprovalMixin, UpdateView): form_class",
"super(AjaxableBookingRequestCreateView, self).get_form_kwargs() # kwargs.update({\"prefix\": \"update\"}) # tz = pytz.timezone(\"Asia/Shanghai\") # kwargs[\"instance\"].start = kwargs[\"instance\"].start.astimezone(tz).strftime(\"%m/%d/%Y\")",
":return: \"\"\" kwargs = super(AjaxableBookingRequestUpdateView, self).get_form_kwargs() kwargs.update({\"prefix\": \"update\"}) tz = pytz.timezone(\"Asia/Shanghai\") kwargs[\"instance\"].start =",
"- datetime.timedelta( days=1)).astimezone(tz).strftime(\"%m/%d/%Y\") return kwargs def form_valid(self, form): candidate = form.save(commit=False) if self.is_valid_approval(candidate):",
"from guardian.shortcuts import assign_perm from resource_daily_scheduler.models import BookingRequest, get_timezone_aware_datetime_from_date_str class BookingRequestForm(forms.ModelForm): start =",
"end_datetime.astimezone(tz): # color = self.COLOR_5_ONGOING color = self.COLOR_5_ONGOING elif event.is_approved: if has_perm: color",
"get(self, request, *args, **kwargs): data = retrieve_param(request) req_id = data[\"requestId\"] r = self.model.objects.get(pk=int(req_id))",
"form_valid(self, form): candidate = form.save(commit=False) if self.is_valid_approval(candidate): candidate.approver = self.request.user candidate.save() else: candidate.is_approved",
"data[\"requestId\"] r = self.model.objects.get(pk=int(req_id)) if r.is_approved: r.is_approved = False result = \"false\" else:",
"kwargs[\"instance\"].start.astimezone(tz).strftime(\"%m/%d/%Y\") kwargs[\"instance\"].end = (kwargs[\"instance\"].end - datetime.timedelta( days=1)).astimezone(tz).strftime(\"%m/%d/%Y\") return kwargs def form_valid(self, form): candidate",
"model = BookingRequest ajax_form_id = \"bookingReqEditForm\" template_name = \"form_view_base_template.html\" submit_button_text = \"Update\" success_url",
"= retrieve_param(request) tz = pytz.timezone(\"Asia/Shanghai\") start = get_timezone_aware_datetime_from_date_str(data[\"start\"]) end = get_timezone_aware_datetime_from_date_str(data[\"end\"]) start_query =",
"BookingRequestUpdateForm model = BookingRequest ajax_form_id = \"bookingReqEditForm\" template_name = \"form_view_base_template.html\" submit_button_text = \"Update\"",
"self.COLOR_3_APPROVED_COMMA_YOU_CAN_CHANGE, self.COLOR_0_YOUR_REQUEST]: event[\"className\"] = \"todo\" res.append(event) return HttpResponse(json.dumps(res), content_type=\"application/json\") def get_color(self, event): color",
"int(attr[6]) attr_name = attr[8:] attr_name = attr_name.replace(\"_COMMA\", \",\") attr_name = attr_name.lower() attr_name =",
"self).form_valid(form) return response class RequestApprovalMixin(object): def is_request_can_be_approved(self, approval_request): conflicts = self.model.objects.filter( start__lt=approval_request.end, end__gte=approval_request.start,",
"return response class ResourceApproverUpdater(object): create_resource_permission = 'change_bookableresource' def form_valid(self, form): candidate = form.save(commit=False)",
"= Q(start__gt=end) res_query = self.model.objects.filter(~(end_query | start_query)) res = [] for event in",
"import json from compat import View import datetime from django import forms from",
"will be called response = super(ResourceApproverUpdater, self).form_valid(form) return response class ColorSchema(object): COLOR_0_YOUR_REQUEST =",
"event = {\"id\": \"%d\" % event.pk, \"resourceId\": \"%d\" % event.resource.pk, \"start\": str(event.start), \"end\":",
"= {} for attr in dir(ColorSchema): if attr != attr.upper(): continue if attr[:6]",
"as the end date in UI is included in the reservation :return: \"\"\"",
"= super(AjaxableBookingRequestUpdateView, self).get_form_kwargs() kwargs.update({\"prefix\": \"update\"}) tz = pytz.timezone(\"Asia/Shanghai\") kwargs[\"instance\"].start = kwargs[\"instance\"].start.astimezone(tz).strftime(\"%m/%d/%Y\") kwargs[\"instance\"].end =",
"end = get_timezone_aware_datetime_from_date_str(data[\"end\"]) start_query = Q(end__lt=start) end_query = Q(start__gt=end) res_query = self.model.objects.filter(~(end_query |",
"\"limegreen\" COLOR_3_APPROVED_COMMA_YOU_CAN_CHANGE = \"DeepPink\" COLOR_4_APPROVED_COMMA_YOU_CANNOT_CHANGE = \"blue\" COLOR_5_ONGOING = \"green\" # COLOR_CONFLICT =",
"= 'change_bookableresource' def form_valid(self, form): candidate = form.save(commit=False) candidate.approver = self.request.user candidate.save() assign_perm(self.create_resource_permission,",
"\"DeepPink\" COLOR_4_APPROVED_COMMA_YOU_CANNOT_CHANGE = \"blue\" COLOR_5_ONGOING = \"green\" # COLOR_CONFLICT = \"DarkGray\" # \"black\"",
") conflicts_filter = conflicts.filter(~Q(id=approval_request.pk) & (Q(is_approved=True) | Q(is_ongoing=True))) # if any(conflicts_filter): # return",
"retrieve_param from guardian.shortcuts import assign_perm from resource_daily_scheduler.models import BookingRequest, get_timezone_aware_datetime_from_date_str class BookingRequestForm(forms.ModelForm): start",
"color def has_permission_to_manage_resource(self, event): return self.request.user.has_perm(self.resource_approval_permission, event.resource) class ApproveRequestView(View, RequestApprovalMixin): model = BookingRequest",
"import HttpResponse from django.views.generic.edit import CreateView, UpdateView import pytz from djangoautoconf.class_based_views.ajax_views import AjaxableResponseMixin",
"FormMixin (ModelFormMixin's parent) HttpResponseRedirect(self.get_success_url()) will be called response = super(ResourceApproverUpdater, self).form_valid(form) return response",
"event.is_canceled: color = self.COLOR_7_CANCELED elif event.is_completed: color = self.COLOR_6_COMPLETED elif event.is_ongoing: # tz",
"self.COLOR_5_ONGOING color = self.COLOR_5_ONGOING elif event.is_approved: if has_perm: color = self.COLOR_3_APPROVED_COMMA_YOU_CAN_CHANGE else: color",
"event.end < end_datetime.astimezone(tz): # color = self.COLOR_5_ONGOING color = self.COLOR_5_ONGOING elif event.is_approved: if",
"= self.COLOR_CONFLICT elif event.requester == self.request.user: color = self.COLOR_0_YOUR_REQUEST return color def has_permission_to_manage_resource(self,",
"\"%d\" % event.pk, \"resourceId\": \"%d\" % event.resource.pk, \"start\": str(event.start), \"end\": str(event.end), \"title\": event.project,",
"(kwargs[\"instance\"].end-datetime.timedelta( # days=1)).astimezone(tz).strftime(\"%m/%d/%Y\") data = retrieve_param(self.request) if (\"start\" in data) and (\"resourceId\" in",
"return response class RequestApprovalMixin(object): def is_request_can_be_approved(self, approval_request): conflicts = self.model.objects.filter( start__lt=approval_request.end, end__gte=approval_request.start, resource=approval_request.resource,",
"template_name = \"form_view_base_template.html\" submit_button_text = \"Create\" def get_form_kwargs(self): \"\"\" Used to update end",
"pytz.timezone(\"Asia/Shanghai\") # end_datetime = event.end # if event.end < end_datetime.astimezone(tz): # color =",
"r.is_approved = False result = \"false\" else: r.is_approved = True result = \"true\"",
"def is_request_can_be_approved(self, approval_request): conflicts = self.model.objects.filter( start__lt=approval_request.end, end__gte=approval_request.start, resource=approval_request.resource, ) conflicts_filter = conflicts.filter(~Q(id=approval_request.pk)",
"else: # color = self.COLOR_CONFLICT elif event.requester == self.request.user: color = self.COLOR_0_YOUR_REQUEST return",
"= \"change_bookableresource\" def get(self, request, *args, **kwargs): data = retrieve_param(request) tz = pytz.timezone(\"Asia/Shanghai\")",
"super(ResourceApproverUpdater, self).form_valid(form) return response class ColorSchema(object): COLOR_0_YOUR_REQUEST = \"tomato\" COLOR_1_WAITING_FOR_YOUR_APPROVAL = \"yellow\" COLOR_2_WAITING_FOR_APPROVAL_FROM_OTHERS",
"self.COLOR_5_ONGOING, self.COLOR_3_APPROVED_COMMA_YOU_CAN_CHANGE, self.COLOR_0_YOUR_REQUEST]: event[\"className\"] = \"todo\" res.append(event) return HttpResponse(json.dumps(res), content_type=\"application/json\") def get_color(self, event):",
"= \"aqua\" COLOR_7_CANCELED = \"grey\" def get_colors(self): colors = {} for attr in",
"get(self, request, *args, **kwargs): data = retrieve_param(request) tz = pytz.timezone(\"Asia/Shanghai\") start = get_timezone_aware_datetime_from_date_str(data[\"start\"])",
"attr != attr.upper(): continue if attr[:6] != \"COLOR_\": continue value = getattr(ColorSchema, attr)",
"RequestApprovalMixin): model = BookingRequest def get(self, request, *args, **kwargs): data = retrieve_param(request) req_id",
"self.model.objects.filter( start__lt=approval_request.end, end__gte=approval_request.start, resource=approval_request.resource, ) conflicts_filter = conflicts.filter(~Q(id=approval_request.pk) & (Q(is_approved=True) | Q(is_ongoing=True))) #",
"import View import datetime from django import forms from django.db.models import Q from",
"class BookingRequestUpdateForm(BookingRequestForm): class Meta: model = BookingRequest exclude = [\"requester\", \"approver\"] class AjaxableBookingRequestCreateView(AjaxableResponseMixin,",
"start_query = Q(end__lt=start) end_query = Q(start__gt=end) res_query = self.model.objects.filter(~(end_query | start_query)) res =",
"self.COLOR_CONFLICT elif event.requester == self.request.user: color = self.COLOR_0_YOUR_REQUEST return color def has_permission_to_manage_resource(self, event):",
"(ModelFormMixin's parent) HttpResponseRedirect(self.get_success_url()) will be called response = super(ResourceApproverUpdater, self).form_valid(form) return response class",
"% event.resource.pk, \"start\": str(event.start), \"end\": str(event.end), \"title\": event.project, \"color\": color} if color in",
"UI is included in the reservation :return: \"\"\" kwargs = super(AjaxableBookingRequestCreateView, self).get_form_kwargs() #",
"parent) HttpResponseRedirect(self.get_success_url()) will be called response = super(AjaxableBookingRequestUpdateView, self).form_valid(form) return response class ResourceApproverUpdater(object):",
"attr in dir(ColorSchema): if attr != attr.upper(): continue if attr[:6] != \"COLOR_\": continue",
"attr) index = int(attr[6]) attr_name = attr[8:] attr_name = attr_name.replace(\"_COMMA\", \",\") attr_name =",
"color = self.COLOR_2_WAITING_FOR_APPROVAL_FROM_OTHERS has_perm = self.has_permission_to_manage_resource(event) if event.is_canceled: color = self.COLOR_7_CANCELED elif event.is_completed:",
"def get_color(self, event): color = self.COLOR_2_WAITING_FOR_APPROVAL_FROM_OTHERS has_perm = self.has_permission_to_manage_resource(event) if event.is_canceled: color =",
"for i in conflicts_filter: return False return True def is_valid_approval(self, approval_request): return (approval_request.approver",
"end = forms.DateField( required=False, widget=forms.TextInput(attrs={ 'class': 'datepicker' })) class Meta: model = BookingRequest",
"View import datetime from django import forms from django.db.models import Q from django.http",
"= self.get_color(event) event = {\"id\": \"%d\" % event.pk, \"resourceId\": \"%d\" % event.resource.pk, \"start\":",
"= self.model.objects.filter(~(end_query | start_query)) res = [] for event in res_query: color =",
"= pytz.timezone(\"Asia/Shanghai\") kwargs[\"instance\"].start = kwargs[\"instance\"].start.astimezone(tz).strftime(\"%m/%d/%Y\") kwargs[\"instance\"].end = (kwargs[\"instance\"].end - datetime.timedelta( days=1)).astimezone(tz).strftime(\"%m/%d/%Y\") return kwargs",
"assign_perm(self.create_resource_permission, self.request.user, candidate) # In ModelFormMixin.form_valid, form.save() and its parent's form_valid will be",
"| start_query)) res = [] for event in res_query: color = self.get_color(event) event",
"\"change_bookableresource\" def get(self, request, *args, **kwargs): data = retrieve_param(request) tz = pytz.timezone(\"Asia/Shanghai\") start",
"return kwargs def form_valid(self, form): candidate = form.save(commit=False) candidate.requester = self.request.user # use",
"be called # And in FormMixin (ModelFormMixin's parent) HttpResponseRedirect(self.get_success_url()) will be called response",
"= \"limegreen\" COLOR_3_APPROVED_COMMA_YOU_CAN_CHANGE = \"DeepPink\" COLOR_4_APPROVED_COMMA_YOU_CANNOT_CHANGE = \"blue\" COLOR_5_ONGOING = \"green\" # COLOR_CONFLICT",
"color = self.COLOR_4_APPROVED_COMMA_YOU_CANNOT_CHANGE elif has_perm: if self.is_request_can_be_approved(event): color = self.COLOR_1_WAITING_FOR_YOUR_APPROVAL # else: #",
"# if any(conflicts_filter): # return False for i in conflicts_filter: return False return",
"= retrieve_param(self.request) if (\"start\" in data) and (\"resourceId\" in data): kwargs[\"initial\"] = {\"start\":",
"required=False, widget=forms.TextInput(attrs={ 'class': 'datepicker' })) class Meta: model = BookingRequest exclude = [\"is_approved\",",
"\"../\" def get_form_kwargs(self): \"\"\" Used to update end date in UI, as the",
"self.request.user # use your own profile here candidate.save() response = super(AjaxableBookingRequestCreateView, self).form_valid(form) return",
"\"Create\" def get_form_kwargs(self): \"\"\" Used to update end date in UI, as the",
"& (Q(is_approved=True) | Q(is_ongoing=True))) # if any(conflicts_filter): # return False for i in",
"for event in res_query: color = self.get_color(event) event = {\"id\": \"%d\" % event.pk,",
"= \"todo\" res.append(event) return HttpResponse(json.dumps(res), content_type=\"application/json\") def get_color(self, event): color = self.COLOR_2_WAITING_FOR_APPROVAL_FROM_OTHERS has_perm",
"return HttpResponse(json.dumps(res), content_type=\"application/json\") def get_color(self, event): color = self.COLOR_2_WAITING_FOR_APPROVAL_FROM_OTHERS has_perm = self.has_permission_to_manage_resource(event) if",
"= self.has_permission_to_manage_resource(event) if event.is_canceled: color = self.COLOR_7_CANCELED elif event.is_completed: color = self.COLOR_6_COMPLETED elif",
"return True def is_valid_approval(self, approval_request): return (approval_request.approver is None) and approval_request.is_approved and \\",
"get_timezone_aware_datetime_from_date_str(data[\"end\"]) start_query = Q(end__lt=start) end_query = Q(start__gt=end) res_query = self.model.objects.filter(~(end_query | start_query)) res",
"= \"tomato\" COLOR_1_WAITING_FOR_YOUR_APPROVAL = \"yellow\" COLOR_2_WAITING_FOR_APPROVAL_FROM_OTHERS = \"limegreen\" COLOR_3_APPROVED_COMMA_YOU_CAN_CHANGE = \"DeepPink\" COLOR_4_APPROVED_COMMA_YOU_CANNOT_CHANGE =",
"exclude = [\"is_approved\", \"requester\", \"approver\", \"is_ongoing\", \"is_completed\", \"is_canceled\"] class BookingRequestUpdateForm(BookingRequestForm): class Meta: model",
"r = self.model.objects.get(pk=int(req_id)) if r.is_approved: r.is_approved = False result = \"false\" else: r.is_approved",
"= \"green\" # COLOR_CONFLICT = \"DarkGray\" # \"black\" COLOR_6_COMPLETED = \"aqua\" COLOR_7_CANCELED =",
"self.COLOR_1_WAITING_FOR_YOUR_APPROVAL # else: # color = self.COLOR_CONFLICT elif event.requester == self.request.user: color =",
"color} if color in [self.COLOR_1_WAITING_FOR_YOUR_APPROVAL, self.COLOR_5_ONGOING, self.COLOR_3_APPROVED_COMMA_YOU_CAN_CHANGE, self.COLOR_0_YOUR_REQUEST]: event[\"className\"] = \"todo\" res.append(event) return",
"\"\"\" kwargs = super(AjaxableBookingRequestCreateView, self).get_form_kwargs() # kwargs.update({\"prefix\": \"update\"}) # tz = pytz.timezone(\"Asia/Shanghai\") #",
"True def is_valid_approval(self, approval_request): return (approval_request.approver is None) and approval_request.is_approved and \\ self.is_request_can_be_approved(approval_request)",
"\"update\"}) # tz = pytz.timezone(\"Asia/Shanghai\") # kwargs[\"instance\"].start = kwargs[\"instance\"].start.astimezone(tz).strftime(\"%m/%d/%Y\") # kwargs[\"instance\"].end = (kwargs[\"instance\"].end-datetime.timedelta(",
"called response = super(ResourceApproverUpdater, self).form_valid(form) return response class ColorSchema(object): COLOR_0_YOUR_REQUEST = \"tomato\" COLOR_1_WAITING_FOR_YOUR_APPROVAL",
"In ModelFormMixin.form_valid, form.save() and its parent's form_valid will be called # And in",
"model = BookingRequest exclude = [\"is_approved\", \"requester\", \"approver\", \"is_ongoing\", \"is_completed\", \"is_canceled\"] class BookingRequestUpdateForm(BookingRequestForm):",
"= [\"requester\", \"approver\"] class AjaxableBookingRequestCreateView(AjaxableResponseMixin, AjaxableFormContextUpdateMixin, CreateView): form_class = BookingRequestForm template_name = \"form_view_base_template.html\"",
"attr[8:] attr_name = attr_name.replace(\"_COMMA\", \",\") attr_name = attr_name.lower() attr_name = attr_name.replace(\"_\", \" \")",
"value = getattr(ColorSchema, attr) index = int(attr[6]) attr_name = attr[8:] attr_name = attr_name.replace(\"_COMMA\",",
"= self.request.user candidate.save() assign_perm(self.create_resource_permission, self.request.user, candidate) # In ModelFormMixin.form_valid, form.save() and its parent's",
"[self.COLOR_1_WAITING_FOR_YOUR_APPROVAL, self.COLOR_5_ONGOING, self.COLOR_3_APPROVED_COMMA_YOU_CAN_CHANGE, self.COLOR_0_YOUR_REQUEST]: event[\"className\"] = \"todo\" res.append(event) return HttpResponse(json.dumps(res), content_type=\"application/json\") def get_color(self,",
"attr[:6] != \"COLOR_\": continue value = getattr(ColorSchema, attr) index = int(attr[6]) attr_name =",
"def form_valid(self, form): candidate = form.save(commit=False) candidate.requester = self.request.user # use your own",
"= forms.DateField( required=False, widget=forms.TextInput(attrs={ 'class': 'datepicker' })) class Meta: model = BookingRequest exclude",
"in res_query: color = self.get_color(event) event = {\"id\": \"%d\" % event.pk, \"resourceId\": \"%d\"",
"pytz.timezone(\"Asia/Shanghai\") kwargs[\"instance\"].start = kwargs[\"instance\"].start.astimezone(tz).strftime(\"%m/%d/%Y\") kwargs[\"instance\"].end = (kwargs[\"instance\"].end - datetime.timedelta( days=1)).astimezone(tz).strftime(\"%m/%d/%Y\") return kwargs def",
":return: \"\"\" kwargs = super(AjaxableBookingRequestCreateView, self).get_form_kwargs() # kwargs.update({\"prefix\": \"update\"}) # tz = pytz.timezone(\"Asia/Shanghai\")",
"days=1)).astimezone(tz).strftime(\"%m/%d/%Y\") return kwargs def form_valid(self, form): candidate = form.save(commit=False) if self.is_valid_approval(candidate): candidate.approver =",
"# color = self.COLOR_5_ONGOING color = self.COLOR_5_ONGOING elif event.is_approved: if has_perm: color =",
"djangoautoconf.django_utils import retrieve_param from guardian.shortcuts import assign_perm from resource_daily_scheduler.models import BookingRequest, get_timezone_aware_datetime_from_date_str class",
"= \"Create\" def get_form_kwargs(self): \"\"\" Used to update end date in UI, as",
"= (kwargs[\"instance\"].end - datetime.timedelta( days=1)).astimezone(tz).strftime(\"%m/%d/%Y\") return kwargs def form_valid(self, form): candidate = form.save(commit=False)",
"class GetScheduleView(View, ColorSchema, RequestApprovalMixin): model = BookingRequest resource_approval_permission = \"change_bookableresource\" def get(self, request,",
"kwargs[\"initial\"] = {\"start\": data[\"start\"], \"resource\": int(data[\"resourceId\"])} return kwargs def form_valid(self, form): candidate =",
"form): candidate = form.save(commit=False) if self.is_valid_approval(candidate): candidate.approver = self.request.user candidate.save() else: candidate.is_approved =",
"RequestApprovalMixin): model = BookingRequest resource_approval_permission = \"change_bookableresource\" def get(self, request, *args, **kwargs): data",
"color = self.COLOR_CONFLICT elif event.requester == self.request.user: color = self.COLOR_0_YOUR_REQUEST return color def",
"ApproveRequestView(View, RequestApprovalMixin): model = BookingRequest def get(self, request, *args, **kwargs): data = retrieve_param(request)",
"resource_approval_permission = \"change_bookableresource\" def get(self, request, *args, **kwargs): data = retrieve_param(request) tz =",
"# use your own profile here candidate.save() response = super(AjaxableBookingRequestCreateView, self).form_valid(form) return response",
"def form_valid(self, form): candidate = form.save(commit=False) candidate.approver = self.request.user candidate.save() assign_perm(self.create_resource_permission, self.request.user, candidate)",
"# end_datetime = event.end # if event.end < end_datetime.astimezone(tz): # color = self.COLOR_5_ONGOING",
"get_timezone_aware_datetime_from_date_str class BookingRequestForm(forms.ModelForm): start = forms.DateField( required=False, widget=forms.TextInput(attrs={ 'class': 'datepicker' })) end =",
"| Q(is_ongoing=True))) # if any(conflicts_filter): # return False for i in conflicts_filter: return",
"attr_name = attr_name.replace(\"_COMMA\", \",\") attr_name = attr_name.lower() attr_name = attr_name.replace(\"_\", \" \") colors[attr_name.capitalize()]",
"import pytz from djangoautoconf.class_based_views.ajax_views import AjaxableResponseMixin from djangoautoconf.class_based_views.create_view_factory import AjaxableFormContextUpdateMixin from djangoautoconf.django_utils import",
"request, *args, **kwargs): data = retrieve_param(request) tz = pytz.timezone(\"Asia/Shanghai\") start = get_timezone_aware_datetime_from_date_str(data[\"start\"]) end",
"False result = \"false\" else: r.is_approved = True result = \"true\" r.save() return",
"# else: # color = self.COLOR_CONFLICT elif event.requester == self.request.user: color = self.COLOR_0_YOUR_REQUEST",
"elif event.requester == self.request.user: color = self.COLOR_0_YOUR_REQUEST return color def has_permission_to_manage_resource(self, event): return",
"color = self.COLOR_1_WAITING_FOR_YOUR_APPROVAL # else: # color = self.COLOR_CONFLICT elif event.requester == self.request.user:",
"= self.COLOR_5_ONGOING elif event.is_approved: if has_perm: color = self.COLOR_3_APPROVED_COMMA_YOU_CAN_CHANGE else: color = self.COLOR_4_APPROVED_COMMA_YOU_CANNOT_CHANGE",
"if color in [self.COLOR_1_WAITING_FOR_YOUR_APPROVAL, self.COLOR_5_ONGOING, self.COLOR_3_APPROVED_COMMA_YOU_CAN_CHANGE, self.COLOR_0_YOUR_REQUEST]: event[\"className\"] = \"todo\" res.append(event) return HttpResponse(json.dumps(res),",
"*args, **kwargs): data = retrieve_param(request) req_id = data[\"requestId\"] r = self.model.objects.get(pk=int(req_id)) if r.is_approved:",
"# return False for i in conflicts_filter: return False return True def is_valid_approval(self,",
"= \"form_view_base_template.html\" submit_button_text = \"Update\" success_url = \"../\" def get_form_kwargs(self): \"\"\" Used to",
"r.is_approved: r.is_approved = False result = \"false\" else: r.is_approved = True result =",
"(index, value) return colors class GetScheduleView(View, ColorSchema, RequestApprovalMixin): model = BookingRequest resource_approval_permission =",
"if r.is_approved: r.is_approved = False result = \"false\" else: r.is_approved = True result",
"\"\"\" kwargs = super(AjaxableBookingRequestUpdateView, self).get_form_kwargs() kwargs.update({\"prefix\": \"update\"}) tz = pytz.timezone(\"Asia/Shanghai\") kwargs[\"instance\"].start = kwargs[\"instance\"].start.astimezone(tz).strftime(\"%m/%d/%Y\")",
"self.COLOR_3_APPROVED_COMMA_YOU_CAN_CHANGE else: color = self.COLOR_4_APPROVED_COMMA_YOU_CANNOT_CHANGE elif has_perm: if self.is_request_can_be_approved(event): color = self.COLOR_1_WAITING_FOR_YOUR_APPROVAL #",
"kwargs[\"instance\"].start = kwargs[\"instance\"].start.astimezone(tz).strftime(\"%m/%d/%Y\") kwargs[\"instance\"].end = (kwargs[\"instance\"].end - datetime.timedelta( days=1)).astimezone(tz).strftime(\"%m/%d/%Y\") return kwargs def form_valid(self,",
"# \"black\" COLOR_6_COMPLETED = \"aqua\" COLOR_7_CANCELED = \"grey\" def get_colors(self): colors = {}",
"form_class = BookingRequestForm template_name = \"form_view_base_template.html\" submit_button_text = \"Create\" def get_form_kwargs(self): \"\"\" Used",
"if has_perm: color = self.COLOR_3_APPROVED_COMMA_YOU_CAN_CHANGE else: color = self.COLOR_4_APPROVED_COMMA_YOU_CANNOT_CHANGE elif has_perm: if self.is_request_can_be_approved(event):",
"return False for i in conflicts_filter: return False return True def is_valid_approval(self, approval_request):",
"called # And in FormMixin (ModelFormMixin's parent) HttpResponseRedirect(self.get_success_url()) will be called response =",
"def get_colors(self): colors = {} for attr in dir(ColorSchema): if attr != attr.upper():",
"= {\"start\": data[\"start\"], \"resource\": int(data[\"resourceId\"])} return kwargs def form_valid(self, form): candidate = form.save(commit=False)",
"color = self.get_color(event) event = {\"id\": \"%d\" % event.pk, \"resourceId\": \"%d\" % event.resource.pk,",
"\"COLOR_\": continue value = getattr(ColorSchema, attr) index = int(attr[6]) attr_name = attr[8:] attr_name",
"is_valid_approval(self, approval_request): return (approval_request.approver is None) and approval_request.is_approved and \\ self.is_request_can_be_approved(approval_request) class AjaxableBookingRequestUpdateView(AjaxableResponseMixin,",
"\"resourceId\": \"%d\" % event.resource.pk, \"start\": str(event.start), \"end\": str(event.end), \"title\": event.project, \"color\": color} if",
"= BookingRequestUpdateForm model = BookingRequest ajax_form_id = \"bookingReqEditForm\" template_name = \"form_view_base_template.html\" submit_button_text =",
"colors class GetScheduleView(View, ColorSchema, RequestApprovalMixin): model = BookingRequest resource_approval_permission = \"change_bookableresource\" def get(self,",
"self.request.user, candidate) # In ModelFormMixin.form_valid, form.save() and its parent's form_valid will be called",
"Meta: model = BookingRequest exclude = [\"is_approved\", \"requester\", \"approver\", \"is_ongoing\", \"is_completed\", \"is_canceled\"] class",
"COLOR_CONFLICT = \"DarkGray\" # \"black\" COLOR_6_COMPLETED = \"aqua\" COLOR_7_CANCELED = \"grey\" def get_colors(self):",
"dir(ColorSchema): if attr != attr.upper(): continue if attr[:6] != \"COLOR_\": continue value =",
"widget=forms.TextInput(attrs={ 'class': 'datepicker' })) end = forms.DateField( required=False, widget=forms.TextInput(attrs={ 'class': 'datepicker' })) class",
"\"\"\" Used to update end date in UI, as the end date in",
"# tz = pytz.timezone(\"Asia/Shanghai\") # kwargs[\"instance\"].start = kwargs[\"instance\"].start.astimezone(tz).strftime(\"%m/%d/%Y\") # kwargs[\"instance\"].end = (kwargs[\"instance\"].end-datetime.timedelta( #",
"import assign_perm from resource_daily_scheduler.models import BookingRequest, get_timezone_aware_datetime_from_date_str class BookingRequestForm(forms.ModelForm): start = forms.DateField( required=False,",
"response = super(ResourceApproverUpdater, self).form_valid(form) return response class ColorSchema(object): COLOR_0_YOUR_REQUEST = \"tomato\" COLOR_1_WAITING_FOR_YOUR_APPROVAL =",
"\"approver\", \"is_ongoing\", \"is_completed\", \"is_canceled\"] class BookingRequestUpdateForm(BookingRequestForm): class Meta: model = BookingRequest exclude =",
"\"is_ongoing\", \"is_completed\", \"is_canceled\"] class BookingRequestUpdateForm(BookingRequestForm): class Meta: model = BookingRequest exclude = [\"requester\",",
"**kwargs): data = retrieve_param(request) tz = pytz.timezone(\"Asia/Shanghai\") start = get_timezone_aware_datetime_from_date_str(data[\"start\"]) end = get_timezone_aware_datetime_from_date_str(data[\"end\"])",
"datetime.timedelta( days=1)).astimezone(tz).strftime(\"%m/%d/%Y\") return kwargs def form_valid(self, form): candidate = form.save(commit=False) if self.is_valid_approval(candidate): candidate.approver",
"event.is_ongoing: # tz = pytz.timezone(\"Asia/Shanghai\") # end_datetime = event.end # if event.end <",
"start_query)) res = [] for event in res_query: color = self.get_color(event) event =",
"start__lt=approval_request.end, end__gte=approval_request.start, resource=approval_request.resource, ) conflicts_filter = conflicts.filter(~Q(id=approval_request.pk) & (Q(is_approved=True) | Q(is_ongoing=True))) # if",
"elif event.is_ongoing: # tz = pytz.timezone(\"Asia/Shanghai\") # end_datetime = event.end # if event.end",
"BookingRequest exclude = [\"requester\", \"approver\"] class AjaxableBookingRequestCreateView(AjaxableResponseMixin, AjaxableFormContextUpdateMixin, CreateView): form_class = BookingRequestForm template_name",
"kwargs.update({\"prefix\": \"update\"}) tz = pytz.timezone(\"Asia/Shanghai\") kwargs[\"instance\"].start = kwargs[\"instance\"].start.astimezone(tz).strftime(\"%m/%d/%Y\") kwargs[\"instance\"].end = (kwargs[\"instance\"].end - datetime.timedelta(",
"kwargs = super(AjaxableBookingRequestCreateView, self).get_form_kwargs() # kwargs.update({\"prefix\": \"update\"}) # tz = pytz.timezone(\"Asia/Shanghai\") # kwargs[\"instance\"].start",
"= \"../\" def get_form_kwargs(self): \"\"\" Used to update end date in UI, as",
"COLOR_3_APPROVED_COMMA_YOU_CAN_CHANGE = \"DeepPink\" COLOR_4_APPROVED_COMMA_YOU_CANNOT_CHANGE = \"blue\" COLOR_5_ONGOING = \"green\" # COLOR_CONFLICT = \"DarkGray\"",
"if self.is_request_can_be_approved(event): color = self.COLOR_1_WAITING_FOR_YOUR_APPROVAL # else: # color = self.COLOR_CONFLICT elif event.requester",
"self.request.user candidate.save() assign_perm(self.create_resource_permission, self.request.user, candidate) # In ModelFormMixin.form_valid, form.save() and its parent's form_valid",
"\" \") colors[attr_name.capitalize()] = (index, value) return colors class GetScheduleView(View, ColorSchema, RequestApprovalMixin): model",
"= kwargs[\"instance\"].start.astimezone(tz).strftime(\"%m/%d/%Y\") # kwargs[\"instance\"].end = (kwargs[\"instance\"].end-datetime.timedelta( # days=1)).astimezone(tz).strftime(\"%m/%d/%Y\") data = retrieve_param(self.request) if (\"start\"",
"self.is_request_can_be_approved(event): color = self.COLOR_1_WAITING_FOR_YOUR_APPROVAL # else: # color = self.COLOR_CONFLICT elif event.requester ==",
"start = forms.DateField( required=False, widget=forms.TextInput(attrs={ 'class': 'datepicker' })) end = forms.DateField( required=False, widget=forms.TextInput(attrs={",
"HttpResponse(json.dumps(res), content_type=\"application/json\") def get_color(self, event): color = self.COLOR_2_WAITING_FOR_APPROVAL_FROM_OTHERS has_perm = self.has_permission_to_manage_resource(event) if event.is_canceled:",
"<filename>resource_daily_scheduler/booking_req_views.py import json from compat import View import datetime from django import forms",
"event.is_completed: color = self.COLOR_6_COMPLETED elif event.is_ongoing: # tz = pytz.timezone(\"Asia/Shanghai\") # end_datetime =",
"{\"id\": \"%d\" % event.pk, \"resourceId\": \"%d\" % event.resource.pk, \"start\": str(event.start), \"end\": str(event.end), \"title\":",
"< end_datetime.astimezone(tz): # color = self.COLOR_5_ONGOING color = self.COLOR_5_ONGOING elif event.is_approved: if has_perm:",
"has_permission_to_manage_resource(self, event): return self.request.user.has_perm(self.resource_approval_permission, event.resource) class ApproveRequestView(View, RequestApprovalMixin): model = BookingRequest def get(self,",
"from django.http import HttpResponse from django.views.generic.edit import CreateView, UpdateView import pytz from djangoautoconf.class_based_views.ajax_views",
"if attr != attr.upper(): continue if attr[:6] != \"COLOR_\": continue value = getattr(ColorSchema,",
"CreateView, UpdateView import pytz from djangoautoconf.class_based_views.ajax_views import AjaxableResponseMixin from djangoautoconf.class_based_views.create_view_factory import AjaxableFormContextUpdateMixin from",
"super(AjaxableBookingRequestUpdateView, self).form_valid(form) return response class ResourceApproverUpdater(object): create_resource_permission = 'change_bookableresource' def form_valid(self, form): candidate",
"= getattr(ColorSchema, attr) index = int(attr[6]) attr_name = attr[8:] attr_name = attr_name.replace(\"_COMMA\", \",\")",
"\"color\": color} if color in [self.COLOR_1_WAITING_FOR_YOUR_APPROVAL, self.COLOR_5_ONGOING, self.COLOR_3_APPROVED_COMMA_YOU_CAN_CHANGE, self.COLOR_0_YOUR_REQUEST]: event[\"className\"] = \"todo\" res.append(event)",
"\"grey\" def get_colors(self): colors = {} for attr in dir(ColorSchema): if attr !=",
"(approval_request.approver is None) and approval_request.is_approved and \\ self.is_request_can_be_approved(approval_request) class AjaxableBookingRequestUpdateView(AjaxableResponseMixin, AjaxableFormContextUpdateMixin, RequestApprovalMixin, UpdateView):",
"event): color = self.COLOR_2_WAITING_FOR_APPROVAL_FROM_OTHERS has_perm = self.has_permission_to_manage_resource(event) if event.is_canceled: color = self.COLOR_7_CANCELED elif",
"self.COLOR_6_COMPLETED elif event.is_ongoing: # tz = pytz.timezone(\"Asia/Shanghai\") # end_datetime = event.end # if",
"= BookingRequest exclude = [\"is_approved\", \"requester\", \"approver\", \"is_ongoing\", \"is_completed\", \"is_canceled\"] class BookingRequestUpdateForm(BookingRequestForm): class",
"request, *args, **kwargs): data = retrieve_param(request) req_id = data[\"requestId\"] r = self.model.objects.get(pk=int(req_id)) if",
"in UI is included in the reservation :return: \"\"\" kwargs = super(AjaxableBookingRequestCreateView, self).get_form_kwargs()",
"end__gte=approval_request.start, resource=approval_request.resource, ) conflicts_filter = conflicts.filter(~Q(id=approval_request.pk) & (Q(is_approved=True) | Q(is_ongoing=True))) # if any(conflicts_filter):",
"update end date in UI, as the end date in UI is included",
"= BookingRequest ajax_form_id = \"bookingReqEditForm\" template_name = \"form_view_base_template.html\" submit_button_text = \"Update\" success_url =",
"\"form_view_base_template.html\" submit_button_text = \"Update\" success_url = \"../\" def get_form_kwargs(self): \"\"\" Used to update",
"tz = pytz.timezone(\"Asia/Shanghai\") # end_datetime = event.end # if event.end < end_datetime.astimezone(tz): #",
"= BookingRequest resource_approval_permission = \"change_bookableresource\" def get(self, request, *args, **kwargs): data = retrieve_param(request)",
"= pytz.timezone(\"Asia/Shanghai\") # kwargs[\"instance\"].start = kwargs[\"instance\"].start.astimezone(tz).strftime(\"%m/%d/%Y\") # kwargs[\"instance\"].end = (kwargs[\"instance\"].end-datetime.timedelta( # days=1)).astimezone(tz).strftime(\"%m/%d/%Y\") data",
"the end date in UI is included in the reservation :return: \"\"\" kwargs",
"'datepicker' })) class Meta: model = BookingRequest exclude = [\"is_approved\", \"requester\", \"approver\", \"is_ongoing\",",
"self.model.objects.filter(~(end_query | start_query)) res = [] for event in res_query: color = self.get_color(event)",
"attr_name = attr[8:] attr_name = attr_name.replace(\"_COMMA\", \",\") attr_name = attr_name.lower() attr_name = attr_name.replace(\"_\",",
"get_colors(self): colors = {} for attr in dir(ColorSchema): if attr != attr.upper(): continue",
"= (kwargs[\"instance\"].end-datetime.timedelta( # days=1)).astimezone(tz).strftime(\"%m/%d/%Y\") data = retrieve_param(self.request) if (\"start\" in data) and (\"resourceId\"",
"attr_name.replace(\"_COMMA\", \",\") attr_name = attr_name.lower() attr_name = attr_name.replace(\"_\", \" \") colors[attr_name.capitalize()] = (index,",
"the reservation :return: \"\"\" kwargs = super(AjaxableBookingRequestCreateView, self).get_form_kwargs() # kwargs.update({\"prefix\": \"update\"}) # tz",
"= BookingRequest exclude = [\"requester\", \"approver\"] class AjaxableBookingRequestCreateView(AjaxableResponseMixin, AjaxableFormContextUpdateMixin, CreateView): form_class = BookingRequestForm",
"= \"false\" else: r.is_approved = True result = \"true\" r.save() return HttpResponse(json.dumps({\"result\": result}),",
"candidate.approver = self.request.user candidate.save() else: candidate.is_approved = False # In ModelFormMixin.form_valid, form.save() and",
"assign_perm from resource_daily_scheduler.models import BookingRequest, get_timezone_aware_datetime_from_date_str class BookingRequestForm(forms.ModelForm): start = forms.DateField( required=False, widget=forms.TextInput(attrs={",
"= int(attr[6]) attr_name = attr[8:] attr_name = attr_name.replace(\"_COMMA\", \",\") attr_name = attr_name.lower() attr_name",
"FormMixin (ModelFormMixin's parent) HttpResponseRedirect(self.get_success_url()) will be called response = super(AjaxableBookingRequestUpdateView, self).form_valid(form) return response",
"form_valid(self, form): candidate = form.save(commit=False) candidate.approver = self.request.user candidate.save() assign_perm(self.create_resource_permission, self.request.user, candidate) #",
"datetime from django import forms from django.db.models import Q from django.http import HttpResponse",
"parent's form_valid will be called # And in FormMixin (ModelFormMixin's parent) HttpResponseRedirect(self.get_success_url()) will",
"if event.is_canceled: color = self.COLOR_7_CANCELED elif event.is_completed: color = self.COLOR_6_COMPLETED elif event.is_ongoing: #",
"kwargs def form_valid(self, form): candidate = form.save(commit=False) candidate.requester = self.request.user # use your",
"submit_button_text = \"Create\" def get_form_kwargs(self): \"\"\" Used to update end date in UI,",
"i in conflicts_filter: return False return True def is_valid_approval(self, approval_request): return (approval_request.approver is",
"self.model.objects.get(pk=int(req_id)) if r.is_approved: r.is_approved = False result = \"false\" else: r.is_approved = True",
"attr_name = attr_name.replace(\"_\", \" \") colors[attr_name.capitalize()] = (index, value) return colors class GetScheduleView(View,",
"\"start\": str(event.start), \"end\": str(event.end), \"title\": event.project, \"color\": color} if color in [self.COLOR_1_WAITING_FOR_YOUR_APPROVAL, self.COLOR_5_ONGOING,",
"= pytz.timezone(\"Asia/Shanghai\") start = get_timezone_aware_datetime_from_date_str(data[\"start\"]) end = get_timezone_aware_datetime_from_date_str(data[\"end\"]) start_query = Q(end__lt=start) end_query =",
"in [self.COLOR_1_WAITING_FOR_YOUR_APPROVAL, self.COLOR_5_ONGOING, self.COLOR_3_APPROVED_COMMA_YOU_CAN_CHANGE, self.COLOR_0_YOUR_REQUEST]: event[\"className\"] = \"todo\" res.append(event) return HttpResponse(json.dumps(res), content_type=\"application/json\") def",
"in FormMixin (ModelFormMixin's parent) HttpResponseRedirect(self.get_success_url()) will be called response = super(ResourceApproverUpdater, self).form_valid(form) return",
"the reservation :return: \"\"\" kwargs = super(AjaxableBookingRequestUpdateView, self).get_form_kwargs() kwargs.update({\"prefix\": \"update\"}) tz = pytz.timezone(\"Asia/Shanghai\")",
"if event.end < end_datetime.astimezone(tz): # color = self.COLOR_5_ONGOING color = self.COLOR_5_ONGOING elif event.is_approved:",
"AjaxableFormContextUpdateMixin, RequestApprovalMixin, UpdateView): form_class = BookingRequestUpdateForm model = BookingRequest ajax_form_id = \"bookingReqEditForm\" template_name",
"\"black\" COLOR_6_COMPLETED = \"aqua\" COLOR_7_CANCELED = \"grey\" def get_colors(self): colors = {} for",
"= attr_name.lower() attr_name = attr_name.replace(\"_\", \" \") colors[attr_name.capitalize()] = (index, value) return colors",
"candidate = form.save(commit=False) if self.is_valid_approval(candidate): candidate.approver = self.request.user candidate.save() else: candidate.is_approved = False",
"model = BookingRequest exclude = [\"requester\", \"approver\"] class AjaxableBookingRequestCreateView(AjaxableResponseMixin, AjaxableFormContextUpdateMixin, CreateView): form_class =",
"\"requester\", \"approver\", \"is_ongoing\", \"is_completed\", \"is_canceled\"] class BookingRequestUpdateForm(BookingRequestForm): class Meta: model = BookingRequest exclude",
"HttpResponseRedirect(self.get_success_url()) will be called response = super(AjaxableBookingRequestUpdateView, self).form_valid(form) return response class ResourceApproverUpdater(object): create_resource_permission",
"[] for event in res_query: color = self.get_color(event) event = {\"id\": \"%d\" %",
"in data): kwargs[\"initial\"] = {\"start\": data[\"start\"], \"resource\": int(data[\"resourceId\"])} return kwargs def form_valid(self, form):",
"# kwargs.update({\"prefix\": \"update\"}) # tz = pytz.timezone(\"Asia/Shanghai\") # kwargs[\"instance\"].start = kwargs[\"instance\"].start.astimezone(tz).strftime(\"%m/%d/%Y\") # kwargs[\"instance\"].end",
"})) end = forms.DateField( required=False, widget=forms.TextInput(attrs={ 'class': 'datepicker' })) class Meta: model =",
"ModelFormMixin.form_valid, form.save() and its parent's form_valid will be called # And in FormMixin",
"candidate = form.save(commit=False) candidate.requester = self.request.user # use your own profile here candidate.save()",
"\",\") attr_name = attr_name.lower() attr_name = attr_name.replace(\"_\", \" \") colors[attr_name.capitalize()] = (index, value)",
"# And in FormMixin (ModelFormMixin's parent) HttpResponseRedirect(self.get_success_url()) will be called response = super(ResourceApproverUpdater,",
"BookingRequest, get_timezone_aware_datetime_from_date_str class BookingRequestForm(forms.ModelForm): start = forms.DateField( required=False, widget=forms.TextInput(attrs={ 'class': 'datepicker' })) end",
"candidate.requester = self.request.user # use your own profile here candidate.save() response = super(AjaxableBookingRequestCreateView,",
"data): kwargs[\"initial\"] = {\"start\": data[\"start\"], \"resource\": int(data[\"resourceId\"])} return kwargs def form_valid(self, form): candidate",
"str(event.end), \"title\": event.project, \"color\": color} if color in [self.COLOR_1_WAITING_FOR_YOUR_APPROVAL, self.COLOR_5_ONGOING, self.COLOR_3_APPROVED_COMMA_YOU_CAN_CHANGE, self.COLOR_0_YOUR_REQUEST]: event[\"className\"]",
"kwargs[\"instance\"].end = (kwargs[\"instance\"].end-datetime.timedelta( # days=1)).astimezone(tz).strftime(\"%m/%d/%Y\") data = retrieve_param(self.request) if (\"start\" in data) and",
"res.append(event) return HttpResponse(json.dumps(res), content_type=\"application/json\") def get_color(self, event): color = self.COLOR_2_WAITING_FOR_APPROVAL_FROM_OTHERS has_perm = self.has_permission_to_manage_resource(event)",
"\"end\": str(event.end), \"title\": event.project, \"color\": color} if color in [self.COLOR_1_WAITING_FOR_YOUR_APPROVAL, self.COLOR_5_ONGOING, self.COLOR_3_APPROVED_COMMA_YOU_CAN_CHANGE, self.COLOR_0_YOUR_REQUEST]:",
"end date in UI is included in the reservation :return: \"\"\" kwargs =",
"django.views.generic.edit import CreateView, UpdateView import pytz from djangoautoconf.class_based_views.ajax_views import AjaxableResponseMixin from djangoautoconf.class_based_views.create_view_factory import",
"= \"bookingReqEditForm\" template_name = \"form_view_base_template.html\" submit_button_text = \"Update\" success_url = \"../\" def get_form_kwargs(self):",
"self.request.user.has_perm(self.resource_approval_permission, event.resource) class ApproveRequestView(View, RequestApprovalMixin): model = BookingRequest def get(self, request, *args, **kwargs):",
"color = self.COLOR_5_ONGOING color = self.COLOR_5_ONGOING elif event.is_approved: if has_perm: color = self.COLOR_3_APPROVED_COMMA_YOU_CAN_CHANGE",
"forms from django.db.models import Q from django.http import HttpResponse from django.views.generic.edit import CreateView,",
"tz = pytz.timezone(\"Asia/Shanghai\") kwargs[\"instance\"].start = kwargs[\"instance\"].start.astimezone(tz).strftime(\"%m/%d/%Y\") kwargs[\"instance\"].end = (kwargs[\"instance\"].end - datetime.timedelta( days=1)).astimezone(tz).strftime(\"%m/%d/%Y\") return",
"retrieve_param(request) req_id = data[\"requestId\"] r = self.model.objects.get(pk=int(req_id)) if r.is_approved: r.is_approved = False result",
"= self.model.objects.filter( start__lt=approval_request.end, end__gte=approval_request.start, resource=approval_request.resource, ) conflicts_filter = conflicts.filter(~Q(id=approval_request.pk) & (Q(is_approved=True) | Q(is_ongoing=True)))",
"= Q(end__lt=start) end_query = Q(start__gt=end) res_query = self.model.objects.filter(~(end_query | start_query)) res = []",
"UI is included in the reservation :return: \"\"\" kwargs = super(AjaxableBookingRequestUpdateView, self).get_form_kwargs() kwargs.update({\"prefix\":",
"AjaxableResponseMixin from djangoautoconf.class_based_views.create_view_factory import AjaxableFormContextUpdateMixin from djangoautoconf.django_utils import retrieve_param from guardian.shortcuts import assign_perm",
"color = self.COLOR_3_APPROVED_COMMA_YOU_CAN_CHANGE else: color = self.COLOR_4_APPROVED_COMMA_YOU_CANNOT_CHANGE elif has_perm: if self.is_request_can_be_approved(event): color =",
"called response = super(AjaxableBookingRequestUpdateView, self).form_valid(form) return response class ResourceApproverUpdater(object): create_resource_permission = 'change_bookableresource' def",
"tz = pytz.timezone(\"Asia/Shanghai\") start = get_timezone_aware_datetime_from_date_str(data[\"start\"]) end = get_timezone_aware_datetime_from_date_str(data[\"end\"]) start_query = Q(end__lt=start) end_query",
"elif has_perm: if self.is_request_can_be_approved(event): color = self.COLOR_1_WAITING_FOR_YOUR_APPROVAL # else: # color = self.COLOR_CONFLICT",
"else: candidate.is_approved = False # In ModelFormMixin.form_valid, form.save() and its parent's form_valid will",
"in dir(ColorSchema): if attr != attr.upper(): continue if attr[:6] != \"COLOR_\": continue value",
"= super(AjaxableBookingRequestCreateView, self).form_valid(form) return response class RequestApprovalMixin(object): def is_request_can_be_approved(self, approval_request): conflicts = self.model.objects.filter(",
"= form.save(commit=False) if self.is_valid_approval(candidate): candidate.approver = self.request.user candidate.save() else: candidate.is_approved = False #",
"= \"DeepPink\" COLOR_4_APPROVED_COMMA_YOU_CANNOT_CHANGE = \"blue\" COLOR_5_ONGOING = \"green\" # COLOR_CONFLICT = \"DarkGray\" #",
"Used to update end date in UI, as the end date in UI",
"end date in UI, as the end date in UI is included in",
"included in the reservation :return: \"\"\" kwargs = super(AjaxableBookingRequestUpdateView, self).get_form_kwargs() kwargs.update({\"prefix\": \"update\"}) tz",
"resource_daily_scheduler.models import BookingRequest, get_timezone_aware_datetime_from_date_str class BookingRequestForm(forms.ModelForm): start = forms.DateField( required=False, widget=forms.TextInput(attrs={ 'class': 'datepicker'",
"has_perm = self.has_permission_to_manage_resource(event) if event.is_canceled: color = self.COLOR_7_CANCELED elif event.is_completed: color = self.COLOR_6_COMPLETED",
"ColorSchema, RequestApprovalMixin): model = BookingRequest resource_approval_permission = \"change_bookableresource\" def get(self, request, *args, **kwargs):",
"from django import forms from django.db.models import Q from django.http import HttpResponse from",
"response = super(AjaxableBookingRequestUpdateView, self).form_valid(form) return response class ResourceApproverUpdater(object): create_resource_permission = 'change_bookableresource' def form_valid(self,",
"And in FormMixin (ModelFormMixin's parent) HttpResponseRedirect(self.get_success_url()) will be called response = super(AjaxableBookingRequestUpdateView, self).form_valid(form)",
"req_id = data[\"requestId\"] r = self.model.objects.get(pk=int(req_id)) if r.is_approved: r.is_approved = False result =",
"pytz.timezone(\"Asia/Shanghai\") # kwargs[\"instance\"].start = kwargs[\"instance\"].start.astimezone(tz).strftime(\"%m/%d/%Y\") # kwargs[\"instance\"].end = (kwargs[\"instance\"].end-datetime.timedelta( # days=1)).astimezone(tz).strftime(\"%m/%d/%Y\") data =",
"ajax_form_id = \"bookingReqEditForm\" template_name = \"form_view_base_template.html\" submit_button_text = \"Update\" success_url = \"../\" def",
"django import forms from django.db.models import Q from django.http import HttpResponse from django.views.generic.edit",
"and \\ self.is_request_can_be_approved(approval_request) class AjaxableBookingRequestUpdateView(AjaxableResponseMixin, AjaxableFormContextUpdateMixin, RequestApprovalMixin, UpdateView): form_class = BookingRequestUpdateForm model =",
"False # In ModelFormMixin.form_valid, form.save() and its parent's form_valid will be called #",
"RequestApprovalMixin, UpdateView): form_class = BookingRequestUpdateForm model = BookingRequest ajax_form_id = \"bookingReqEditForm\" template_name =",
"!= attr.upper(): continue if attr[:6] != \"COLOR_\": continue value = getattr(ColorSchema, attr) index",
"kwargs = super(AjaxableBookingRequestUpdateView, self).get_form_kwargs() kwargs.update({\"prefix\": \"update\"}) tz = pytz.timezone(\"Asia/Shanghai\") kwargs[\"instance\"].start = kwargs[\"instance\"].start.astimezone(tz).strftime(\"%m/%d/%Y\") kwargs[\"instance\"].end",
"color = self.COLOR_0_YOUR_REQUEST return color def has_permission_to_manage_resource(self, event): return self.request.user.has_perm(self.resource_approval_permission, event.resource) class ApproveRequestView(View,",
"reservation :return: \"\"\" kwargs = super(AjaxableBookingRequestCreateView, self).get_form_kwargs() # kwargs.update({\"prefix\": \"update\"}) # tz =",
"(kwargs[\"instance\"].end - datetime.timedelta( days=1)).astimezone(tz).strftime(\"%m/%d/%Y\") return kwargs def form_valid(self, form): candidate = form.save(commit=False) if",
"str(event.start), \"end\": str(event.end), \"title\": event.project, \"color\": color} if color in [self.COLOR_1_WAITING_FOR_YOUR_APPROVAL, self.COLOR_5_ONGOING, self.COLOR_3_APPROVED_COMMA_YOU_CAN_CHANGE,",
"= False # In ModelFormMixin.form_valid, form.save() and its parent's form_valid will be called",
"\"yellow\" COLOR_2_WAITING_FOR_APPROVAL_FROM_OTHERS = \"limegreen\" COLOR_3_APPROVED_COMMA_YOU_CAN_CHANGE = \"DeepPink\" COLOR_4_APPROVED_COMMA_YOU_CANNOT_CHANGE = \"blue\" COLOR_5_ONGOING = \"green\"",
"= [\"is_approved\", \"requester\", \"approver\", \"is_ongoing\", \"is_completed\", \"is_canceled\"] class BookingRequestUpdateForm(BookingRequestForm): class Meta: model =",
"\"resource\": int(data[\"resourceId\"])} return kwargs def form_valid(self, form): candidate = form.save(commit=False) candidate.requester = self.request.user",
"in the reservation :return: \"\"\" kwargs = super(AjaxableBookingRequestUpdateView, self).get_form_kwargs() kwargs.update({\"prefix\": \"update\"}) tz =",
"= False result = \"false\" else: r.is_approved = True result = \"true\" r.save()",
"form.save(commit=False) candidate.approver = self.request.user candidate.save() assign_perm(self.create_resource_permission, self.request.user, candidate) # In ModelFormMixin.form_valid, form.save() and",
"{} for attr in dir(ColorSchema): if attr != attr.upper(): continue if attr[:6] !=",
"will be called response = super(AjaxableBookingRequestUpdateView, self).form_valid(form) return response class ResourceApproverUpdater(object): create_resource_permission =",
"class ApproveRequestView(View, RequestApprovalMixin): model = BookingRequest def get(self, request, *args, **kwargs): data =",
"= self.COLOR_3_APPROVED_COMMA_YOU_CAN_CHANGE else: color = self.COLOR_4_APPROVED_COMMA_YOU_CANNOT_CHANGE elif has_perm: if self.is_request_can_be_approved(event): color = self.COLOR_1_WAITING_FOR_YOUR_APPROVAL",
"Q(end__lt=start) end_query = Q(start__gt=end) res_query = self.model.objects.filter(~(end_query | start_query)) res = [] for",
"res = [] for event in res_query: color = self.get_color(event) event = {\"id\":",
"\"is_completed\", \"is_canceled\"] class BookingRequestUpdateForm(BookingRequestForm): class Meta: model = BookingRequest exclude = [\"requester\", \"approver\"]",
"class BookingRequestForm(forms.ModelForm): start = forms.DateField( required=False, widget=forms.TextInput(attrs={ 'class': 'datepicker' })) end = forms.DateField(",
"= \"grey\" def get_colors(self): colors = {} for attr in dir(ColorSchema): if attr",
"get_color(self, event): color = self.COLOR_2_WAITING_FOR_APPROVAL_FROM_OTHERS has_perm = self.has_permission_to_manage_resource(event) if event.is_canceled: color = self.COLOR_7_CANCELED",
"Q(start__gt=end) res_query = self.model.objects.filter(~(end_query | start_query)) res = [] for event in res_query:",
"= self.model.objects.get(pk=int(req_id)) if r.is_approved: r.is_approved = False result = \"false\" else: r.is_approved =",
"forms.DateField( required=False, widget=forms.TextInput(attrs={ 'class': 'datepicker' })) end = forms.DateField( required=False, widget=forms.TextInput(attrs={ 'class': 'datepicker'",
"self.COLOR_5_ONGOING elif event.is_approved: if has_perm: color = self.COLOR_3_APPROVED_COMMA_YOU_CAN_CHANGE else: color = self.COLOR_4_APPROVED_COMMA_YOU_CANNOT_CHANGE elif",
"elif event.is_approved: if has_perm: color = self.COLOR_3_APPROVED_COMMA_YOU_CAN_CHANGE else: color = self.COLOR_4_APPROVED_COMMA_YOU_CANNOT_CHANGE elif has_perm:",
"UpdateView): form_class = BookingRequestUpdateForm model = BookingRequest ajax_form_id = \"bookingReqEditForm\" template_name = \"form_view_base_template.html\"",
"conflicts = self.model.objects.filter( start__lt=approval_request.end, end__gte=approval_request.start, resource=approval_request.resource, ) conflicts_filter = conflicts.filter(~Q(id=approval_request.pk) & (Q(is_approved=True) |",
"COLOR_1_WAITING_FOR_YOUR_APPROVAL = \"yellow\" COLOR_2_WAITING_FOR_APPROVAL_FROM_OTHERS = \"limegreen\" COLOR_3_APPROVED_COMMA_YOU_CAN_CHANGE = \"DeepPink\" COLOR_4_APPROVED_COMMA_YOU_CANNOT_CHANGE = \"blue\" COLOR_5_ONGOING",
"response class RequestApprovalMixin(object): def is_request_can_be_approved(self, approval_request): conflicts = self.model.objects.filter( start__lt=approval_request.end, end__gte=approval_request.start, resource=approval_request.resource, )",
"date in UI, as the end date in UI is included in the",
"COLOR_2_WAITING_FOR_APPROVAL_FROM_OTHERS = \"limegreen\" COLOR_3_APPROVED_COMMA_YOU_CAN_CHANGE = \"DeepPink\" COLOR_4_APPROVED_COMMA_YOU_CANNOT_CHANGE = \"blue\" COLOR_5_ONGOING = \"green\" #",
"self.COLOR_0_YOUR_REQUEST]: event[\"className\"] = \"todo\" res.append(event) return HttpResponse(json.dumps(res), content_type=\"application/json\") def get_color(self, event): color =",
"return kwargs def form_valid(self, form): candidate = form.save(commit=False) if self.is_valid_approval(candidate): candidate.approver = self.request.user",
"= pytz.timezone(\"Asia/Shanghai\") # end_datetime = event.end # if event.end < end_datetime.astimezone(tz): # color",
"Q(is_ongoing=True))) # if any(conflicts_filter): # return False for i in conflicts_filter: return False",
"is included in the reservation :return: \"\"\" kwargs = super(AjaxableBookingRequestUpdateView, self).get_form_kwargs() kwargs.update({\"prefix\": \"update\"})",
"result = \"false\" else: r.is_approved = True result = \"true\" r.save() return HttpResponse(json.dumps({\"result\":",
"form): candidate = form.save(commit=False) candidate.approver = self.request.user candidate.save() assign_perm(self.create_resource_permission, self.request.user, candidate) # In",
"[\"requester\", \"approver\"] class AjaxableBookingRequestCreateView(AjaxableResponseMixin, AjaxableFormContextUpdateMixin, CreateView): form_class = BookingRequestForm template_name = \"form_view_base_template.html\" submit_button_text",
"data) and (\"resourceId\" in data): kwargs[\"initial\"] = {\"start\": data[\"start\"], \"resource\": int(data[\"resourceId\"])} return kwargs",
"*args, **kwargs): data = retrieve_param(request) tz = pytz.timezone(\"Asia/Shanghai\") start = get_timezone_aware_datetime_from_date_str(data[\"start\"]) end =",
"candidate.save() else: candidate.is_approved = False # In ModelFormMixin.form_valid, form.save() and its parent's form_valid",
"(\"resourceId\" in data): kwargs[\"initial\"] = {\"start\": data[\"start\"], \"resource\": int(data[\"resourceId\"])} return kwargs def form_valid(self,",
"event[\"className\"] = \"todo\" res.append(event) return HttpResponse(json.dumps(res), content_type=\"application/json\") def get_color(self, event): color = self.COLOR_2_WAITING_FOR_APPROVAL_FROM_OTHERS",
"res_query: color = self.get_color(event) event = {\"id\": \"%d\" % event.pk, \"resourceId\": \"%d\" %",
"BookingRequest def get(self, request, *args, **kwargs): data = retrieve_param(request) req_id = data[\"requestId\"] r",
"form.save(commit=False) if self.is_valid_approval(candidate): candidate.approver = self.request.user candidate.save() else: candidate.is_approved = False # In",
"self.COLOR_2_WAITING_FOR_APPROVAL_FROM_OTHERS has_perm = self.has_permission_to_manage_resource(event) if event.is_canceled: color = self.COLOR_7_CANCELED elif event.is_completed: color =",
"django.http import HttpResponse from django.views.generic.edit import CreateView, UpdateView import pytz from djangoautoconf.class_based_views.ajax_views import",
"= kwargs[\"instance\"].start.astimezone(tz).strftime(\"%m/%d/%Y\") kwargs[\"instance\"].end = (kwargs[\"instance\"].end - datetime.timedelta( days=1)).astimezone(tz).strftime(\"%m/%d/%Y\") return kwargs def form_valid(self, form):",
"\"DarkGray\" # \"black\" COLOR_6_COMPLETED = \"aqua\" COLOR_7_CANCELED = \"grey\" def get_colors(self): colors =",
"event): return self.request.user.has_perm(self.resource_approval_permission, event.resource) class ApproveRequestView(View, RequestApprovalMixin): model = BookingRequest def get(self, request,",
"= data[\"requestId\"] r = self.model.objects.get(pk=int(req_id)) if r.is_approved: r.is_approved = False result = \"false\"",
"# color = self.COLOR_CONFLICT elif event.requester == self.request.user: color = self.COLOR_0_YOUR_REQUEST return color",
"COLOR_4_APPROVED_COMMA_YOU_CANNOT_CHANGE = \"blue\" COLOR_5_ONGOING = \"green\" # COLOR_CONFLICT = \"DarkGray\" # \"black\" COLOR_6_COMPLETED",
"color = self.COLOR_7_CANCELED elif event.is_completed: color = self.COLOR_6_COMPLETED elif event.is_ongoing: # tz =",
"HttpResponseRedirect(self.get_success_url()) will be called response = super(ResourceApproverUpdater, self).form_valid(form) return response class ColorSchema(object): COLOR_0_YOUR_REQUEST",
"guardian.shortcuts import assign_perm from resource_daily_scheduler.models import BookingRequest, get_timezone_aware_datetime_from_date_str class BookingRequestForm(forms.ModelForm): start = forms.DateField(",
"form.save(commit=False) candidate.requester = self.request.user # use your own profile here candidate.save() response =",
"pytz from djangoautoconf.class_based_views.ajax_views import AjaxableResponseMixin from djangoautoconf.class_based_views.create_view_factory import AjaxableFormContextUpdateMixin from djangoautoconf.django_utils import retrieve_param",
"= [] for event in res_query: color = self.get_color(event) event = {\"id\": \"%d\"",
"submit_button_text = \"Update\" success_url = \"../\" def get_form_kwargs(self): \"\"\" Used to update end",
"def get_form_kwargs(self): \"\"\" Used to update end date in UI, as the end",
"form.save() and its parent's form_valid will be called # And in FormMixin (ModelFormMixin's",
"= \"yellow\" COLOR_2_WAITING_FOR_APPROVAL_FROM_OTHERS = \"limegreen\" COLOR_3_APPROVED_COMMA_YOU_CAN_CHANGE = \"DeepPink\" COLOR_4_APPROVED_COMMA_YOU_CANNOT_CHANGE = \"blue\" COLOR_5_ONGOING =",
"= attr_name.replace(\"_\", \" \") colors[attr_name.capitalize()] = (index, value) return colors class GetScheduleView(View, ColorSchema,",
"attr_name.replace(\"_\", \" \") colors[attr_name.capitalize()] = (index, value) return colors class GetScheduleView(View, ColorSchema, RequestApprovalMixin):",
"= get_timezone_aware_datetime_from_date_str(data[\"end\"]) start_query = Q(end__lt=start) end_query = Q(start__gt=end) res_query = self.model.objects.filter(~(end_query | start_query))",
"elif event.is_completed: color = self.COLOR_6_COMPLETED elif event.is_ongoing: # tz = pytz.timezone(\"Asia/Shanghai\") # end_datetime",
"Q from django.http import HttpResponse from django.views.generic.edit import CreateView, UpdateView import pytz from",
"= self.COLOR_1_WAITING_FOR_YOUR_APPROVAL # else: # color = self.COLOR_CONFLICT elif event.requester == self.request.user: color",
"== self.request.user: color = self.COLOR_0_YOUR_REQUEST return color def has_permission_to_manage_resource(self, event): return self.request.user.has_perm(self.resource_approval_permission, event.resource)"
] |
[
"= A (1001) a.show ('america') autoTester.check (A.p) autoTester.check (a.p) b = B (2002)",
"aClass.__bases__: if not aBase in result and aBase != object: result.append (aBase) mro",
"label) autoTester.check ('C.show', label, self.x, self.y) a = A (1001) a.show ('america') autoTester.check",
"self.x) def show2 (self, label): autoTester.check ('A.show2', label, self.x) class B: p, q",
"autoTester.check (c.p) autoTester.check (c.q) c.show2 ('amsterdam') A.show2 (c, 'rotterdam') show3 = c.show show3",
"(a, 'p')) autoTester.check (hasattr (a, 'q')) autoTester.check ('<br><br>Augmented isinstance and issubclass<br>') # Augmented",
"y autoTester.check (self.p) def show (self, label): autoTester.check ('B.show', label, self.y) class C",
"((simpleTypes, tupleTypes)): for j, aType in enumerate (types): for k, aClass in enumerate",
"in result and aBase != object: result.append (aBase) mro (aBase, result) if last",
"list, A, B, C, bool, str, float, int, object) tupleTypes = ((dict, list),",
"[aClass] last = 1 for aBase in aClass.__bases__: if not aBase in result",
"autoTester.check (c.q) c.show2 ('amsterdam') A.show2 (c, 'rotterdam') show3 = c.show show3 ('copy') autoTester.check",
"k, isinstance (anObject, aType)) if types == simpleTypes: autoTester.check (i, j, k, isinstance",
"autoTester.check (i, j, k, isinstance (anObject, simpleTypes)) for i, types in enumerate ((simpleTypes,",
"(c.p) autoTester.check (c.q) c.show2 ('amsterdam') A.show2 (c, 'rotterdam') show3 = c.show show3 ('copy')",
"''' Recursively assemble method resolution order from all base classes''' last = 0",
"autoTester.check (A.p) autoTester.check (a.p) c = C (3003, 4004) c.show ('netherlands') autoTester.check (C.p)",
"tupleTypes)): for j, aType in enumerate (types): for k, anObject in enumerate (({'a':",
"j, k, issubclass (aClass, aType)) if types == simpleTypes: autoTester.check (i + 2,",
"Recursively assemble method resolution order from all base classes''' last = 0 if",
"if last and object in aClass.__bases__: aRoot.append (object) return result autoTester.check ([aClass.__name__ for",
"autoTester.check (hasattr (a, 'y')) autoTester.check (hasattr (a, 'p')) autoTester.check (hasattr (a, 'q')) autoTester.check",
"label, self.x, self.y) a = A (1001) a.show ('america') autoTester.check (A.p) autoTester.check (a.p)",
"autoTester.check ('<br><br>Augmented isinstance and issubclass<br>') # Augmented meaning: compatible with native JavaScript types",
"123 def __init__ (self, x): self.x = x autoTester.check (self.p) def show (self,",
"tupleTypes = ((dict, list), (bool, int), (bool, A), (C, B), (B, object)) for",
"(B.p) autoTester.check (b.p) autoTester.check (b.q) autoTester.check (A.p) autoTester.check (a.p) c = C (3003,",
"autoTester.check ('B.show', label, self.y) class C (A, B): def __init__ (self, x, y):",
"float)): autoTester.check (i + 2, j, k, issubclass (aClass, aType)) if types ==",
"(A.p) autoTester.check (a.p) b = B (2002) b.show ('russia') autoTester.check (B.p) autoTester.check (b.p)",
"(hasattr (a, 'y')) autoTester.check (hasattr (a, 'p')) autoTester.check (hasattr (a, 'q')) autoTester.check ('<br><br>Augmented",
"and issubclass<br>') # Augmented meaning: compatible with native JavaScript types simpleTypes = (dict,",
"in enumerate ((dict, list, A, C, B, bool, str, int, float)): autoTester.check (i",
"('A.show2', label, self.x) class B: p, q = 456, 789 def __init__ (self,",
"(a, 'y')) autoTester.check (hasattr (a, 'p')) autoTester.check (hasattr (a, 'q')) autoTester.check ('<br><br>Augmented isinstance",
"result = None): ''' Recursively assemble method resolution order from all base classes'''",
"A (1001) a.show ('america') autoTester.check (A.p) autoTester.check (a.p) b = B (2002) b.show",
"enumerate (types): for k, aClass in enumerate ((dict, list, A, C, B, bool,",
"result is None: result = [aClass] last = 1 for aBase in aClass.__bases__:",
"base classes''' last = 0 if result is None: result = [aClass] last",
"def mro (aClass, result = None): ''' Recursively assemble method resolution order from",
"def show (self, label): A.show (self, label) B.show (self, label) autoTester.check ('C.show', label,",
"for k, aClass in enumerate ((dict, list, A, C, B, bool, str, int,",
"(self, x, y): autoTester.check ('In C constructor') A.__init__ (self, x) B.__init__ (self, y)",
"('In C constructor') A.__init__ (self, x) B.__init__ (self, y) def show (self, label):",
"autoTester.check ('A.show', label, self.x) def show2 (self, label): autoTester.check ('A.show2', label, self.x) class",
"+ 2, j, k, issubclass (aClass, simpleTypes)) autoTester.check ('<br><br>Method resolution order<br>') def mro",
"(self, label): A.show (self, label) B.show (self, label) autoTester.check ('C.show', label, self.x, self.y)",
"(aBase) mro (aBase, result) if last and object in aClass.__bases__: aRoot.append (object) return",
"x autoTester.check (self.p) def show (self, label): autoTester.check ('A.show', label, self.x) def show2",
"aBase in result and aBase != object: result.append (aBase) mro (aBase, result) if",
"int, float)): autoTester.check (i + 2, j, k, issubclass (aClass, aType)) if types",
"enumerate (types): for k, anObject in enumerate (({'a': 1}, [], a, C, c,",
"= [aClass] last = 1 for aBase in aClass.__bases__: if not aBase in",
"b.show ('russia') autoTester.check (B.p) autoTester.check (b.p) autoTester.check (b.q) autoTester.check (A.p) autoTester.check (a.p) c",
"last and object in aClass.__bases__: aRoot.append (object) return result autoTester.check ([aClass.__name__ for aClass",
"[], a, C, c, C, b, True, 'a', 1, 1.2)): autoTester.check (i, j,",
"= C (3003, 4004) c.show ('netherlands') autoTester.check (C.p) autoTester.check (c.p) autoTester.check (c.q) c.show2",
"enumerate (({'a': 1}, [], a, C, c, C, b, True, 'a', 1, 1.2)):",
"= y autoTester.check (self.p) def show (self, label): autoTester.check ('B.show', label, self.y) class",
"(b.q) autoTester.check (A.p) autoTester.check (a.p) c = C (3003, 4004) c.show ('netherlands') autoTester.check",
"(2002) b.show ('russia') autoTester.check (B.p) autoTester.check (b.p) autoTester.check (b.q) autoTester.check (A.p) autoTester.check (a.p)",
"(a.p) b = B (2002) b.show ('russia') autoTester.check (B.p) autoTester.check (b.p) autoTester.check (b.q)",
"(bool, A), (C, B), (B, object)) for i, types in enumerate ((simpleTypes, tupleTypes)):",
"(hasattr (a, 'p')) autoTester.check (hasattr (a, 'q')) autoTester.check ('<br><br>Augmented isinstance and issubclass<br>') #",
"aType in enumerate (types): for k, aClass in enumerate ((dict, list, A, C,",
"(self, x): self.x = x autoTester.check (self.p) def show (self, label): autoTester.check ('A.show',",
"B constructor') self.y = y autoTester.check (self.p) def show (self, label): autoTester.check ('B.show',",
"C, b, True, 'a', 1, 1.2)): autoTester.check (i, j, k, isinstance (anObject, aType))",
"types == simpleTypes: autoTester.check (i, j, k, isinstance (anObject, simpleTypes)) for i, types",
"show (self, label): autoTester.check ('B.show', label, self.y) class C (A, B): def __init__",
"j, k, isinstance (anObject, simpleTypes)) for i, types in enumerate ((simpleTypes, tupleTypes)): for",
"str, int, float)): autoTester.check (i + 2, j, k, issubclass (aClass, aType)) if",
"object) tupleTypes = ((dict, list), (bool, int), (bool, A), (C, B), (B, object))",
"bool, str, int, float)): autoTester.check (i + 2, j, k, issubclass (aClass, aType))",
"x): self.x = x autoTester.check (self.p) def show (self, label): autoTester.check ('A.show', label,",
"aBase != object: result.append (aBase) mro (aBase, result) if last and object in",
"and aBase != object: result.append (aBase) mro (aBase, result) if last and object",
"__init__ (self, y): autoTester.check ('In B constructor') self.y = y autoTester.check (self.p) def",
"in enumerate (({'a': 1}, [], a, C, c, C, b, True, 'a', 1,",
"if result is None: result = [aClass] last = 1 for aBase in",
"'a', 1, 1.2)): autoTester.check (i, j, k, isinstance (anObject, aType)) if types ==",
"(self, x) B.__init__ (self, y) def show (self, label): A.show (self, label) B.show",
"('america') autoTester.check (A.p) autoTester.check (a.p) b = B (2002) b.show ('russia') autoTester.check (B.p)",
"B), (B, object)) for i, types in enumerate ((simpleTypes, tupleTypes)): for j, aType",
"j, k, issubclass (aClass, simpleTypes)) autoTester.check ('<br><br>Method resolution order<br>') def mro (aClass, result",
"self.y) class C (A, B): def __init__ (self, x, y): autoTester.check ('In C",
"aBase in aClass.__bases__: if not aBase in result and aBase != object: result.append",
"is None: result = [aClass] last = 1 for aBase in aClass.__bases__: if",
"show (self, label): autoTester.check ('A.show', label, self.x) def show2 (self, label): autoTester.check ('A.show2',",
"C, bool, str, float, int, object) tupleTypes = ((dict, list), (bool, int), (bool,",
"with native JavaScript types simpleTypes = (dict, list, A, B, C, bool, str,",
"all base classes''' last = 0 if result is None: result = [aClass]",
"(aClass, simpleTypes)) autoTester.check ('<br><br>Method resolution order<br>') def mro (aClass, result = None): '''",
"aType)) if types == simpleTypes: autoTester.check (i + 2, j, k, issubclass (aClass,",
"if types == simpleTypes: autoTester.check (i + 2, j, k, issubclass (aClass, simpleTypes))",
"__init__ (self, x): self.x = x autoTester.check (self.p) def show (self, label): autoTester.check",
"isinstance and issubclass<br>') # Augmented meaning: compatible with native JavaScript types simpleTypes =",
"aType in enumerate (types): for k, anObject in enumerate (({'a': 1}, [], a,",
"(a.p) c = C (3003, 4004) c.show ('netherlands') autoTester.check (C.p) autoTester.check (c.p) autoTester.check",
"(C.p) autoTester.check (c.p) autoTester.check (c.q) c.show2 ('amsterdam') A.show2 (c, 'rotterdam') show3 = c.show",
"JavaScript types simpleTypes = (dict, list, A, B, C, bool, str, float, int,",
"autoTester.check (self.p) def show (self, label): autoTester.check ('B.show', label, self.y) class C (A,",
"(self, label): autoTester.check ('B.show', label, self.y) class C (A, B): def __init__ (self,",
"a.show ('america') autoTester.check (A.p) autoTester.check (a.p) b = B (2002) b.show ('russia') autoTester.check",
"'q')) autoTester.check ('<br><br>Augmented isinstance and issubclass<br>') # Augmented meaning: compatible with native JavaScript",
"issubclass<br>') # Augmented meaning: compatible with native JavaScript types simpleTypes = (dict, list,",
"= 123 def __init__ (self, x): self.x = x autoTester.check (self.p) def show",
"isinstance (anObject, aType)) if types == simpleTypes: autoTester.check (i, j, k, isinstance (anObject,",
"run (autoTester): autoTester.check ('<br>General<br>') class A: p = 123 def __init__ (self, x):",
"j, k, isinstance (anObject, aType)) if types == simpleTypes: autoTester.check (i, j, k,",
"and object in aClass.__bases__: aRoot.append (object) return result autoTester.check ([aClass.__name__ for aClass in",
"autoTester.check (self.p) def show (self, label): autoTester.check ('A.show', label, self.x) def show2 (self,",
"== simpleTypes: autoTester.check (i + 2, j, k, issubclass (aClass, simpleTypes)) autoTester.check ('<br><br>Method",
"('<br><br>Augmented isinstance and issubclass<br>') # Augmented meaning: compatible with native JavaScript types simpleTypes",
"x) B.__init__ (self, y) def show (self, label): A.show (self, label) B.show (self,",
"(self, label) B.show (self, label) autoTester.check ('C.show', label, self.x, self.y) a = A",
"y): autoTester.check ('In B constructor') self.y = y autoTester.check (self.p) def show (self,",
"def __init__ (self, x, y): autoTester.check ('In C constructor') A.__init__ (self, x) B.__init__",
"in aClass.__bases__: aRoot.append (object) return result autoTester.check ([aClass.__name__ for aClass in mro (C)])",
"enumerate ((simpleTypes, tupleTypes)): for j, aType in enumerate (types): for k, aClass in",
"autoTester.check ('C.show', label, self.x, self.y) a = A (1001) a.show ('america') autoTester.check (A.p)",
"def show (self, label): autoTester.check ('B.show', label, self.y) class C (A, B): def",
"(hasattr (a, 'x')) autoTester.check (hasattr (a, 'y')) autoTester.check (hasattr (a, 'p')) autoTester.check (hasattr",
"int, object) tupleTypes = ((dict, list), (bool, int), (bool, A), (C, B), (B,",
"(c, 'rotterdam') show3 = c.show show3 ('copy') autoTester.check (hasattr (a, 'x')) autoTester.check (hasattr",
"float, int, object) tupleTypes = ((dict, list), (bool, int), (bool, A), (C, B),",
"object in aClass.__bases__: aRoot.append (object) return result autoTester.check ([aClass.__name__ for aClass in mro",
"label, self.x) def show2 (self, label): autoTester.check ('A.show2', label, self.x) class B: p,",
"result and aBase != object: result.append (aBase) mro (aBase, result) if last and",
"(i, j, k, isinstance (anObject, aType)) if types == simpleTypes: autoTester.check (i, j,",
"types simpleTypes = (dict, list, A, B, C, bool, str, float, int, object)",
"def show (self, label): autoTester.check ('A.show', label, self.x) def show2 (self, label): autoTester.check",
"for aBase in aClass.__bases__: if not aBase in result and aBase != object:",
"(hasattr (a, 'q')) autoTester.check ('<br><br>Augmented isinstance and issubclass<br>') # Augmented meaning: compatible with",
"A, C, B, bool, str, int, float)): autoTester.check (i + 2, j, k,",
"autoTester.check (hasattr (a, 'x')) autoTester.check (hasattr (a, 'y')) autoTester.check (hasattr (a, 'p')) autoTester.check",
"tupleTypes)): for j, aType in enumerate (types): for k, aClass in enumerate ((dict,",
"1 for aBase in aClass.__bases__: if not aBase in result and aBase !=",
"from all base classes''' last = 0 if result is None: result =",
"('In B constructor') self.y = y autoTester.check (self.p) def show (self, label): autoTester.check",
"label): autoTester.check ('A.show', label, self.x) def show2 (self, label): autoTester.check ('A.show2', label, self.x)",
"in enumerate (types): for k, anObject in enumerate (({'a': 1}, [], a, C,",
"a, C, c, C, b, True, 'a', 1, 1.2)): autoTester.check (i, j, k,",
"y) def show (self, label): A.show (self, label) B.show (self, label) autoTester.check ('C.show',",
"enumerate ((simpleTypes, tupleTypes)): for j, aType in enumerate (types): for k, anObject in",
"(B, object)) for i, types in enumerate ((simpleTypes, tupleTypes)): for j, aType in",
"list, A, C, B, bool, str, int, float)): autoTester.check (i + 2, j,",
"0 if result is None: result = [aClass] last = 1 for aBase",
"(self.p) def show (self, label): autoTester.check ('B.show', label, self.y) class C (A, B):",
"meaning: compatible with native JavaScript types simpleTypes = (dict, list, A, B, C,",
"c = C (3003, 4004) c.show ('netherlands') autoTester.check (C.p) autoTester.check (c.p) autoTester.check (c.q)",
"enumerate ((dict, list, A, C, B, bool, str, int, float)): autoTester.check (i +",
"simpleTypes: autoTester.check (i, j, k, isinstance (anObject, simpleTypes)) for i, types in enumerate",
"2, j, k, issubclass (aClass, aType)) if types == simpleTypes: autoTester.check (i +",
"(i + 2, j, k, issubclass (aClass, aType)) if types == simpleTypes: autoTester.check",
"label): autoTester.check ('A.show2', label, self.x) class B: p, q = 456, 789 def",
"label): autoTester.check ('B.show', label, self.y) class C (A, B): def __init__ (self, x,",
"types == simpleTypes: autoTester.check (i + 2, j, k, issubclass (aClass, simpleTypes)) autoTester.check",
"simpleTypes)) for i, types in enumerate ((simpleTypes, tupleTypes)): for j, aType in enumerate",
"x, y): autoTester.check ('In C constructor') A.__init__ (self, x) B.__init__ (self, y) def",
"label, self.x) class B: p, q = 456, 789 def __init__ (self, y):",
"result.append (aBase) mro (aBase, result) if last and object in aClass.__bases__: aRoot.append (object)",
"self.x, self.y) a = A (1001) a.show ('america') autoTester.check (A.p) autoTester.check (a.p) b",
"autoTester.check (b.p) autoTester.check (b.q) autoTester.check (A.p) autoTester.check (a.p) c = C (3003, 4004)",
"if types == simpleTypes: autoTester.check (i, j, k, isinstance (anObject, simpleTypes)) for i,",
"class B: p, q = 456, 789 def __init__ (self, y): autoTester.check ('In",
"= 1 for aBase in aClass.__bases__: if not aBase in result and aBase",
"constructor') self.y = y autoTester.check (self.p) def show (self, label): autoTester.check ('B.show', label,",
"not aBase in result and aBase != object: result.append (aBase) mro (aBase, result)",
"c.show show3 ('copy') autoTester.check (hasattr (a, 'x')) autoTester.check (hasattr (a, 'y')) autoTester.check (hasattr",
"('copy') autoTester.check (hasattr (a, 'x')) autoTester.check (hasattr (a, 'y')) autoTester.check (hasattr (a, 'p'))",
"c.show ('netherlands') autoTester.check (C.p) autoTester.check (c.p) autoTester.check (c.q) c.show2 ('amsterdam') A.show2 (c, 'rotterdam')",
"b, True, 'a', 1, 1.2)): autoTester.check (i, j, k, isinstance (anObject, aType)) if",
"autoTester.check (i, j, k, isinstance (anObject, aType)) if types == simpleTypes: autoTester.check (i,",
"A.show2 (c, 'rotterdam') show3 = c.show show3 ('copy') autoTester.check (hasattr (a, 'x')) autoTester.check",
"def __init__ (self, y): autoTester.check ('In B constructor') self.y = y autoTester.check (self.p)",
"(self, y): autoTester.check ('In B constructor') self.y = y autoTester.check (self.p) def show",
"isinstance (anObject, simpleTypes)) for i, types in enumerate ((simpleTypes, tupleTypes)): for j, aType",
"autoTester.check ('<br><br>Method resolution order<br>') def mro (aClass, result = None): ''' Recursively assemble",
"('russia') autoTester.check (B.p) autoTester.check (b.p) autoTester.check (b.q) autoTester.check (A.p) autoTester.check (a.p) c =",
"__init__ (self, x, y): autoTester.check ('In C constructor') A.__init__ (self, x) B.__init__ (self,",
"autoTester.check (hasattr (a, 'p')) autoTester.check (hasattr (a, 'q')) autoTester.check ('<br><br>Augmented isinstance and issubclass<br>')",
"(1001) a.show ('america') autoTester.check (A.p) autoTester.check (a.p) b = B (2002) b.show ('russia')",
"autoTester.check (a.p) b = B (2002) b.show ('russia') autoTester.check (B.p) autoTester.check (b.p) autoTester.check",
"2, j, k, issubclass (aClass, simpleTypes)) autoTester.check ('<br><br>Method resolution order<br>') def mro (aClass,",
"p, q = 456, 789 def __init__ (self, y): autoTester.check ('In B constructor')",
"k, anObject in enumerate (({'a': 1}, [], a, C, c, C, b, True,",
"('C.show', label, self.x, self.y) a = A (1001) a.show ('america') autoTester.check (A.p) autoTester.check",
"class A: p = 123 def __init__ (self, x): self.x = x autoTester.check",
"('amsterdam') A.show2 (c, 'rotterdam') show3 = c.show show3 ('copy') autoTester.check (hasattr (a, 'x'))",
"autoTester.check (hasattr (a, 'q')) autoTester.check ('<br><br>Augmented isinstance and issubclass<br>') # Augmented meaning: compatible",
"('B.show', label, self.y) class C (A, B): def __init__ (self, x, y): autoTester.check",
"= 456, 789 def __init__ (self, y): autoTester.check ('In B constructor') self.y =",
"autoTester.check (B.p) autoTester.check (b.p) autoTester.check (b.q) autoTester.check (A.p) autoTester.check (a.p) c = C",
"= c.show show3 ('copy') autoTester.check (hasattr (a, 'x')) autoTester.check (hasattr (a, 'y')) autoTester.check",
"aClass in enumerate ((dict, list, A, C, B, bool, str, int, float)): autoTester.check",
"A.__init__ (self, x) B.__init__ (self, y) def show (self, label): A.show (self, label)",
"last = 0 if result is None: result = [aClass] last = 1",
"((simpleTypes, tupleTypes)): for j, aType in enumerate (types): for k, anObject in enumerate",
"def show2 (self, label): autoTester.check ('A.show2', label, self.x) class B: p, q =",
"self.y = y autoTester.check (self.p) def show (self, label): autoTester.check ('B.show', label, self.y)",
"(A.p) autoTester.check (a.p) c = C (3003, 4004) c.show ('netherlands') autoTester.check (C.p) autoTester.check",
"q = 456, 789 def __init__ (self, y): autoTester.check ('In B constructor') self.y",
"order from all base classes''' last = 0 if result is None: result",
"(aBase, result) if last and object in aClass.__bases__: aRoot.append (object) return result autoTester.check",
"'p')) autoTester.check (hasattr (a, 'q')) autoTester.check ('<br><br>Augmented isinstance and issubclass<br>') # Augmented meaning:",
"('<br><br>Method resolution order<br>') def mro (aClass, result = None): ''' Recursively assemble method",
"resolution order from all base classes''' last = 0 if result is None:",
"issubclass (aClass, aType)) if types == simpleTypes: autoTester.check (i + 2, j, k,",
"= None): ''' Recursively assemble method resolution order from all base classes''' last",
"autoTester.check (A.p) autoTester.check (a.p) b = B (2002) b.show ('russia') autoTester.check (B.p) autoTester.check",
"True, 'a', 1, 1.2)): autoTester.check (i, j, k, isinstance (anObject, aType)) if types",
"k, isinstance (anObject, simpleTypes)) for i, types in enumerate ((simpleTypes, tupleTypes)): for j,",
"constructor') A.__init__ (self, x) B.__init__ (self, y) def show (self, label): A.show (self,",
"456, 789 def __init__ (self, y): autoTester.check ('In B constructor') self.y = y",
"simpleTypes)) autoTester.check ('<br><br>Method resolution order<br>') def mro (aClass, result = None): ''' Recursively",
"show3 = c.show show3 ('copy') autoTester.check (hasattr (a, 'x')) autoTester.check (hasattr (a, 'y'))",
"in enumerate ((simpleTypes, tupleTypes)): for j, aType in enumerate (types): for k, anObject",
"(self, label) autoTester.check ('C.show', label, self.x, self.y) a = A (1001) a.show ('america')",
"k, issubclass (aClass, simpleTypes)) autoTester.check ('<br><br>Method resolution order<br>') def mro (aClass, result =",
"classes''' last = 0 if result is None: result = [aClass] last =",
"None: result = [aClass] last = 1 for aBase in aClass.__bases__: if not",
"('A.show', label, self.x) def show2 (self, label): autoTester.check ('A.show2', label, self.x) class B:",
"((dict, list, A, C, B, bool, str, int, float)): autoTester.check (i + 2,",
"for i, types in enumerate ((simpleTypes, tupleTypes)): for j, aType in enumerate (types):",
"(anObject, simpleTypes)) for i, types in enumerate ((simpleTypes, tupleTypes)): for j, aType in",
"c, C, b, True, 'a', 1, 1.2)): autoTester.check (i, j, k, isinstance (anObject,",
"B.__init__ (self, y) def show (self, label): A.show (self, label) B.show (self, label)",
"autoTester.check ('In B constructor') self.y = y autoTester.check (self.p) def show (self, label):",
"y): autoTester.check ('In C constructor') A.__init__ (self, x) B.__init__ (self, y) def show",
"C constructor') A.__init__ (self, x) B.__init__ (self, y) def show (self, label): A.show",
"(3003, 4004) c.show ('netherlands') autoTester.check (C.p) autoTester.check (c.p) autoTester.check (c.q) c.show2 ('amsterdam') A.show2",
"label): A.show (self, label) B.show (self, label) autoTester.check ('C.show', label, self.x, self.y) a",
"aType)) if types == simpleTypes: autoTester.check (i, j, k, isinstance (anObject, simpleTypes)) for",
"B, bool, str, int, float)): autoTester.check (i + 2, j, k, issubclass (aClass,",
"autoTester.check ('In C constructor') A.__init__ (self, x) B.__init__ (self, y) def show (self,",
"(dict, list, A, B, C, bool, str, float, int, object) tupleTypes = ((dict,",
"A), (C, B), (B, object)) for i, types in enumerate ((simpleTypes, tupleTypes)): for",
"simpleTypes = (dict, list, A, B, C, bool, str, float, int, object) tupleTypes",
"(A, B): def __init__ (self, x, y): autoTester.check ('In C constructor') A.__init__ (self,",
"789 def __init__ (self, y): autoTester.check ('In B constructor') self.y = y autoTester.check",
"for j, aType in enumerate (types): for k, aClass in enumerate ((dict, list,",
"(({'a': 1}, [], a, C, c, C, b, True, 'a', 1, 1.2)): autoTester.check",
"(self.p) def show (self, label): autoTester.check ('A.show', label, self.x) def show2 (self, label):",
"A.show (self, label) B.show (self, label) autoTester.check ('C.show', label, self.x, self.y) a =",
"None): ''' Recursively assemble method resolution order from all base classes''' last =",
"show2 (self, label): autoTester.check ('A.show2', label, self.x) class B: p, q = 456,",
"(aClass, result = None): ''' Recursively assemble method resolution order from all base",
"label) B.show (self, label) autoTester.check ('C.show', label, self.x, self.y) a = A (1001)",
"anObject in enumerate (({'a': 1}, [], a, C, c, C, b, True, 'a',",
"result = [aClass] last = 1 for aBase in aClass.__bases__: if not aBase",
"C, c, C, b, True, 'a', 1, 1.2)): autoTester.check (i, j, k, isinstance",
"autoTester.check (i + 2, j, k, issubclass (aClass, simpleTypes)) autoTester.check ('<br><br>Method resolution order<br>')",
"1, 1.2)): autoTester.check (i, j, k, isinstance (anObject, aType)) if types == simpleTypes:",
"autoTester.check ('<br>General<br>') class A: p = 123 def __init__ (self, x): self.x =",
"(self, label): autoTester.check ('A.show', label, self.x) def show2 (self, label): autoTester.check ('A.show2', label,",
"last = 1 for aBase in aClass.__bases__: if not aBase in result and",
"b = B (2002) b.show ('russia') autoTester.check (B.p) autoTester.check (b.p) autoTester.check (b.q) autoTester.check",
"C (A, B): def __init__ (self, x, y): autoTester.check ('In C constructor') A.__init__",
"simpleTypes: autoTester.check (i + 2, j, k, issubclass (aClass, simpleTypes)) autoTester.check ('<br><br>Method resolution",
"B: p, q = 456, 789 def __init__ (self, y): autoTester.check ('In B",
"'rotterdam') show3 = c.show show3 ('copy') autoTester.check (hasattr (a, 'x')) autoTester.check (hasattr (a,",
"list), (bool, int), (bool, A), (C, B), (B, object)) for i, types in",
"self.x) class B: p, q = 456, 789 def __init__ (self, y): autoTester.check",
"p = 123 def __init__ (self, x): self.x = x autoTester.check (self.p) def",
"+ 2, j, k, issubclass (aClass, aType)) if types == simpleTypes: autoTester.check (i",
"= 0 if result is None: result = [aClass] last = 1 for",
"k, aClass in enumerate ((dict, list, A, C, B, bool, str, int, float)):",
"assemble method resolution order from all base classes''' last = 0 if result",
"issubclass (aClass, simpleTypes)) autoTester.check ('<br><br>Method resolution order<br>') def mro (aClass, result = None):",
"mro (aClass, result = None): ''' Recursively assemble method resolution order from all",
"(a, 'x')) autoTester.check (hasattr (a, 'y')) autoTester.check (hasattr (a, 'p')) autoTester.check (hasattr (a,",
"self.x = x autoTester.check (self.p) def show (self, label): autoTester.check ('A.show', label, self.x)",
"order<br>') def mro (aClass, result = None): ''' Recursively assemble method resolution order",
"if not aBase in result and aBase != object: result.append (aBase) mro (aBase,",
"(a, 'q')) autoTester.check ('<br><br>Augmented isinstance and issubclass<br>') # Augmented meaning: compatible with native",
"show3 ('copy') autoTester.check (hasattr (a, 'x')) autoTester.check (hasattr (a, 'y')) autoTester.check (hasattr (a,",
"== simpleTypes: autoTester.check (i, j, k, isinstance (anObject, simpleTypes)) for i, types in",
"native JavaScript types simpleTypes = (dict, list, A, B, C, bool, str, float,",
"k, issubclass (aClass, aType)) if types == simpleTypes: autoTester.check (i + 2, j,",
"autoTester.check (a.p) c = C (3003, 4004) c.show ('netherlands') autoTester.check (C.p) autoTester.check (c.p)",
"= (dict, list, A, B, C, bool, str, float, int, object) tupleTypes =",
"A, B, C, bool, str, float, int, object) tupleTypes = ((dict, list), (bool,",
"= B (2002) b.show ('russia') autoTester.check (B.p) autoTester.check (b.p) autoTester.check (b.q) autoTester.check (A.p)",
"(i + 2, j, k, issubclass (aClass, simpleTypes)) autoTester.check ('<br><br>Method resolution order<br>') def",
"B.show (self, label) autoTester.check ('C.show', label, self.x, self.y) a = A (1001) a.show",
"c.show2 ('amsterdam') A.show2 (c, 'rotterdam') show3 = c.show show3 ('copy') autoTester.check (hasattr (a,",
"(aClass, aType)) if types == simpleTypes: autoTester.check (i + 2, j, k, issubclass",
"B): def __init__ (self, x, y): autoTester.check ('In C constructor') A.__init__ (self, x)",
"(self, y) def show (self, label): A.show (self, label) B.show (self, label) autoTester.check",
"in enumerate (types): for k, aClass in enumerate ((dict, list, A, C, B,",
"for k, anObject in enumerate (({'a': 1}, [], a, C, c, C, b,",
"j, aType in enumerate (types): for k, aClass in enumerate ((dict, list, A,",
"(types): for k, aClass in enumerate ((dict, list, A, C, B, bool, str,",
"(bool, int), (bool, A), (C, B), (B, object)) for i, types in enumerate",
"int), (bool, A), (C, B), (B, object)) for i, types in enumerate ((simpleTypes,",
"!= object: result.append (aBase) mro (aBase, result) if last and object in aClass.__bases__:",
"show (self, label): A.show (self, label) B.show (self, label) autoTester.check ('C.show', label, self.x,",
"bool, str, float, int, object) tupleTypes = ((dict, list), (bool, int), (bool, A),",
"label, self.y) class C (A, B): def __init__ (self, x, y): autoTester.check ('In",
"C, B, bool, str, int, float)): autoTester.check (i + 2, j, k, issubclass",
"(self, label): autoTester.check ('A.show2', label, self.x) class B: p, q = 456, 789",
"Augmented meaning: compatible with native JavaScript types simpleTypes = (dict, list, A, B,",
"types in enumerate ((simpleTypes, tupleTypes)): for j, aType in enumerate (types): for k,",
"('<br>General<br>') class A: p = 123 def __init__ (self, x): self.x = x",
"autoTester.check (C.p) autoTester.check (c.p) autoTester.check (c.q) c.show2 ('amsterdam') A.show2 (c, 'rotterdam') show3 =",
"(types): for k, anObject in enumerate (({'a': 1}, [], a, C, c, C,",
"resolution order<br>') def mro (aClass, result = None): ''' Recursively assemble method resolution",
"def run (autoTester): autoTester.check ('<br>General<br>') class A: p = 123 def __init__ (self,",
"(c.q) c.show2 ('amsterdam') A.show2 (c, 'rotterdam') show3 = c.show show3 ('copy') autoTester.check (hasattr",
"object: result.append (aBase) mro (aBase, result) if last and object in aClass.__bases__: aRoot.append",
"in enumerate ((simpleTypes, tupleTypes)): for j, aType in enumerate (types): for k, aClass",
"j, aType in enumerate (types): for k, anObject in enumerate (({'a': 1}, [],",
"autoTester.check (b.q) autoTester.check (A.p) autoTester.check (a.p) c = C (3003, 4004) c.show ('netherlands')",
"(autoTester): autoTester.check ('<br>General<br>') class A: p = 123 def __init__ (self, x): self.x",
"result) if last and object in aClass.__bases__: aRoot.append (object) return result autoTester.check ([aClass.__name__",
"str, float, int, object) tupleTypes = ((dict, list), (bool, int), (bool, A), (C,",
"= x autoTester.check (self.p) def show (self, label): autoTester.check ('A.show', label, self.x) def",
"self.y) a = A (1001) a.show ('america') autoTester.check (A.p) autoTester.check (a.p) b =",
"'y')) autoTester.check (hasattr (a, 'p')) autoTester.check (hasattr (a, 'q')) autoTester.check ('<br><br>Augmented isinstance and",
"object)) for i, types in enumerate ((simpleTypes, tupleTypes)): for j, aType in enumerate",
"B (2002) b.show ('russia') autoTester.check (B.p) autoTester.check (b.p) autoTester.check (b.q) autoTester.check (A.p) autoTester.check",
"('netherlands') autoTester.check (C.p) autoTester.check (c.p) autoTester.check (c.q) c.show2 ('amsterdam') A.show2 (c, 'rotterdam') show3",
"A: p = 123 def __init__ (self, x): self.x = x autoTester.check (self.p)",
"C (3003, 4004) c.show ('netherlands') autoTester.check (C.p) autoTester.check (c.p) autoTester.check (c.q) c.show2 ('amsterdam')",
"B, C, bool, str, float, int, object) tupleTypes = ((dict, list), (bool, int),",
"(anObject, aType)) if types == simpleTypes: autoTester.check (i, j, k, isinstance (anObject, simpleTypes))",
"4004) c.show ('netherlands') autoTester.check (C.p) autoTester.check (c.p) autoTester.check (c.q) c.show2 ('amsterdam') A.show2 (c,",
"autoTester.check (i + 2, j, k, issubclass (aClass, aType)) if types == simpleTypes:",
"(i, j, k, isinstance (anObject, simpleTypes)) for i, types in enumerate ((simpleTypes, tupleTypes)):",
"autoTester.check ('A.show2', label, self.x) class B: p, q = 456, 789 def __init__",
"# Augmented meaning: compatible with native JavaScript types simpleTypes = (dict, list, A,",
"def __init__ (self, x): self.x = x autoTester.check (self.p) def show (self, label):",
"class C (A, B): def __init__ (self, x, y): autoTester.check ('In C constructor')",
"1.2)): autoTester.check (i, j, k, isinstance (anObject, aType)) if types == simpleTypes: autoTester.check",
"'x')) autoTester.check (hasattr (a, 'y')) autoTester.check (hasattr (a, 'p')) autoTester.check (hasattr (a, 'q'))",
"(C, B), (B, object)) for i, types in enumerate ((simpleTypes, tupleTypes)): for j,",
"((dict, list), (bool, int), (bool, A), (C, B), (B, object)) for i, types",
"= ((dict, list), (bool, int), (bool, A), (C, B), (B, object)) for i,",
"method resolution order from all base classes''' last = 0 if result is",
"1}, [], a, C, c, C, b, True, 'a', 1, 1.2)): autoTester.check (i,",
"(b.p) autoTester.check (b.q) autoTester.check (A.p) autoTester.check (a.p) c = C (3003, 4004) c.show",
"in aClass.__bases__: if not aBase in result and aBase != object: result.append (aBase)",
"mro (aBase, result) if last and object in aClass.__bases__: aRoot.append (object) return result",
"for j, aType in enumerate (types): for k, anObject in enumerate (({'a': 1},",
"a = A (1001) a.show ('america') autoTester.check (A.p) autoTester.check (a.p) b = B",
"compatible with native JavaScript types simpleTypes = (dict, list, A, B, C, bool,",
"i, types in enumerate ((simpleTypes, tupleTypes)): for j, aType in enumerate (types): for"
] |
[
"files def getFontName(self): return self._name def getFontSize(self): return self._size def render(self, text, antialias,",
"self._font.render(text, antialias, color, background) def size(self, text): return self._font.size(text) def get_height(self): return self._font.get_height()",
"pygame.font.SysFont(name, size) #TODO Add support for font files def getFontName(self): return self._name def",
"Add support for font files def getFontName(self): return self._name def getFontSize(self): return self._size",
"return self._name def getFontSize(self): return self._size def render(self, text, antialias, color, background=None): return",
"self._size def render(self, text, antialias, color, background=None): return self._font.render(text, antialias, color, background) def",
"def render(self, text, antialias, color, background=None): return self._font.render(text, antialias, color, background) def size(self,",
"background=None): return self._font.render(text, antialias, color, background) def size(self, text): return self._font.size(text) def get_height(self):",
"def __init__(self, name, size): self._name = name self._size = size self._font = pygame.font.SysFont(name,",
"def getFontName(self): return self._name def getFontSize(self): return self._size def render(self, text, antialias, color,",
"= pygame.font.SysFont(name, size) #TODO Add support for font files def getFontName(self): return self._name",
"pygame class Font(): def __init__(self, name, size): self._name = name self._size = size",
"size self._font = pygame.font.SysFont(name, size) #TODO Add support for font files def getFontName(self):",
"name, size): self._name = name self._size = size self._font = pygame.font.SysFont(name, size) #TODO",
"support for font files def getFontName(self): return self._name def getFontSize(self): return self._size def",
"for font files def getFontName(self): return self._name def getFontSize(self): return self._size def render(self,",
"getFontSize(self): return self._size def render(self, text, antialias, color, background=None): return self._font.render(text, antialias, color,",
"self._size = size self._font = pygame.font.SysFont(name, size) #TODO Add support for font files",
"size): self._name = name self._size = size self._font = pygame.font.SysFont(name, size) #TODO Add",
"font files def getFontName(self): return self._name def getFontSize(self): return self._size def render(self, text,",
"import pygame class Font(): def __init__(self, name, size): self._name = name self._size =",
"text, antialias, color, background=None): return self._font.render(text, antialias, color, background) def size(self, text): return",
"= name self._size = size self._font = pygame.font.SysFont(name, size) #TODO Add support for",
"getFontName(self): return self._name def getFontSize(self): return self._size def render(self, text, antialias, color, background=None):",
"__init__(self, name, size): self._name = name self._size = size self._font = pygame.font.SysFont(name, size)",
"name self._size = size self._font = pygame.font.SysFont(name, size) #TODO Add support for font",
"Font(): def __init__(self, name, size): self._name = name self._size = size self._font =",
"= size self._font = pygame.font.SysFont(name, size) #TODO Add support for font files def",
"def getFontSize(self): return self._size def render(self, text, antialias, color, background=None): return self._font.render(text, antialias,",
"class Font(): def __init__(self, name, size): self._name = name self._size = size self._font",
"antialias, color, background=None): return self._font.render(text, antialias, color, background) def size(self, text): return self._font.size(text)",
"self._name def getFontSize(self): return self._size def render(self, text, antialias, color, background=None): return self._font.render(text,",
"color, background=None): return self._font.render(text, antialias, color, background) def size(self, text): return self._font.size(text) def",
"size) #TODO Add support for font files def getFontName(self): return self._name def getFontSize(self):",
"return self._font.render(text, antialias, color, background) def size(self, text): return self._font.size(text) def get_height(self): return",
"#TODO Add support for font files def getFontName(self): return self._name def getFontSize(self): return",
"self._name = name self._size = size self._font = pygame.font.SysFont(name, size) #TODO Add support",
"return self._size def render(self, text, antialias, color, background=None): return self._font.render(text, antialias, color, background)",
"self._font = pygame.font.SysFont(name, size) #TODO Add support for font files def getFontName(self): return",
"render(self, text, antialias, color, background=None): return self._font.render(text, antialias, color, background) def size(self, text):"
] |
[
"def __init__(self): self._listeners = [] self._raw_listeners = [] def __call__(self, msg): return def",
"def add_listener(self, listener): self._listeners.append(listener) def add_raw_listener(self, raw_listener): self._raw_listeners.append(raw_listener) def recieve(self, msg): for listener",
"msg): for listener in self._listeners: listener(msg) packed_msg = pack_msg(msg) for raw_listener in self._raw_listeners:",
"[] def __call__(self, msg): return def add_listener(self, listener): self._listeners.append(listener) def add_raw_listener(self, raw_listener): self._raw_listeners.append(raw_listener)",
"msg): return def add_listener(self, listener): self._listeners.append(listener) def add_raw_listener(self, raw_listener): self._raw_listeners.append(raw_listener) def recieve(self, msg):",
"self._listeners = [] self._raw_listeners = [] def __call__(self, msg): return def add_listener(self, listener):",
"class DirectReceiverMock: def __init__(self): self._listeners = [] self._raw_listeners = [] def __call__(self, msg):",
"from mite.utils import pack_msg class DirectReceiverMock: def __init__(self): self._listeners = [] self._raw_listeners =",
"= [] self._raw_listeners = [] def __call__(self, msg): return def add_listener(self, listener): self._listeners.append(listener)",
"= [] def __call__(self, msg): return def add_listener(self, listener): self._listeners.append(listener) def add_raw_listener(self, raw_listener):",
"self._raw_listeners.append(raw_listener) def recieve(self, msg): for listener in self._listeners: listener(msg) packed_msg = pack_msg(msg) for",
"def __call__(self, msg): return def add_listener(self, listener): self._listeners.append(listener) def add_raw_listener(self, raw_listener): self._raw_listeners.append(raw_listener) def",
"listener): self._listeners.append(listener) def add_raw_listener(self, raw_listener): self._raw_listeners.append(raw_listener) def recieve(self, msg): for listener in self._listeners:",
"def recieve(self, msg): for listener in self._listeners: listener(msg) packed_msg = pack_msg(msg) for raw_listener",
"pack_msg class DirectReceiverMock: def __init__(self): self._listeners = [] self._raw_listeners = [] def __call__(self,",
"import pack_msg class DirectReceiverMock: def __init__(self): self._listeners = [] self._raw_listeners = [] def",
"self._listeners.append(listener) def add_raw_listener(self, raw_listener): self._raw_listeners.append(raw_listener) def recieve(self, msg): for listener in self._listeners: listener(msg)",
"raw_listener): self._raw_listeners.append(raw_listener) def recieve(self, msg): for listener in self._listeners: listener(msg) packed_msg = pack_msg(msg)",
"mite.utils import pack_msg class DirectReceiverMock: def __init__(self): self._listeners = [] self._raw_listeners = []",
"__init__(self): self._listeners = [] self._raw_listeners = [] def __call__(self, msg): return def add_listener(self,",
"[] self._raw_listeners = [] def __call__(self, msg): return def add_listener(self, listener): self._listeners.append(listener) def",
"self._raw_listeners = [] def __call__(self, msg): return def add_listener(self, listener): self._listeners.append(listener) def add_raw_listener(self,",
"for listener in self._listeners: listener(msg) packed_msg = pack_msg(msg) for raw_listener in self._raw_listeners: raw_listener(packed_msg)",
"def add_raw_listener(self, raw_listener): self._raw_listeners.append(raw_listener) def recieve(self, msg): for listener in self._listeners: listener(msg) packed_msg",
"DirectReceiverMock: def __init__(self): self._listeners = [] self._raw_listeners = [] def __call__(self, msg): return",
"__call__(self, msg): return def add_listener(self, listener): self._listeners.append(listener) def add_raw_listener(self, raw_listener): self._raw_listeners.append(raw_listener) def recieve(self,",
"add_raw_listener(self, raw_listener): self._raw_listeners.append(raw_listener) def recieve(self, msg): for listener in self._listeners: listener(msg) packed_msg =",
"recieve(self, msg): for listener in self._listeners: listener(msg) packed_msg = pack_msg(msg) for raw_listener in",
"add_listener(self, listener): self._listeners.append(listener) def add_raw_listener(self, raw_listener): self._raw_listeners.append(raw_listener) def recieve(self, msg): for listener in",
"return def add_listener(self, listener): self._listeners.append(listener) def add_raw_listener(self, raw_listener): self._raw_listeners.append(raw_listener) def recieve(self, msg): for"
] |
[
"\"\" self.initbar() def initbar(self): print((\"{0:143}{1}\").format(\"[\",\"]\")) def terminal_length(self): cols,rows = os.get_terminal_size() return cols def",
"class Progressbar(): def __init__(self): self.line = \"\" self.arrow = \"\" self.initbar() def initbar(self):",
"cols def update(self): self.line += \"=\" self.arrow = \">\" print(\"{0}{1}{2:{l}}{3}\".format(\"[\", self.line, self.arrow, \"]\",l",
"self.line += \"=\" self.arrow = \">\" print(\"{0}{1}{2:{l}}{3}\".format(\"[\", self.line, self.arrow, \"]\",l = 140 -",
"#!/usr/bin/env python3 import time, subprocess,os class Progressbar(): def __init__(self): self.line = \"\" self.arrow",
"print((\"{0:143}{1}\").format(\"[\",\"]\")) def terminal_length(self): cols,rows = os.get_terminal_size() return cols def update(self): self.line += \"=\"",
"self.arrow, \"]\",l = 140 - len(self.line))) bar = Progressbar() for i in range(1,140):",
"= os.get_terminal_size() return cols def update(self): self.line += \"=\" self.arrow = \">\" print(\"{0}{1}{2:{l}}{3}\".format(\"[\",",
"def initbar(self): print((\"{0:143}{1}\").format(\"[\",\"]\")) def terminal_length(self): cols,rows = os.get_terminal_size() return cols def update(self): self.line",
"python3 import time, subprocess,os class Progressbar(): def __init__(self): self.line = \"\" self.arrow =",
"self.arrow = \">\" print(\"{0}{1}{2:{l}}{3}\".format(\"[\", self.line, self.arrow, \"]\",l = 140 - len(self.line))) bar =",
"return cols def update(self): self.line += \"=\" self.arrow = \">\" print(\"{0}{1}{2:{l}}{3}\".format(\"[\", self.line, self.arrow,",
"= \"\" self.arrow = \"\" self.initbar() def initbar(self): print((\"{0:143}{1}\").format(\"[\",\"]\")) def terminal_length(self): cols,rows =",
"self.initbar() def initbar(self): print((\"{0:143}{1}\").format(\"[\",\"]\")) def terminal_length(self): cols,rows = os.get_terminal_size() return cols def update(self):",
"def __init__(self): self.line = \"\" self.arrow = \"\" self.initbar() def initbar(self): print((\"{0:143}{1}\").format(\"[\",\"]\")) def",
"self.line = \"\" self.arrow = \"\" self.initbar() def initbar(self): print((\"{0:143}{1}\").format(\"[\",\"]\")) def terminal_length(self): cols,rows",
"= 140 - len(self.line))) bar = Progressbar() for i in range(1,140): subprocess.call([\"clear\"]) #",
"terminal_length(self): cols,rows = os.get_terminal_size() return cols def update(self): self.line += \"=\" self.arrow =",
"print(\"{0}{1}{2:{l}}{3}\".format(\"[\", self.line, self.arrow, \"]\",l = 140 - len(self.line))) bar = Progressbar() for i",
"\">\" print(\"{0}{1}{2:{l}}{3}\".format(\"[\", self.line, self.arrow, \"]\",l = 140 - len(self.line))) bar = Progressbar() for",
"- len(self.line))) bar = Progressbar() for i in range(1,140): subprocess.call([\"clear\"]) # print(i) bar.update()",
"\"=\" self.arrow = \">\" print(\"{0}{1}{2:{l}}{3}\".format(\"[\", self.line, self.arrow, \"]\",l = 140 - len(self.line))) bar",
"140 - len(self.line))) bar = Progressbar() for i in range(1,140): subprocess.call([\"clear\"]) # print(i)",
"import time, subprocess,os class Progressbar(): def __init__(self): self.line = \"\" self.arrow = \"\"",
"def update(self): self.line += \"=\" self.arrow = \">\" print(\"{0}{1}{2:{l}}{3}\".format(\"[\", self.line, self.arrow, \"]\",l =",
"def terminal_length(self): cols,rows = os.get_terminal_size() return cols def update(self): self.line += \"=\" self.arrow",
"Progressbar(): def __init__(self): self.line = \"\" self.arrow = \"\" self.initbar() def initbar(self): print((\"{0:143}{1}\").format(\"[\",\"]\"))",
"self.line, self.arrow, \"]\",l = 140 - len(self.line))) bar = Progressbar() for i in",
"len(self.line))) bar = Progressbar() for i in range(1,140): subprocess.call([\"clear\"]) # print(i) bar.update() time.sleep(0.02)",
"cols,rows = os.get_terminal_size() return cols def update(self): self.line += \"=\" self.arrow = \">\"",
"<gh_stars>0 #!/usr/bin/env python3 import time, subprocess,os class Progressbar(): def __init__(self): self.line = \"\"",
"__init__(self): self.line = \"\" self.arrow = \"\" self.initbar() def initbar(self): print((\"{0:143}{1}\").format(\"[\",\"]\")) def terminal_length(self):",
"\"\" self.arrow = \"\" self.initbar() def initbar(self): print((\"{0:143}{1}\").format(\"[\",\"]\")) def terminal_length(self): cols,rows = os.get_terminal_size()",
"self.arrow = \"\" self.initbar() def initbar(self): print((\"{0:143}{1}\").format(\"[\",\"]\")) def terminal_length(self): cols,rows = os.get_terminal_size() return",
"\"]\",l = 140 - len(self.line))) bar = Progressbar() for i in range(1,140): subprocess.call([\"clear\"])",
"os.get_terminal_size() return cols def update(self): self.line += \"=\" self.arrow = \">\" print(\"{0}{1}{2:{l}}{3}\".format(\"[\", self.line,",
"initbar(self): print((\"{0:143}{1}\").format(\"[\",\"]\")) def terminal_length(self): cols,rows = os.get_terminal_size() return cols def update(self): self.line +=",
"+= \"=\" self.arrow = \">\" print(\"{0}{1}{2:{l}}{3}\".format(\"[\", self.line, self.arrow, \"]\",l = 140 - len(self.line)))",
"update(self): self.line += \"=\" self.arrow = \">\" print(\"{0}{1}{2:{l}}{3}\".format(\"[\", self.line, self.arrow, \"]\",l = 140",
"time, subprocess,os class Progressbar(): def __init__(self): self.line = \"\" self.arrow = \"\" self.initbar()",
"= \">\" print(\"{0}{1}{2:{l}}{3}\".format(\"[\", self.line, self.arrow, \"]\",l = 140 - len(self.line))) bar = Progressbar()",
"= \"\" self.initbar() def initbar(self): print((\"{0:143}{1}\").format(\"[\",\"]\")) def terminal_length(self): cols,rows = os.get_terminal_size() return cols",
"subprocess,os class Progressbar(): def __init__(self): self.line = \"\" self.arrow = \"\" self.initbar() def"
] |
[
"class My(object): y = 5988 class Mt(My): z = 598 class Mat(Mt): x",
"y = 5988 class Mt(My): z = 598 class Mat(Mt): x = 54",
"My(object): y = 5988 class Mt(My): z = 598 class Mat(Mt): x =",
"= 5988 class Mt(My): z = 598 class Mat(Mt): x = 54 p1=Mat()",
"Mt(My): z = 598 class Mat(Mt): x = 54 p1=Mat() print(p1.x) print(p1.y) print(p1.z)",
"5988 class Mt(My): z = 598 class Mat(Mt): x = 54 p1=Mat() print(p1.x)",
"class Mt(My): z = 598 class Mat(Mt): x = 54 p1=Mat() print(p1.x) print(p1.y)"
] |
[
"{'tag': 'tag3'}) ok_('Test event' not in response.content) ok_('Second test event' in response.content) response",
"self.client.get(url, {'tag': ['tag1', 'tag3']}) ok_('Test event' in response.content) ok_('Second test event' in response.content)",
"['tag1', 'tag3']}) ok_('Test event' in response.content) ok_('Second test event' in response.content) response =",
"event = Event.objects.get(title='Test event') group = Group.objects.get() approval = Approval(event=event, group=group) approval.save() event_page",
"start_time=event1.start_time, archive_time=event1.archive_time, public=True, status=event1.status, placeholder_img=event1.placeholder_img, ) eq_(Event.objects.approved().count(), 2) eq_(Event.objects.archived().count(), 2) tag1 = Tag.objects.create(name='tag1')",
"ok_('not scheduled' in response_fail.content) def test_old_slug(self): \"\"\"An old slug will redirect properly to",
"response.content) response = self.client.get(url, {'tag': 'tag2'}) ok_('Test event' in response.content) ok_('Second test event'",
"here. Lorem Ipsum is simply dummy text of the printing and typesetting industry.",
"event') group = Group.objects.get() approval = Approval(event=event, group=group) approval.save() event_page = reverse('main:event', kwargs={'slug':",
"respond successfully.\"\"\" participant = Participant.objects.get(name='<NAME>') participant_page = reverse('main:participant', kwargs={'slug': participant.slug}) response_ok = self.client.get(participant_page)",
"cache clear!' event_change.save() response_changed = self.client.get(reverse('main:calendar')) ok_(response_changed.content != response_public.content) ok_('cache clear' in response_changed.content)",
"ok_('Second test event' not in response.content) response = self.client.get(url, {'tag': 'tag3'}) ok_('Test event'",
"scheduled' in response_fail.content) def test_old_slug(self): \"\"\"An old slug will redirect properly to the",
"= self.client.get(url, {'tag': ['tag1', 'tag3']}) ok_('Test event' in response.content) ok_('Second test event' in",
"test_old_slug(self): \"\"\"An old slug will redirect properly to the current event page.\"\"\" old_event_slug",
"= True approval.processed = True approval.save() response_ok = self.client.get(event_page) eq_(response_ok.status_code, 200) event.public =",
"in response_public.content) event.short_description = 'One-liner' event.save() response_public = self.client.get(reverse('main:calendar')) eq_(response_public.status_code, 200) ok_('Check out",
"participant clear token page changes the Participant status as expected.\"\"\" participant = Participant.objects.get(name='<NAME>')",
"test event' in response.content) response = self.client.get(url, {'tag': 'tag1'}) ok_('Test event' in response.content)",
"event') event1.status = Event.STATUS_SCHEDULED event1.start_time -= delay event1.archive_time = event1.start_time event1.save() eq_(Event.objects.approved().count(), 1)",
"= Event.objects.get(title='Test event') event.start_time = datetime.datetime.utcnow().replace(tzinfo=utc) event.archive_time = None event.save() def test_home(self): \"\"\"Index",
"= Participant.objects.get(name='<NAME>') participant.cleared = Participant.CLEARED_NO token = str(uuid.uuid4()) participant.clear_token = token participant.save() url",
"'Bogus'}) eq_(response.status_code, 301) response = self.client.get(url, {'tag': ['tag1', 'Bogus']}) eq_(response.status_code, 301) # the",
"self.client.get(participant_page) eq_(response_ok.status_code, 200) participant.cleared = Participant.CLEARED_NO participant.save() response_ok = self.client.get(participant_page) eq_(response_ok.status_code, 200) def",
"ok_('Second test event' in response.content) response = self.client.get(url, {'tag': 'tag1'}) ok_('Test event' in",
") class TestPages(TestCase): fixtures = ['airmozilla/manage/tests/main_testdata.json'] def setUp(self): # Make the fixture event",
"Participant.CLEARED_NO participant.save() response_ok = self.client.get(participant_page) eq_(response_ok.status_code, 200) def test_participant_clear(self): \"\"\"Visiting a participant clear",
"test event' in response.content) response = self.client.get(url, {'tag': 'tag2'}) ok_('Test event' in response.content)",
"= Event.objects.get(title='Test event') event.description = \"\"\" Check out the <a href=\"http://example.com\">Example</a> page and",
"old slug will redirect properly to the current event page.\"\"\" old_event_slug = EventOldSlug.objects.get(slug='test-old-slug')",
"200) response_empty_page = self.client.get(reverse('main:home', kwargs={'page': 10000})) eq_(response_empty_page.status_code, 200) def test_event(self): \"\"\"Event view page",
"response_ok = self.client.get(event_page) eq_(response_ok.status_code, 200) event.public = False event.save() response_fail = self.client.get(event_page) self.assertRedirects(response_fail,",
"response_public = self.client.get(reverse('main:calendar')) eq_(response_public.status_code, 200) ok_('LOCATION:Mountain View' in response_public.content) response_private = self.client.get(reverse('main:private_calendar')) eq_(response_private.status_code,",
"= Approval(event=event, group=group) approval.save() event_page = reverse('main:event', kwargs={'slug': event.slug}) response_fail_approval = self.client.get(event_page) eq_(response_fail_approval.status_code,",
"eq_(participant.cleared, Participant.CLEARED_YES) def test_calendars(self): \"\"\"Calendars respond successfully.\"\"\" response_public = self.client.get(reverse('main:calendar')) eq_(response_public.status_code, 200) ok_('LOCATION:Mountain",
"response = self.client.get(url, {'tag': ['tag1', 'tag3']}) ok_('Test event' in response.content) ok_('Second test event'",
"it to make a type specimen book. If the text is getting really",
"import ( Approval, Event, EventOldSlug, Participant, Tag ) class TestPages(TestCase): fixtures = ['airmozilla/manage/tests/main_testdata.json']",
"in response.content) response = self.client.get(url, {'tag': ['tag1', 'tag3']}) ok_('Test event' in response.content) ok_('Second",
"Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem",
"= Participant.objects.get(name='<NAME>') eq_(participant.clear_token, '') eq_(participant.cleared, Participant.CLEARED_YES) def test_calendars(self): \"\"\"Calendars respond successfully.\"\"\" response_public =",
"the fixture event live as of the test. event = Event.objects.get(title='Test event') event.start_time",
"= self.client.get(url, {'tag': 'tag1'}) ok_('Test event' in response.content) ok_('Second test event' not in",
"Event.objects.get(title='Test event') group = Group.objects.get() approval = Approval(event=event, group=group) approval.save() event_page = reverse('main:event',",
"kwargs={'slug': old_event_slug.slug}) ) self.assertRedirects( response, reverse('main:event', kwargs={'slug': old_event_slug.event.slug}) ) def test_participant(self): \"\"\"Participant pages",
"both events appear response = self.client.get(url) ok_('Test event' in response.content) ok_('Second test event'",
"{'tag': ['tag1', 'Bogus']}) eq_(response.status_code, 301) # the good tag stays ok_('?tag=tag1' in response['Location'])",
"Event, EventOldSlug, Participant, Tag ) class TestPages(TestCase): fixtures = ['airmozilla/manage/tests/main_testdata.json'] def setUp(self): #",
"kwargs={'clear_token': token}) response_ok = self.client.get(url) eq_(response_ok.status_code, 200) response_changed = self.client.post(url) eq_(response_changed.status_code, 200) participant",
"= True approval.save() response_ok = self.client.get(event_page) eq_(response_ok.status_code, 200) event.public = False event.save() response_fail",
"and scrambled it to make a type specimen book. If the text is",
"eq_(response_ok.status_code, 200) response_changed = self.client.post(url) eq_(response_changed.status_code, 200) participant = Participant.objects.get(name='<NAME>') eq_(participant.clear_token, '') eq_(participant.cleared,",
"pages always respond successfully.\"\"\" participant = Participant.objects.get(name='<NAME>') participant_page = reverse('main:participant', kwargs={'slug': participant.slug}) response_ok",
"eq_(response_ok.status_code, 200) participant.cleared = Participant.CLEARED_NO participant.save() response_ok = self.client.get(participant_page) eq_(response_ok.status_code, 200) def test_participant_clear(self):",
"event1.status = Event.STATUS_SCHEDULED event1.start_time -= delay event1.archive_time = event1.start_time event1.save() eq_(Event.objects.approved().count(), 1) eq_(Event.objects.archived().count(),",
"kwargs={'page': 10000})) eq_(response_empty_page.status_code, 200) def test_event(self): \"\"\"Event view page loads correctly if the",
"\"\"\" Check out the <a href=\"http://example.com\">Example</a> page and <strong>THIS PAGE</strong> here. Lorem Ipsum",
"of the test. event = Event.objects.get(title='Test event') event.start_time = datetime.datetime.utcnow().replace(tzinfo=utc) event.archive_time = None",
"placeholder_img=event1.placeholder_img, ) eq_(Event.objects.approved().count(), 2) eq_(Event.objects.archived().count(), 2) tag1 = Tag.objects.create(name='tag1') tag2 = Tag.objects.create(name='tag2') tag3",
"request a login otherwise.\"\"\" event = Event.objects.get(title='Test event') group = Group.objects.get() approval =",
"self.client.post(url) eq_(response_changed.status_code, 200) participant = Participant.objects.get(name='<NAME>') eq_(participant.clear_token, '') eq_(participant.cleared, Participant.CLEARED_YES) def test_calendars(self): \"\"\"Calendars",
"printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text",
"the industry's standard dummy text ever since the 1500s, when an unknown printer",
"slug will redirect properly to the current event page.\"\"\" old_event_slug = EventOldSlug.objects.get(slug='test-old-slug') response",
"a participant clear token page changes the Participant status as expected.\"\"\" participant =",
"successfully.\"\"\" response_public = self.client.get(reverse('main:calendar')) eq_(response_public.status_code, 200) ok_('LOCATION:Mountain View' in response_public.content) response_private = self.client.get(reverse('main:private_calendar'))",
"= self.client.get(event_page) self.assertRedirects(response_fail, reverse('main:login')) event.public = True event.status = Event.STATUS_INITIATED event.save() response_fail =",
"datetime.datetime.utcnow().replace(tzinfo=utc) event.archive_time = None event.save() def test_home(self): \"\"\"Index page loads and paginates correctly.\"\"\"",
"# Cache tests event_change = Event.objects.get(id=22) event_change.title = 'Hello cache clear!' event_change.save() response_changed",
"the current event page.\"\"\" old_event_slug = EventOldSlug.objects.get(slug='test-old-slug') response = self.client.get( reverse('main:event', kwargs={'slug': old_event_slug.slug})",
"= Group.objects.get() approval = Approval(event=event, group=group) approval.save() event_page = reverse('main:event', kwargs={'slug': event.slug}) response_fail_approval",
"of type and scrambled it to make a type specimen book. If the",
"class TestPages(TestCase): fixtures = ['airmozilla/manage/tests/main_testdata.json'] def setUp(self): # Make the fixture event live",
"the <a href=\"http://example.com\">Example</a> page and <strong>THIS PAGE</strong> here. Lorem Ipsum is simply dummy",
"2) eq_(Event.objects.archived().count(), 2) tag1 = Tag.objects.create(name='tag1') tag2 = Tag.objects.create(name='tag2') tag3 = Tag.objects.create(name='tag3') event1.tags.add(tag1)",
"as expected.\"\"\" participant = Participant.objects.get(name='<NAME>') participant.cleared = Participant.CLEARED_NO token = str(uuid.uuid4()) participant.clear_token =",
"self.client.get( reverse('main:event', kwargs={'slug': old_event_slug.slug}) ) self.assertRedirects( response, reverse('main:event', kwargs={'slug': old_event_slug.event.slug}) ) def test_participant(self):",
"= self.client.get( reverse('main:event', kwargs={'slug': old_event_slug.slug}) ) self.assertRedirects( response, reverse('main:event', kwargs={'slug': old_event_slug.event.slug}) ) def",
"the' not in response_public.content) ok_('One-liner' in response_public.content) def test_filter_by_tags(self): url = reverse('main:home') delay",
"View' in response_public.content) response_private = self.client.get(reverse('main:private_calendar')) eq_(response_private.status_code, 200) # Cache tests event_change =",
"self.client.get(reverse('main:home')) eq_(response.status_code, 200) response_empty_page = self.client.get(reverse('main:home', kwargs={'page': 10000})) eq_(response_empty_page.status_code, 200) def test_event(self): \"\"\"Event",
"event.save() response_public = self.client.get(reverse('main:calendar')) eq_(response_public.status_code, 200) ok_('Check out the' not in response_public.content) ok_('One-liner'",
"ok_('Check out the Example page' in response_public.content) ok_('and THIS PAGE here' in response_public.content)",
"Participant.CLEARED_NO token = str(uuid.uuid4()) participant.clear_token = token participant.save() url = reverse('main:participant_clear', kwargs={'clear_token': token})",
"def test_event(self): \"\"\"Event view page loads correctly if the event is public and",
"= str(uuid.uuid4()) participant.clear_token = token participant.save() url = reverse('main:participant_clear', kwargs={'clear_token': token}) response_ok =",
"in response_public.content) def test_filter_by_tags(self): url = reverse('main:home') delay = datetime.timedelta(days=1) event1 = Event.objects.get(title='Test",
"Tag ) class TestPages(TestCase): fixtures = ['airmozilla/manage/tests/main_testdata.json'] def setUp(self): # Make the fixture",
"['airmozilla/manage/tests/main_testdata.json'] def setUp(self): # Make the fixture event live as of the test.",
"= reverse('main:participant_clear', kwargs={'clear_token': token}) response_ok = self.client.get(url) eq_(response_ok.status_code, 200) response_changed = self.client.post(url) eq_(response_changed.status_code,",
"= self.client.get(reverse('main:calendar')) eq_(response_public.status_code, 200) ok_('LOCATION:Mountain View' in response_public.content) response_private = self.client.get(reverse('main:private_calendar')) eq_(response_private.status_code, 200)",
"scrambled it to make a type specimen book. If the text is getting",
"event2.tags.add(tag2) event2.tags.add(tag3) # check that both events appear response = self.client.get(url) ok_('Test event'",
"\"\"\"Visiting a participant clear token page changes the Participant status as expected.\"\"\" participant",
"loads correctly if the event is public and scheduled and approved; request a",
"out the' not in response_public.content) ok_('One-liner' in response_public.content) def test_filter_by_tags(self): url = reverse('main:home')",
"response_changed = self.client.get(reverse('main:calendar')) ok_(response_changed.content != response_public.content) ok_('cache clear' in response_changed.content) def test_calendars_description(self): event",
"-= delay event1.archive_time = event1.start_time event1.save() eq_(Event.objects.approved().count(), 1) eq_(Event.objects.archived().count(), 1) event2 = Event.objects.create(",
"Tag.objects.create(name='tag1') tag2 = Tag.objects.create(name='tag2') tag3 = Tag.objects.create(name='tag3') event1.tags.add(tag1) event1.tags.add(tag2) event2.tags.add(tag2) event2.tags.add(tag3) # check",
"self.client.get(url, {'tag': ['tag1', 'Bogus']}) eq_(response.status_code, 301) # the good tag stays ok_('?tag=tag1' in",
"event' in response.content) ok_('Second test event' in response.content) response = self.client.get(url, {'tag': 'Bogus'})",
"participant = Participant.objects.get(name='<NAME>') eq_(participant.clear_token, '') eq_(participant.cleared, Participant.CLEARED_YES) def test_calendars(self): \"\"\"Calendars respond successfully.\"\"\" response_public",
"type and scrambled it to make a type specimen book. If the text",
"event.slug}) response_fail_approval = self.client.get(event_page) eq_(response_fail_approval.status_code, 200) ok_('not approved' in response_fail_approval.content) approval.approved = True",
"live as of the test. event = Event.objects.get(title='Test event') event.start_time = datetime.datetime.utcnow().replace(tzinfo=utc) event.archive_time",
"response_ok = self.client.get(participant_page) eq_(response_ok.status_code, 200) participant.cleared = Participant.CLEARED_NO participant.save() response_ok = self.client.get(participant_page) eq_(response_ok.status_code,",
"funfactory.urlresolvers import reverse from nose.tools import eq_, ok_ from airmozilla.main.models import ( Approval,",
"paginates correctly.\"\"\" response = self.client.get(reverse('main:home')) eq_(response.status_code, 200) response_empty_page = self.client.get(reverse('main:home', kwargs={'page': 10000})) eq_(response_empty_page.status_code,",
"response.content) ok_('Second test event' in response.content) response = self.client.get(url, {'tag': 'tag1'}) ok_('Test event'",
"not in response.content) ok_('Second test event' in response.content) response = self.client.get(url, {'tag': ['tag1',",
"Participant.CLEARED_YES) def test_calendars(self): \"\"\"Calendars respond successfully.\"\"\" response_public = self.client.get(reverse('main:calendar')) eq_(response_public.status_code, 200) ok_('LOCATION:Mountain View'",
"test_participant_clear(self): \"\"\"Visiting a participant clear token page changes the Participant status as expected.\"\"\"",
"successfully.\"\"\" participant = Participant.objects.get(name='<NAME>') participant_page = reverse('main:participant', kwargs={'slug': participant.slug}) response_ok = self.client.get(participant_page) eq_(response_ok.status_code,",
"from django.contrib.auth.models import Group from django.test import TestCase from django.utils.timezone import utc from",
"reverse('main:login')) event.public = True event.status = Event.STATUS_INITIATED event.save() response_fail = self.client.get(event_page) eq_(response_fail.status_code, 200)",
"in response.content) ok_('Second test event' in response.content) response = self.client.get(url, {'tag': 'tag1'}) ok_('Test",
"Tag.objects.create(name='tag2') tag3 = Tag.objects.create(name='tag3') event1.tags.add(tag1) event1.tags.add(tag2) event2.tags.add(tag2) event2.tags.add(tag3) # check that both events",
"import eq_, ok_ from airmozilla.main.models import ( Approval, Event, EventOldSlug, Participant, Tag )",
"participant = Participant.objects.get(name='<NAME>') participant_page = reverse('main:participant', kwargs={'slug': participant.slug}) response_ok = self.client.get(participant_page) eq_(response_ok.status_code, 200)",
"from funfactory.urlresolvers import reverse from nose.tools import eq_, ok_ from airmozilla.main.models import (",
"kwargs={'slug': old_event_slug.event.slug}) ) def test_participant(self): \"\"\"Participant pages always respond successfully.\"\"\" participant = Participant.objects.get(name='<NAME>')",
"= Participant.CLEARED_NO participant.save() response_ok = self.client.get(participant_page) eq_(response_ok.status_code, 200) def test_participant_clear(self): \"\"\"Visiting a participant",
"response_public.content) response_private = self.client.get(reverse('main:private_calendar')) eq_(response_private.status_code, 200) # Cache tests event_change = Event.objects.get(id=22) event_change.title",
"events appear response = self.client.get(url) ok_('Test event' in response.content) ok_('Second test event' in",
"self.client.get(reverse('main:home', kwargs={'page': 10000})) eq_(response_empty_page.status_code, 200) def test_event(self): \"\"\"Event view page loads correctly if",
"page changes the Participant status as expected.\"\"\" participant = Participant.objects.get(name='<NAME>') participant.cleared = Participant.CLEARED_NO",
"True approval.processed = True approval.save() response_ok = self.client.get(event_page) eq_(response_ok.status_code, 200) event.public = False",
"response_fail = self.client.get(event_page) self.assertRedirects(response_fail, reverse('main:login')) event.public = True event.status = Event.STATUS_INITIATED event.save() response_fail",
"event1.tags.add(tag2) event2.tags.add(tag2) event2.tags.add(tag3) # check that both events appear response = self.client.get(url) ok_('Test",
"import reverse from nose.tools import eq_, ok_ from airmozilla.main.models import ( Approval, Event,",
"event.save() response_fail = self.client.get(event_page) self.assertRedirects(response_fail, reverse('main:login')) event.public = True event.status = Event.STATUS_INITIATED event.save()",
"response_empty_page = self.client.get(reverse('main:home', kwargs={'page': 10000})) eq_(response_empty_page.status_code, 200) def test_event(self): \"\"\"Event view page loads",
"approval.approved = True approval.processed = True approval.save() response_ok = self.client.get(event_page) eq_(response_ok.status_code, 200) event.public",
"airmozilla.main.models import ( Approval, Event, EventOldSlug, Participant, Tag ) class TestPages(TestCase): fixtures =",
"the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy",
"response_public.content) ok_('One-liner' in response_public.content) def test_filter_by_tags(self): url = reverse('main:home') delay = datetime.timedelta(days=1) event1",
"True event.status = Event.STATUS_INITIATED event.save() response_fail = self.client.get(event_page) eq_(response_fail.status_code, 200) ok_('not scheduled' in",
"utc from funfactory.urlresolvers import reverse from nose.tools import eq_, ok_ from airmozilla.main.models import",
"event.save() response_public = self.client.get(reverse('main:calendar')) eq_(response_public.status_code, 200) ok_('Check out the Example page' in response_public.content)",
"specimen book. If the text is getting really long it will be truncated.",
"a type specimen book. If the text is getting really long it will",
"and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever",
"response_ok = self.client.get(participant_page) eq_(response_ok.status_code, 200) def test_participant_clear(self): \"\"\"Visiting a participant clear token page",
"= self.client.get(reverse('main:home')) eq_(response.status_code, 200) response_empty_page = self.client.get(reverse('main:home', kwargs={'page': 10000})) eq_(response_empty_page.status_code, 200) def test_event(self):",
"in response.content) ok_('Second test event' in response.content) response = self.client.get(url, {'tag': 'Bogus'}) eq_(response.status_code,",
"ok_(response_changed.content != response_public.content) ok_('cache clear' in response_changed.content) def test_calendars_description(self): event = Event.objects.get(title='Test event')",
"( Approval, Event, EventOldSlug, Participant, Tag ) class TestPages(TestCase): fixtures = ['airmozilla/manage/tests/main_testdata.json'] def",
"eq_(response_ok.status_code, 200) def test_participant_clear(self): \"\"\"Visiting a participant clear token page changes the Participant",
"response_changed.content) def test_calendars_description(self): event = Event.objects.get(title='Test event') event.description = \"\"\" Check out the",
"not in response.content) response = self.client.get(url, {'tag': 'tag3'}) ok_('Test event' not in response.content)",
"EventOldSlug.objects.get(slug='test-old-slug') response = self.client.get( reverse('main:event', kwargs={'slug': old_event_slug.slug}) ) self.assertRedirects( response, reverse('main:event', kwargs={'slug': old_event_slug.event.slug})",
"ok_('Second test event' in response.content) response = self.client.get(url, {'tag': 'tag2'}) ok_('Test event' in",
"def test_participant(self): \"\"\"Participant pages always respond successfully.\"\"\" participant = Participant.objects.get(name='<NAME>') participant_page = reverse('main:participant',",
"eq_(response_empty_page.status_code, 200) def test_event(self): \"\"\"Event view page loads correctly if the event is",
"test_event(self): \"\"\"Event view page loads correctly if the event is public and scheduled",
"response = self.client.get(url, {'tag': 'tag1'}) ok_('Test event' in response.content) ok_('Second test event' not",
"response.content) response = self.client.get(url, {'tag': 'Bogus'}) eq_(response.status_code, 301) response = self.client.get(url, {'tag': ['tag1',",
"self.client.get(participant_page) eq_(response_ok.status_code, 200) def test_participant_clear(self): \"\"\"Visiting a participant clear token page changes the",
"loads and paginates correctly.\"\"\" response = self.client.get(reverse('main:home')) eq_(response.status_code, 200) response_empty_page = self.client.get(reverse('main:home', kwargs={'page':",
"truncated. \"\"\".strip() event.save() response_public = self.client.get(reverse('main:calendar')) eq_(response_public.status_code, 200) ok_('Check out the Example page'",
"eq_(Event.objects.approved().count(), 2) eq_(Event.objects.archived().count(), 2) tag1 = Tag.objects.create(name='tag1') tag2 = Tag.objects.create(name='tag2') tag3 = Tag.objects.create(name='tag3')",
"\"\"\"An old slug will redirect properly to the current event page.\"\"\" old_event_slug =",
"# Make the fixture event live as of the test. event = Event.objects.get(title='Test",
"ok_('LOCATION:Mountain View' in response_public.content) response_private = self.client.get(reverse('main:private_calendar')) eq_(response_private.status_code, 200) # Cache tests event_change",
"approval = Approval(event=event, group=group) approval.save() event_page = reverse('main:event', kwargs={'slug': event.slug}) response_fail_approval = self.client.get(event_page)",
"response_changed = self.client.post(url) eq_(response_changed.status_code, 200) participant = Participant.objects.get(name='<NAME>') eq_(participant.clear_token, '') eq_(participant.cleared, Participant.CLEARED_YES) def",
"in response_public.content) ok_('and THIS PAGE here' in response_public.content) ok_('will be truncated' not in",
"200) ok_('Check out the Example page' in response_public.content) ok_('and THIS PAGE here' in",
"<filename>airmozilla/main/tests/test_views.py<gh_stars>0 import datetime import uuid from django.contrib.auth.models import Group from django.test import TestCase",
"{'tag': ['tag1', 'tag3']}) ok_('Test event' in response.content) ok_('Second test event' in response.content) response",
"!= response_public.content) ok_('cache clear' in response_changed.content) def test_calendars_description(self): event = Event.objects.get(title='Test event') event.description",
"page loads and paginates correctly.\"\"\" response = self.client.get(reverse('main:home')) eq_(response.status_code, 200) response_empty_page = self.client.get(reverse('main:home',",
"'tag3']}) ok_('Test event' in response.content) ok_('Second test event' in response.content) response = self.client.get(url,",
"= datetime.timedelta(days=1) event1 = Event.objects.get(title='Test event') event1.status = Event.STATUS_SCHEDULED event1.start_time -= delay event1.archive_time",
"check that both events appear response = self.client.get(url) ok_('Test event' in response.content) ok_('Second",
"response_fail.content) def test_old_slug(self): \"\"\"An old slug will redirect properly to the current event",
"\"\"\"Event view page loads correctly if the event is public and scheduled and",
"unknown printer took a galley of type and scrambled it to make a",
"{'tag': 'tag2'}) ok_('Test event' in response.content) ok_('Second test event' in response.content) response =",
"= self.client.post(url) eq_(response_changed.status_code, 200) participant = Participant.objects.get(name='<NAME>') eq_(participant.clear_token, '') eq_(participant.cleared, Participant.CLEARED_YES) def test_calendars(self):",
"printer took a galley of type and scrambled it to make a type",
"2) tag1 = Tag.objects.create(name='tag1') tag2 = Tag.objects.create(name='tag2') tag3 = Tag.objects.create(name='tag3') event1.tags.add(tag1) event1.tags.add(tag2) event2.tags.add(tag2)",
"PAGE</strong> here. Lorem Ipsum is simply dummy text of the printing and typesetting",
"response.content) response = self.client.get(url, {'tag': 'tag1'}) ok_('Test event' in response.content) ok_('Second test event'",
"self.client.get(url, {'tag': 'tag3'}) ok_('Test event' not in response.content) ok_('Second test event' in response.content)",
"clear token page changes the Participant status as expected.\"\"\" participant = Participant.objects.get(name='<NAME>') participant.cleared",
"response_public = self.client.get(reverse('main:calendar')) eq_(response_public.status_code, 200) ok_('Check out the' not in response_public.content) ok_('One-liner' in",
"TestCase from django.utils.timezone import utc from funfactory.urlresolvers import reverse from nose.tools import eq_,",
"'One-liner' event.save() response_public = self.client.get(reverse('main:calendar')) eq_(response_public.status_code, 200) ok_('Check out the' not in response_public.content)",
"Make the fixture event live as of the test. event = Event.objects.get(title='Test event')",
"and paginates correctly.\"\"\" response = self.client.get(reverse('main:home')) eq_(response.status_code, 200) response_empty_page = self.client.get(reverse('main:home', kwargs={'page': 10000}))",
"respond successfully.\"\"\" response_public = self.client.get(reverse('main:calendar')) eq_(response_public.status_code, 200) ok_('LOCATION:Mountain View' in response_public.content) response_private =",
"ok_('Check out the' not in response_public.content) ok_('One-liner' in response_public.content) def test_filter_by_tags(self): url =",
"public and scheduled and approved; request a login otherwise.\"\"\" event = Event.objects.get(title='Test event')",
"eq_(response_public.status_code, 200) ok_('Check out the Example page' in response_public.content) ok_('and THIS PAGE here'",
"event.public = True event.status = Event.STATUS_INITIATED event.save() response_fail = self.client.get(event_page) eq_(response_fail.status_code, 200) ok_('not",
"response = self.client.get(url, {'tag': 'tag3'}) ok_('Test event' not in response.content) ok_('Second test event'",
"approved' in response_fail_approval.content) approval.approved = True approval.processed = True approval.save() response_ok = self.client.get(event_page)",
"test_home(self): \"\"\"Index page loads and paginates correctly.\"\"\" response = self.client.get(reverse('main:home')) eq_(response.status_code, 200) response_empty_page",
"= self.client.get(event_page) eq_(response_ok.status_code, 200) event.public = False event.save() response_fail = self.client.get(event_page) self.assertRedirects(response_fail, reverse('main:login'))",
"to make a type specimen book. If the text is getting really long",
"correctly if the event is public and scheduled and approved; request a login",
"took a galley of type and scrambled it to make a type specimen",
"be truncated' not in response_public.content) event.short_description = 'One-liner' event.save() response_public = self.client.get(reverse('main:calendar')) eq_(response_public.status_code,",
"in response.content) response = self.client.get(url, {'tag': 'Bogus'}) eq_(response.status_code, 301) response = self.client.get(url, {'tag':",
"approval.save() event_page = reverse('main:event', kwargs={'slug': event.slug}) response_fail_approval = self.client.get(event_page) eq_(response_fail_approval.status_code, 200) ok_('not approved'",
"from airmozilla.main.models import ( Approval, Event, EventOldSlug, Participant, Tag ) class TestPages(TestCase): fixtures",
"event_change.save() response_changed = self.client.get(reverse('main:calendar')) ok_(response_changed.content != response_public.content) ok_('cache clear' in response_changed.content) def test_calendars_description(self):",
"= self.client.get(participant_page) eq_(response_ok.status_code, 200) participant.cleared = Participant.CLEARED_NO participant.save() response_ok = self.client.get(participant_page) eq_(response_ok.status_code, 200)",
"page and <strong>THIS PAGE</strong> here. Lorem Ipsum is simply dummy text of the",
") def test_participant(self): \"\"\"Participant pages always respond successfully.\"\"\" participant = Participant.objects.get(name='<NAME>') participant_page =",
"event is public and scheduled and approved; request a login otherwise.\"\"\" event =",
"be truncated. \"\"\".strip() event.save() response_public = self.client.get(reverse('main:calendar')) eq_(response_public.status_code, 200) ok_('Check out the Example",
"industry. Lorem Ipsum has been the industry's standard dummy text ever since the",
"= self.client.get(url, {'tag': 'Bogus'}) eq_(response.status_code, 301) response = self.client.get(url, {'tag': ['tag1', 'Bogus']}) eq_(response.status_code,",
"Event.objects.get(title='Test event') event1.status = Event.STATUS_SCHEDULED event1.start_time -= delay event1.archive_time = event1.start_time event1.save() eq_(Event.objects.approved().count(),",
"Participant, Tag ) class TestPages(TestCase): fixtures = ['airmozilla/manage/tests/main_testdata.json'] def setUp(self): # Make the",
"event.short_description = 'One-liner' event.save() response_public = self.client.get(reverse('main:calendar')) eq_(response_public.status_code, 200) ok_('Check out the' not",
"scheduled and approved; request a login otherwise.\"\"\" event = Event.objects.get(title='Test event') group =",
"event live as of the test. event = Event.objects.get(title='Test event') event.start_time = datetime.datetime.utcnow().replace(tzinfo=utc)",
"200) event.public = False event.save() response_fail = self.client.get(event_page) self.assertRedirects(response_fail, reverse('main:login')) event.public = True",
"self.client.get(reverse('main:calendar')) eq_(response_public.status_code, 200) ok_('Check out the Example page' in response_public.content) ok_('and THIS PAGE",
"ever since the 1500s, when an unknown printer took a galley of type",
"event' in response.content) response = self.client.get(url, {'tag': 'tag2'}) ok_('Test event' in response.content) ok_('Second",
"= self.client.get(url) ok_('Test event' in response.content) ok_('Second test event' in response.content) response =",
"response_public.content) def test_filter_by_tags(self): url = reverse('main:home') delay = datetime.timedelta(days=1) event1 = Event.objects.get(title='Test event')",
"THIS PAGE here' in response_public.content) ok_('will be truncated' not in response_public.content) event.short_description =",
"def test_calendars(self): \"\"\"Calendars respond successfully.\"\"\" response_public = self.client.get(reverse('main:calendar')) eq_(response_public.status_code, 200) ok_('LOCATION:Mountain View' in",
"is simply dummy text of the printing and typesetting industry. Lorem Ipsum has",
"import Group from django.test import TestCase from django.utils.timezone import utc from funfactory.urlresolvers import",
"in response.content) ok_('Second test event' not in response.content) response = self.client.get(url, {'tag': 'tag3'})",
"200) response_changed = self.client.post(url) eq_(response_changed.status_code, 200) participant = Participant.objects.get(name='<NAME>') eq_(participant.clear_token, '') eq_(participant.cleared, Participant.CLEARED_YES)",
"in response.content) ok_('Second test event' in response.content) response = self.client.get(url, {'tag': 'tag2'}) ok_('Test",
"page loads correctly if the event is public and scheduled and approved; request",
"Example page' in response_public.content) ok_('and THIS PAGE here' in response_public.content) ok_('will be truncated'",
"event2 = Event.objects.create( title='Second test event', description='Anything', start_time=event1.start_time, archive_time=event1.archive_time, public=True, status=event1.status, placeholder_img=event1.placeholder_img, )",
"test_calendars_description(self): event = Event.objects.get(title='Test event') event.description = \"\"\" Check out the <a href=\"http://example.com\">Example</a>",
"Event.objects.get(title='Test event') event.description = \"\"\" Check out the <a href=\"http://example.com\">Example</a> page and <strong>THIS",
"make a type specimen book. If the text is getting really long it",
"the test. event = Event.objects.get(title='Test event') event.start_time = datetime.datetime.utcnow().replace(tzinfo=utc) event.archive_time = None event.save()",
"= self.client.get(reverse('main:calendar')) ok_(response_changed.content != response_public.content) ok_('cache clear' in response_changed.content) def test_calendars_description(self): event =",
"in response_public.content) ok_('will be truncated' not in response_public.content) event.short_description = 'One-liner' event.save() response_public",
"event_change = Event.objects.get(id=22) event_change.title = 'Hello cache clear!' event_change.save() response_changed = self.client.get(reverse('main:calendar')) ok_(response_changed.content",
"<strong>THIS PAGE</strong> here. Lorem Ipsum is simply dummy text of the printing and",
"= self.client.get(reverse('main:home', kwargs={'page': 10000})) eq_(response_empty_page.status_code, 200) def test_event(self): \"\"\"Event view page loads correctly",
"view page loads correctly if the event is public and scheduled and approved;",
"group = Group.objects.get() approval = Approval(event=event, group=group) approval.save() event_page = reverse('main:event', kwargs={'slug': event.slug})",
"event' in response.content) response = self.client.get(url, {'tag': 'tag1'}) ok_('Test event' in response.content) ok_('Second",
"200) ok_('not scheduled' in response_fail.content) def test_old_slug(self): \"\"\"An old slug will redirect properly",
"to the current event page.\"\"\" old_event_slug = EventOldSlug.objects.get(slug='test-old-slug') response = self.client.get( reverse('main:event', kwargs={'slug':",
"url = reverse('main:home') delay = datetime.timedelta(days=1) event1 = Event.objects.get(title='Test event') event1.status = Event.STATUS_SCHEDULED",
"it will be truncated. \"\"\".strip() event.save() response_public = self.client.get(reverse('main:calendar')) eq_(response_public.status_code, 200) ok_('Check out",
"here' in response_public.content) ok_('will be truncated' not in response_public.content) event.short_description = 'One-liner' event.save()",
"django.contrib.auth.models import Group from django.test import TestCase from django.utils.timezone import utc from funfactory.urlresolvers",
"response.content) ok_('Second test event' not in response.content) response = self.client.get(url, {'tag': 'tag3'}) ok_('Test",
"tag1 = Tag.objects.create(name='tag1') tag2 = Tag.objects.create(name='tag2') tag3 = Tag.objects.create(name='tag3') event1.tags.add(tag1) event1.tags.add(tag2) event2.tags.add(tag2) event2.tags.add(tag3)",
"ok_('will be truncated' not in response_public.content) event.short_description = 'One-liner' event.save() response_public = self.client.get(reverse('main:calendar'))",
"redirect properly to the current event page.\"\"\" old_event_slug = EventOldSlug.objects.get(slug='test-old-slug') response = self.client.get(",
"kwargs={'slug': participant.slug}) response_ok = self.client.get(participant_page) eq_(response_ok.status_code, 200) participant.cleared = Participant.CLEARED_NO participant.save() response_ok =",
"ok_ from airmozilla.main.models import ( Approval, Event, EventOldSlug, Participant, Tag ) class TestPages(TestCase):",
"def test_calendars_description(self): event = Event.objects.get(title='Test event') event.description = \"\"\" Check out the <a",
"tests event_change = Event.objects.get(id=22) event_change.title = 'Hello cache clear!' event_change.save() response_changed = self.client.get(reverse('main:calendar'))",
"self.client.get(url) ok_('Test event' in response.content) ok_('Second test event' in response.content) response = self.client.get(url,",
"eq_(response.status_code, 301) response = self.client.get(url, {'tag': ['tag1', 'Bogus']}) eq_(response.status_code, 301) # the good",
"kwargs={'slug': event.slug}) response_fail_approval = self.client.get(event_page) eq_(response_fail_approval.status_code, 200) ok_('not approved' in response_fail_approval.content) approval.approved =",
"200) def test_participant_clear(self): \"\"\"Visiting a participant clear token page changes the Participant status",
"def setUp(self): # Make the fixture event live as of the test. event",
"status=event1.status, placeholder_img=event1.placeholder_img, ) eq_(Event.objects.approved().count(), 2) eq_(Event.objects.archived().count(), 2) tag1 = Tag.objects.create(name='tag1') tag2 = Tag.objects.create(name='tag2')",
"that both events appear response = self.client.get(url) ok_('Test event' in response.content) ok_('Second test",
"participant = Participant.objects.get(name='<NAME>') participant.cleared = Participant.CLEARED_NO token = str(uuid.uuid4()) participant.clear_token = token participant.save()",
"in response.content) response = self.client.get(url, {'tag': 'tag1'}) ok_('Test event' in response.content) ok_('Second test",
"response = self.client.get(reverse('main:home')) eq_(response.status_code, 200) response_empty_page = self.client.get(reverse('main:home', kwargs={'page': 10000})) eq_(response_empty_page.status_code, 200) def",
"response = self.client.get(url) ok_('Test event' in response.content) ok_('Second test event' in response.content) response",
"200) ok_('not approved' in response_fail_approval.content) approval.approved = True approval.processed = True approval.save() response_ok",
"= Event.objects.get(title='Test event') group = Group.objects.get() approval = Approval(event=event, group=group) approval.save() event_page =",
"response.content) ok_('Second test event' in response.content) response = self.client.get(url, {'tag': 'tag2'}) ok_('Test event'",
"in response_public.content) response_private = self.client.get(reverse('main:private_calendar')) eq_(response_private.status_code, 200) # Cache tests event_change = Event.objects.get(id=22)",
"event1.start_time -= delay event1.archive_time = event1.start_time event1.save() eq_(Event.objects.approved().count(), 1) eq_(Event.objects.archived().count(), 1) event2 =",
"= \"\"\" Check out the <a href=\"http://example.com\">Example</a> page and <strong>THIS PAGE</strong> here. Lorem",
"'tag3'}) ok_('Test event' not in response.content) ok_('Second test event' in response.content) response =",
"event1.tags.add(tag1) event1.tags.add(tag2) event2.tags.add(tag2) event2.tags.add(tag3) # check that both events appear response = self.client.get(url)",
"event.save() def test_home(self): \"\"\"Index page loads and paginates correctly.\"\"\" response = self.client.get(reverse('main:home')) eq_(response.status_code,",
"If the text is getting really long it will be truncated. \"\"\".strip() event.save()",
"old_event_slug = EventOldSlug.objects.get(slug='test-old-slug') response = self.client.get( reverse('main:event', kwargs={'slug': old_event_slug.slug}) ) self.assertRedirects( response, reverse('main:event',",
"response.content) ok_('Second test event' in response.content) response = self.client.get(url, {'tag': ['tag1', 'tag3']}) ok_('Test",
"login otherwise.\"\"\" event = Event.objects.get(title='Test event') group = Group.objects.get() approval = Approval(event=event, group=group)",
"event1.save() eq_(Event.objects.approved().count(), 1) eq_(Event.objects.archived().count(), 1) event2 = Event.objects.create( title='Second test event', description='Anything', start_time=event1.start_time,",
"eq_(response_ok.status_code, 200) event.public = False event.save() response_fail = self.client.get(event_page) self.assertRedirects(response_fail, reverse('main:login')) event.public =",
"text of the printing and typesetting industry. Lorem Ipsum has been the industry's",
"200) participant.cleared = Participant.CLEARED_NO participant.save() response_ok = self.client.get(participant_page) eq_(response_ok.status_code, 200) def test_participant_clear(self): \"\"\"Visiting",
"TestPages(TestCase): fixtures = ['airmozilla/manage/tests/main_testdata.json'] def setUp(self): # Make the fixture event live as",
"event1.start_time event1.save() eq_(Event.objects.approved().count(), 1) eq_(Event.objects.archived().count(), 1) event2 = Event.objects.create( title='Second test event', description='Anything',",
"fixture event live as of the test. event = Event.objects.get(title='Test event') event.start_time =",
"in response_fail.content) def test_old_slug(self): \"\"\"An old slug will redirect properly to the current",
"changes the Participant status as expected.\"\"\" participant = Participant.objects.get(name='<NAME>') participant.cleared = Participant.CLEARED_NO token",
"participant.cleared = Participant.CLEARED_NO participant.save() response_ok = self.client.get(participant_page) eq_(response_ok.status_code, 200) def test_participant_clear(self): \"\"\"Visiting a",
"public=True, status=event1.status, placeholder_img=event1.placeholder_img, ) eq_(Event.objects.approved().count(), 2) eq_(Event.objects.archived().count(), 2) tag1 = Tag.objects.create(name='tag1') tag2 =",
"current event page.\"\"\" old_event_slug = EventOldSlug.objects.get(slug='test-old-slug') response = self.client.get( reverse('main:event', kwargs={'slug': old_event_slug.slug}) )",
"\"\"\"Participant pages always respond successfully.\"\"\" participant = Participant.objects.get(name='<NAME>') participant_page = reverse('main:participant', kwargs={'slug': participant.slug})",
"301) response = self.client.get(url, {'tag': ['tag1', 'Bogus']}) eq_(response.status_code, 301) # the good tag",
"in response_fail_approval.content) approval.approved = True approval.processed = True approval.save() response_ok = self.client.get(event_page) eq_(response_ok.status_code,",
"self.client.get(reverse('main:calendar')) eq_(response_public.status_code, 200) ok_('LOCATION:Mountain View' in response_public.content) response_private = self.client.get(reverse('main:private_calendar')) eq_(response_private.status_code, 200) #",
"import datetime import uuid from django.contrib.auth.models import Group from django.test import TestCase from",
"= 'One-liner' event.save() response_public = self.client.get(reverse('main:calendar')) eq_(response_public.status_code, 200) ok_('Check out the' not in",
"response_fail_approval.content) approval.approved = True approval.processed = True approval.save() response_ok = self.client.get(event_page) eq_(response_ok.status_code, 200)",
"clear' in response_changed.content) def test_calendars_description(self): event = Event.objects.get(title='Test event') event.description = \"\"\" Check",
"def test_filter_by_tags(self): url = reverse('main:home') delay = datetime.timedelta(days=1) event1 = Event.objects.get(title='Test event') event1.status",
"since the 1500s, when an unknown printer took a galley of type and",
"= self.client.get(url, {'tag': ['tag1', 'Bogus']}) eq_(response.status_code, 301) # the good tag stays ok_('?tag=tag1'",
"getting really long it will be truncated. \"\"\".strip() event.save() response_public = self.client.get(reverse('main:calendar')) eq_(response_public.status_code,",
"event1.archive_time = event1.start_time event1.save() eq_(Event.objects.approved().count(), 1) eq_(Event.objects.archived().count(), 1) event2 = Event.objects.create( title='Second test",
"appear response = self.client.get(url) ok_('Test event' in response.content) ok_('Second test event' in response.content)",
"True approval.save() response_ok = self.client.get(event_page) eq_(response_ok.status_code, 200) event.public = False event.save() response_fail =",
"Ipsum has been the industry's standard dummy text ever since the 1500s, when",
"not in response_public.content) event.short_description = 'One-liner' event.save() response_public = self.client.get(reverse('main:calendar')) eq_(response_public.status_code, 200) ok_('Check",
"response_public.content) event.short_description = 'One-liner' event.save() response_public = self.client.get(reverse('main:calendar')) eq_(response_public.status_code, 200) ok_('Check out the'",
"really long it will be truncated. \"\"\".strip() event.save() response_public = self.client.get(reverse('main:calendar')) eq_(response_public.status_code, 200)",
"when an unknown printer took a galley of type and scrambled it to",
"will be truncated. \"\"\".strip() event.save() response_public = self.client.get(reverse('main:calendar')) eq_(response_public.status_code, 200) ok_('Check out the",
"a galley of type and scrambled it to make a type specimen book.",
"self.client.get(reverse('main:calendar')) ok_(response_changed.content != response_public.content) ok_('cache clear' in response_changed.content) def test_calendars_description(self): event = Event.objects.get(title='Test",
"event') event.start_time = datetime.datetime.utcnow().replace(tzinfo=utc) event.archive_time = None event.save() def test_home(self): \"\"\"Index page loads",
"def test_home(self): \"\"\"Index page loads and paginates correctly.\"\"\" response = self.client.get(reverse('main:home')) eq_(response.status_code, 200)",
"def test_old_slug(self): \"\"\"An old slug will redirect properly to the current event page.\"\"\"",
"'Hello cache clear!' event_change.save() response_changed = self.client.get(reverse('main:calendar')) ok_(response_changed.content != response_public.content) ok_('cache clear' in",
"clear!' event_change.save() response_changed = self.client.get(reverse('main:calendar')) ok_(response_changed.content != response_public.content) ok_('cache clear' in response_changed.content) def",
"delay = datetime.timedelta(days=1) event1 = Event.objects.get(title='Test event') event1.status = Event.STATUS_SCHEDULED event1.start_time -= delay",
"event page.\"\"\" old_event_slug = EventOldSlug.objects.get(slug='test-old-slug') response = self.client.get( reverse('main:event', kwargs={'slug': old_event_slug.slug}) ) self.assertRedirects(",
"and scheduled and approved; request a login otherwise.\"\"\" event = Event.objects.get(title='Test event') group",
"self.client.get(event_page) eq_(response_fail.status_code, 200) ok_('not scheduled' in response_fail.content) def test_old_slug(self): \"\"\"An old slug will",
"eq_(Event.objects.approved().count(), 1) eq_(Event.objects.archived().count(), 1) event2 = Event.objects.create( title='Second test event', description='Anything', start_time=event1.start_time, archive_time=event1.archive_time,",
"event.save() response_fail = self.client.get(event_page) eq_(response_fail.status_code, 200) ok_('not scheduled' in response_fail.content) def test_old_slug(self): \"\"\"An",
"response_fail_approval = self.client.get(event_page) eq_(response_fail_approval.status_code, 200) ok_('not approved' in response_fail_approval.content) approval.approved = True approval.processed",
"= Tag.objects.create(name='tag3') event1.tags.add(tag1) event1.tags.add(tag2) event2.tags.add(tag2) event2.tags.add(tag3) # check that both events appear response",
"200) def test_event(self): \"\"\"Event view page loads correctly if the event is public",
"= self.client.get(reverse('main:calendar')) eq_(response_public.status_code, 200) ok_('Check out the' not in response_public.content) ok_('One-liner' in response_public.content)",
"galley of type and scrambled it to make a type specimen book. If",
"event = Event.objects.get(title='Test event') event.description = \"\"\" Check out the <a href=\"http://example.com\">Example</a> page",
"= datetime.datetime.utcnow().replace(tzinfo=utc) event.archive_time = None event.save() def test_home(self): \"\"\"Index page loads and paginates",
"event = Event.objects.get(title='Test event') event.start_time = datetime.datetime.utcnow().replace(tzinfo=utc) event.archive_time = None event.save() def test_home(self):",
"will redirect properly to the current event page.\"\"\" old_event_slug = EventOldSlug.objects.get(slug='test-old-slug') response =",
"eq_(response_public.status_code, 200) ok_('Check out the' not in response_public.content) ok_('One-liner' in response_public.content) def test_filter_by_tags(self):",
"event2.tags.add(tag3) # check that both events appear response = self.client.get(url) ok_('Test event' in",
"ok_('cache clear' in response_changed.content) def test_calendars_description(self): event = Event.objects.get(title='Test event') event.description = \"\"\"",
"= Event.objects.get(id=22) event_change.title = 'Hello cache clear!' event_change.save() response_changed = self.client.get(reverse('main:calendar')) ok_(response_changed.content !=",
"response_public = self.client.get(reverse('main:calendar')) eq_(response_public.status_code, 200) ok_('Check out the Example page' in response_public.content) ok_('and",
"Group.objects.get() approval = Approval(event=event, group=group) approval.save() event_page = reverse('main:event', kwargs={'slug': event.slug}) response_fail_approval =",
"nose.tools import eq_, ok_ from airmozilla.main.models import ( Approval, Event, EventOldSlug, Participant, Tag",
"token participant.save() url = reverse('main:participant_clear', kwargs={'clear_token': token}) response_ok = self.client.get(url) eq_(response_ok.status_code, 200) response_changed",
"long it will be truncated. \"\"\".strip() event.save() response_public = self.client.get(reverse('main:calendar')) eq_(response_public.status_code, 200) ok_('Check",
"response_public.content) ok_('and THIS PAGE here' in response_public.content) ok_('will be truncated' not in response_public.content)",
"None event.save() def test_home(self): \"\"\"Index page loads and paginates correctly.\"\"\" response = self.client.get(reverse('main:home'))",
"Cache tests event_change = Event.objects.get(id=22) event_change.title = 'Hello cache clear!' event_change.save() response_changed =",
"self.client.get(url, {'tag': 'tag2'}) ok_('Test event' in response.content) ok_('Second test event' in response.content) response",
"Participant.objects.get(name='<NAME>') participant_page = reverse('main:participant', kwargs={'slug': participant.slug}) response_ok = self.client.get(participant_page) eq_(response_ok.status_code, 200) participant.cleared =",
"datetime.timedelta(days=1) event1 = Event.objects.get(title='Test event') event1.status = Event.STATUS_SCHEDULED event1.start_time -= delay event1.archive_time =",
"test_calendars(self): \"\"\"Calendars respond successfully.\"\"\" response_public = self.client.get(reverse('main:calendar')) eq_(response_public.status_code, 200) ok_('LOCATION:Mountain View' in response_public.content)",
"\"\"\"Calendars respond successfully.\"\"\" response_public = self.client.get(reverse('main:calendar')) eq_(response_public.status_code, 200) ok_('LOCATION:Mountain View' in response_public.content) response_private",
"event.description = \"\"\" Check out the <a href=\"http://example.com\">Example</a> page and <strong>THIS PAGE</strong> here.",
"participant.save() response_ok = self.client.get(participant_page) eq_(response_ok.status_code, 200) def test_participant_clear(self): \"\"\"Visiting a participant clear token",
"event.archive_time = None event.save() def test_home(self): \"\"\"Index page loads and paginates correctly.\"\"\" response",
"has been the industry's standard dummy text ever since the 1500s, when an",
"= False event.save() response_fail = self.client.get(event_page) self.assertRedirects(response_fail, reverse('main:login')) event.public = True event.status =",
"response = self.client.get(url, {'tag': 'Bogus'}) eq_(response.status_code, 301) response = self.client.get(url, {'tag': ['tag1', 'Bogus']})",
"event' in response.content) ok_('Second test event' in response.content) response = self.client.get(url, {'tag': 'tag1'})",
"title='Second test event', description='Anything', start_time=event1.start_time, archive_time=event1.archive_time, public=True, status=event1.status, placeholder_img=event1.placeholder_img, ) eq_(Event.objects.approved().count(), 2) eq_(Event.objects.archived().count(),",
"= self.client.get(url, {'tag': 'tag2'}) ok_('Test event' in response.content) ok_('Second test event' in response.content)",
"ok_('Test event' not in response.content) ok_('Second test event' in response.content) response = self.client.get(url,",
"been the industry's standard dummy text ever since the 1500s, when an unknown",
"test event', description='Anything', start_time=event1.start_time, archive_time=event1.archive_time, public=True, status=event1.status, placeholder_img=event1.placeholder_img, ) eq_(Event.objects.approved().count(), 2) eq_(Event.objects.archived().count(), 2)",
"ok_('and THIS PAGE here' in response_public.content) ok_('will be truncated' not in response_public.content) event.short_description",
"token}) response_ok = self.client.get(url) eq_(response_ok.status_code, 200) response_changed = self.client.post(url) eq_(response_changed.status_code, 200) participant =",
"'') eq_(participant.cleared, Participant.CLEARED_YES) def test_calendars(self): \"\"\"Calendars respond successfully.\"\"\" response_public = self.client.get(reverse('main:calendar')) eq_(response_public.status_code, 200)",
"Event.objects.get(id=22) event_change.title = 'Hello cache clear!' event_change.save() response_changed = self.client.get(reverse('main:calendar')) ok_(response_changed.content != response_public.content)",
"{'tag': 'tag1'}) ok_('Test event' in response.content) ok_('Second test event' not in response.content) response",
"of the printing and typesetting industry. Lorem Ipsum has been the industry's standard",
"= self.client.get(reverse('main:calendar')) eq_(response_public.status_code, 200) ok_('Check out the Example page' in response_public.content) ok_('and THIS",
"= reverse('main:participant', kwargs={'slug': participant.slug}) response_ok = self.client.get(participant_page) eq_(response_ok.status_code, 200) participant.cleared = Participant.CLEARED_NO participant.save()",
"response_public.content) ok_('will be truncated' not in response_public.content) event.short_description = 'One-liner' event.save() response_public =",
"Approval(event=event, group=group) approval.save() event_page = reverse('main:event', kwargs={'slug': event.slug}) response_fail_approval = self.client.get(event_page) eq_(response_fail_approval.status_code, 200)",
"self.client.get(url, {'tag': 'tag1'}) ok_('Test event' in response.content) ok_('Second test event' not in response.content)",
"1) event2 = Event.objects.create( title='Second test event', description='Anything', start_time=event1.start_time, archive_time=event1.archive_time, public=True, status=event1.status, placeholder_img=event1.placeholder_img,",
"response = self.client.get( reverse('main:event', kwargs={'slug': old_event_slug.slug}) ) self.assertRedirects( response, reverse('main:event', kwargs={'slug': old_event_slug.event.slug}) )",
"setUp(self): # Make the fixture event live as of the test. event =",
"self.assertRedirects(response_fail, reverse('main:login')) event.public = True event.status = Event.STATUS_INITIATED event.save() response_fail = self.client.get(event_page) eq_(response_fail.status_code,",
"old_event_slug.event.slug}) ) def test_participant(self): \"\"\"Participant pages always respond successfully.\"\"\" participant = Participant.objects.get(name='<NAME>') participant_page",
"from django.utils.timezone import utc from funfactory.urlresolvers import reverse from nose.tools import eq_, ok_",
"event.start_time = datetime.datetime.utcnow().replace(tzinfo=utc) event.archive_time = None event.save() def test_home(self): \"\"\"Index page loads and",
"href=\"http://example.com\">Example</a> page and <strong>THIS PAGE</strong> here. Lorem Ipsum is simply dummy text of",
"test event' in response.content) response = self.client.get(url, {'tag': 'Bogus'}) eq_(response.status_code, 301) response =",
"datetime import uuid from django.contrib.auth.models import Group from django.test import TestCase from django.utils.timezone",
"Approval, Event, EventOldSlug, Participant, Tag ) class TestPages(TestCase): fixtures = ['airmozilla/manage/tests/main_testdata.json'] def setUp(self):",
"group=group) approval.save() event_page = reverse('main:event', kwargs={'slug': event.slug}) response_fail_approval = self.client.get(event_page) eq_(response_fail_approval.status_code, 200) ok_('not",
"EventOldSlug, Participant, Tag ) class TestPages(TestCase): fixtures = ['airmozilla/manage/tests/main_testdata.json'] def setUp(self): # Make",
"dummy text ever since the 1500s, when an unknown printer took a galley",
"{'tag': 'Bogus'}) eq_(response.status_code, 301) response = self.client.get(url, {'tag': ['tag1', 'Bogus']}) eq_(response.status_code, 301) #",
"self.client.get(event_page) self.assertRedirects(response_fail, reverse('main:login')) event.public = True event.status = Event.STATUS_INITIATED event.save() response_fail = self.client.get(event_page)",
"eq_(response_changed.status_code, 200) participant = Participant.objects.get(name='<NAME>') eq_(participant.clear_token, '') eq_(participant.cleared, Participant.CLEARED_YES) def test_calendars(self): \"\"\"Calendars respond",
"ok_('Test event' in response.content) ok_('Second test event' not in response.content) response = self.client.get(url,",
"event' not in response.content) ok_('Second test event' in response.content) response = self.client.get(url, {'tag':",
"page' in response_public.content) ok_('and THIS PAGE here' in response_public.content) ok_('will be truncated' not",
"200) # Cache tests event_change = Event.objects.get(id=22) event_change.title = 'Hello cache clear!' event_change.save()",
"event' not in response.content) response = self.client.get(url, {'tag': 'tag3'}) ok_('Test event' not in",
"eq_(response.status_code, 200) response_empty_page = self.client.get(reverse('main:home', kwargs={'page': 10000})) eq_(response_empty_page.status_code, 200) def test_event(self): \"\"\"Event view",
"event') event.description = \"\"\" Check out the <a href=\"http://example.com\">Example</a> page and <strong>THIS PAGE</strong>",
"page.\"\"\" old_event_slug = EventOldSlug.objects.get(slug='test-old-slug') response = self.client.get( reverse('main:event', kwargs={'slug': old_event_slug.slug}) ) self.assertRedirects( response,",
"PAGE here' in response_public.content) ok_('will be truncated' not in response_public.content) event.short_description = 'One-liner'",
"Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum",
"django.utils.timezone import utc from funfactory.urlresolvers import reverse from nose.tools import eq_, ok_ from",
"eq_(Event.objects.archived().count(), 2) tag1 = Tag.objects.create(name='tag1') tag2 = Tag.objects.create(name='tag2') tag3 = Tag.objects.create(name='tag3') event1.tags.add(tag1) event1.tags.add(tag2)",
"event' in response.content) response = self.client.get(url, {'tag': ['tag1', 'tag3']}) ok_('Test event' in response.content)",
"in response.content) ok_('Second test event' in response.content) response = self.client.get(url, {'tag': ['tag1', 'tag3']})",
"test event' not in response.content) response = self.client.get(url, {'tag': 'tag3'}) ok_('Test event' not",
"False event.save() response_fail = self.client.get(event_page) self.assertRedirects(response_fail, reverse('main:login')) event.public = True event.status = Event.STATUS_INITIATED",
"ok_('One-liner' in response_public.content) def test_filter_by_tags(self): url = reverse('main:home') delay = datetime.timedelta(days=1) event1 =",
"Participant status as expected.\"\"\" participant = Participant.objects.get(name='<NAME>') participant.cleared = Participant.CLEARED_NO token = str(uuid.uuid4())",
"text is getting really long it will be truncated. \"\"\".strip() event.save() response_public =",
"status as expected.\"\"\" participant = Participant.objects.get(name='<NAME>') participant.cleared = Participant.CLEARED_NO token = str(uuid.uuid4()) participant.clear_token",
"participant.slug}) response_ok = self.client.get(participant_page) eq_(response_ok.status_code, 200) participant.cleared = Participant.CLEARED_NO participant.save() response_ok = self.client.get(participant_page)",
"= Participant.objects.get(name='<NAME>') participant_page = reverse('main:participant', kwargs={'slug': participant.slug}) response_ok = self.client.get(participant_page) eq_(response_ok.status_code, 200) participant.cleared",
"1) eq_(Event.objects.archived().count(), 1) event2 = Event.objects.create( title='Second test event', description='Anything', start_time=event1.start_time, archive_time=event1.archive_time, public=True,",
"self.client.get(reverse('main:private_calendar')) eq_(response_private.status_code, 200) # Cache tests event_change = Event.objects.get(id=22) event_change.title = 'Hello cache",
"in response.content) response = self.client.get(url, {'tag': 'tag3'}) ok_('Test event' not in response.content) ok_('Second",
"reverse('main:event', kwargs={'slug': old_event_slug.event.slug}) ) def test_participant(self): \"\"\"Participant pages always respond successfully.\"\"\" participant =",
"= Tag.objects.create(name='tag1') tag2 = Tag.objects.create(name='tag2') tag3 = Tag.objects.create(name='tag3') event1.tags.add(tag1) event1.tags.add(tag2) event2.tags.add(tag2) event2.tags.add(tag3) #",
"reverse('main:participant', kwargs={'slug': participant.slug}) response_ok = self.client.get(participant_page) eq_(response_ok.status_code, 200) participant.cleared = Participant.CLEARED_NO participant.save() response_ok",
"response_private = self.client.get(reverse('main:private_calendar')) eq_(response_private.status_code, 200) # Cache tests event_change = Event.objects.get(id=22) event_change.title =",
"reverse('main:event', kwargs={'slug': old_event_slug.slug}) ) self.assertRedirects( response, reverse('main:event', kwargs={'slug': old_event_slug.event.slug}) ) def test_participant(self): \"\"\"Participant",
"# check that both events appear response = self.client.get(url) ok_('Test event' in response.content)",
"dummy text of the printing and typesetting industry. Lorem Ipsum has been the",
"= Event.objects.create( title='Second test event', description='Anything', start_time=event1.start_time, archive_time=event1.archive_time, public=True, status=event1.status, placeholder_img=event1.placeholder_img, ) eq_(Event.objects.approved().count(),",
"eq_(response_fail_approval.status_code, 200) ok_('not approved' in response_fail_approval.content) approval.approved = True approval.processed = True approval.save()",
"Participant.objects.get(name='<NAME>') participant.cleared = Participant.CLEARED_NO token = str(uuid.uuid4()) participant.clear_token = token participant.save() url =",
"self.client.get(event_page) eq_(response_fail_approval.status_code, 200) ok_('not approved' in response_fail_approval.content) approval.approved = True approval.processed = True",
"self.client.get(reverse('main:calendar')) eq_(response_public.status_code, 200) ok_('Check out the' not in response_public.content) ok_('One-liner' in response_public.content) def",
"import utc from funfactory.urlresolvers import reverse from nose.tools import eq_, ok_ from airmozilla.main.models",
"Event.STATUS_INITIATED event.save() response_fail = self.client.get(event_page) eq_(response_fail.status_code, 200) ok_('not scheduled' in response_fail.content) def test_old_slug(self):",
"test_filter_by_tags(self): url = reverse('main:home') delay = datetime.timedelta(days=1) event1 = Event.objects.get(title='Test event') event1.status =",
"and approved; request a login otherwise.\"\"\" event = Event.objects.get(title='Test event') group = Group.objects.get()",
"response, reverse('main:event', kwargs={'slug': old_event_slug.event.slug}) ) def test_participant(self): \"\"\"Participant pages always respond successfully.\"\"\" participant",
"fixtures = ['airmozilla/manage/tests/main_testdata.json'] def setUp(self): # Make the fixture event live as of",
"the Example page' in response_public.content) ok_('and THIS PAGE here' in response_public.content) ok_('will be",
"= EventOldSlug.objects.get(slug='test-old-slug') response = self.client.get( reverse('main:event', kwargs={'slug': old_event_slug.slug}) ) self.assertRedirects( response, reverse('main:event', kwargs={'slug':",
"properly to the current event page.\"\"\" old_event_slug = EventOldSlug.objects.get(slug='test-old-slug') response = self.client.get( reverse('main:event',",
"the Participant status as expected.\"\"\" participant = Participant.objects.get(name='<NAME>') participant.cleared = Participant.CLEARED_NO token =",
"Group from django.test import TestCase from django.utils.timezone import utc from funfactory.urlresolvers import reverse",
"ok_('Second test event' in response.content) response = self.client.get(url, {'tag': 'Bogus'}) eq_(response.status_code, 301) response",
"approved; request a login otherwise.\"\"\" event = Event.objects.get(title='Test event') group = Group.objects.get() approval",
"event_page = reverse('main:event', kwargs={'slug': event.slug}) response_fail_approval = self.client.get(event_page) eq_(response_fail_approval.status_code, 200) ok_('not approved' in",
"Event.objects.get(title='Test event') event.start_time = datetime.datetime.utcnow().replace(tzinfo=utc) event.archive_time = None event.save() def test_home(self): \"\"\"Index page",
"url = reverse('main:participant_clear', kwargs={'clear_token': token}) response_ok = self.client.get(url) eq_(response_ok.status_code, 200) response_changed = self.client.post(url)",
"eq_, ok_ from airmozilla.main.models import ( Approval, Event, EventOldSlug, Participant, Tag ) class",
"text ever since the 1500s, when an unknown printer took a galley of",
"'tag1'}) ok_('Test event' in response.content) ok_('Second test event' not in response.content) response =",
"= reverse('main:home') delay = datetime.timedelta(days=1) event1 = Event.objects.get(title='Test event') event1.status = Event.STATUS_SCHEDULED event1.start_time",
"otherwise.\"\"\" event = Event.objects.get(title='Test event') group = Group.objects.get() approval = Approval(event=event, group=group) approval.save()",
"= True event.status = Event.STATUS_INITIATED event.save() response_fail = self.client.get(event_page) eq_(response_fail.status_code, 200) ok_('not scheduled'",
"simply dummy text of the printing and typesetting industry. Lorem Ipsum has been",
"reverse('main:participant_clear', kwargs={'clear_token': token}) response_ok = self.client.get(url) eq_(response_ok.status_code, 200) response_changed = self.client.post(url) eq_(response_changed.status_code, 200)",
"in response.content) response = self.client.get(url, {'tag': 'tag2'}) ok_('Test event' in response.content) ok_('Second test",
"200) participant = Participant.objects.get(name='<NAME>') eq_(participant.clear_token, '') eq_(participant.cleared, Participant.CLEARED_YES) def test_calendars(self): \"\"\"Calendars respond successfully.\"\"\"",
"response.content) ok_('Second test event' in response.content) response = self.client.get(url, {'tag': 'Bogus'}) eq_(response.status_code, 301)",
"standard dummy text ever since the 1500s, when an unknown printer took a",
"response = self.client.get(url, {'tag': 'tag2'}) ok_('Test event' in response.content) ok_('Second test event' in",
"\"\"\"Index page loads and paginates correctly.\"\"\" response = self.client.get(reverse('main:home')) eq_(response.status_code, 200) response_empty_page =",
"= Tag.objects.create(name='tag2') tag3 = Tag.objects.create(name='tag3') event1.tags.add(tag1) event1.tags.add(tag2) event2.tags.add(tag2) event2.tags.add(tag3) # check that both",
"= None event.save() def test_home(self): \"\"\"Index page loads and paginates correctly.\"\"\" response =",
"out the Example page' in response_public.content) ok_('and THIS PAGE here' in response_public.content) ok_('will",
"event1 = Event.objects.get(title='Test event') event1.status = Event.STATUS_SCHEDULED event1.start_time -= delay event1.archive_time = event1.start_time",
"from nose.tools import eq_, ok_ from airmozilla.main.models import ( Approval, Event, EventOldSlug, Participant,",
"1500s, when an unknown printer took a galley of type and scrambled it",
"correctly.\"\"\" response = self.client.get(reverse('main:home')) eq_(response.status_code, 200) response_empty_page = self.client.get(reverse('main:home', kwargs={'page': 10000})) eq_(response_empty_page.status_code, 200)",
"response = self.client.get(url, {'tag': ['tag1', 'Bogus']}) eq_(response.status_code, 301) # the good tag stays",
"response_ok = self.client.get(url) eq_(response_ok.status_code, 200) response_changed = self.client.post(url) eq_(response_changed.status_code, 200) participant = Participant.objects.get(name='<NAME>')",
"description='Anything', start_time=event1.start_time, archive_time=event1.archive_time, public=True, status=event1.status, placeholder_img=event1.placeholder_img, ) eq_(Event.objects.approved().count(), 2) eq_(Event.objects.archived().count(), 2) tag1 =",
"token page changes the Participant status as expected.\"\"\" participant = Participant.objects.get(name='<NAME>') participant.cleared =",
") self.assertRedirects( response, reverse('main:event', kwargs={'slug': old_event_slug.event.slug}) ) def test_participant(self): \"\"\"Participant pages always respond",
"= Event.STATUS_SCHEDULED event1.start_time -= delay event1.archive_time = event1.start_time event1.save() eq_(Event.objects.approved().count(), 1) eq_(Event.objects.archived().count(), 1)",
"import TestCase from django.utils.timezone import utc from funfactory.urlresolvers import reverse from nose.tools import",
"event.status = Event.STATUS_INITIATED event.save() response_fail = self.client.get(event_page) eq_(response_fail.status_code, 200) ok_('not scheduled' in response_fail.content)",
"= ['airmozilla/manage/tests/main_testdata.json'] def setUp(self): # Make the fixture event live as of the",
"200) ok_('LOCATION:Mountain View' in response_public.content) response_private = self.client.get(reverse('main:private_calendar')) eq_(response_private.status_code, 200) # Cache tests",
"and <strong>THIS PAGE</strong> here. Lorem Ipsum is simply dummy text of the printing",
"type specimen book. If the text is getting really long it will be",
"self.client.get(url) eq_(response_ok.status_code, 200) response_changed = self.client.post(url) eq_(response_changed.status_code, 200) participant = Participant.objects.get(name='<NAME>') eq_(participant.clear_token, '')",
"test event' in response.content) response = self.client.get(url, {'tag': ['tag1', 'tag3']}) ok_('Test event' in",
"= self.client.get(url) eq_(response_ok.status_code, 200) response_changed = self.client.post(url) eq_(response_changed.status_code, 200) participant = Participant.objects.get(name='<NAME>') eq_(participant.clear_token,",
"self.client.get(url, {'tag': 'Bogus'}) eq_(response.status_code, 301) response = self.client.get(url, {'tag': ['tag1', 'Bogus']}) eq_(response.status_code, 301)",
"= self.client.get(participant_page) eq_(response_ok.status_code, 200) def test_participant_clear(self): \"\"\"Visiting a participant clear token page changes",
"Event.STATUS_SCHEDULED event1.start_time -= delay event1.archive_time = event1.start_time event1.save() eq_(Event.objects.approved().count(), 1) eq_(Event.objects.archived().count(), 1) event2",
"= reverse('main:event', kwargs={'slug': event.slug}) response_fail_approval = self.client.get(event_page) eq_(response_fail_approval.status_code, 200) ok_('not approved' in response_fail_approval.content)",
"tag2 = Tag.objects.create(name='tag2') tag3 = Tag.objects.create(name='tag3') event1.tags.add(tag1) event1.tags.add(tag2) event2.tags.add(tag2) event2.tags.add(tag3) # check that",
"out the <a href=\"http://example.com\">Example</a> page and <strong>THIS PAGE</strong> here. Lorem Ipsum is simply",
"delay event1.archive_time = event1.start_time event1.save() eq_(Event.objects.approved().count(), 1) eq_(Event.objects.archived().count(), 1) event2 = Event.objects.create( title='Second",
"reverse('main:event', kwargs={'slug': event.slug}) response_fail_approval = self.client.get(event_page) eq_(response_fail_approval.status_code, 200) ok_('not approved' in response_fail_approval.content) approval.approved",
"= self.client.get(reverse('main:private_calendar')) eq_(response_private.status_code, 200) # Cache tests event_change = Event.objects.get(id=22) event_change.title = 'Hello",
"= Event.STATUS_INITIATED event.save() response_fail = self.client.get(event_page) eq_(response_fail.status_code, 200) ok_('not scheduled' in response_fail.content) def",
"participant_page = reverse('main:participant', kwargs={'slug': participant.slug}) response_ok = self.client.get(participant_page) eq_(response_ok.status_code, 200) participant.cleared = Participant.CLEARED_NO",
"archive_time=event1.archive_time, public=True, status=event1.status, placeholder_img=event1.placeholder_img, ) eq_(Event.objects.approved().count(), 2) eq_(Event.objects.archived().count(), 2) tag1 = Tag.objects.create(name='tag1') tag2",
"Tag.objects.create(name='tag3') event1.tags.add(tag1) event1.tags.add(tag2) event2.tags.add(tag2) event2.tags.add(tag3) # check that both events appear response =",
"typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since",
"participant.save() url = reverse('main:participant_clear', kwargs={'clear_token': token}) response_ok = self.client.get(url) eq_(response_ok.status_code, 200) response_changed =",
"eq_(participant.clear_token, '') eq_(participant.cleared, Participant.CLEARED_YES) def test_calendars(self): \"\"\"Calendars respond successfully.\"\"\" response_public = self.client.get(reverse('main:calendar')) eq_(response_public.status_code,",
"= self.client.get(event_page) eq_(response_fail_approval.status_code, 200) ok_('not approved' in response_fail_approval.content) approval.approved = True approval.processed =",
"eq_(Event.objects.archived().count(), 1) event2 = Event.objects.create( title='Second test event', description='Anything', start_time=event1.start_time, archive_time=event1.archive_time, public=True, status=event1.status,",
"response_fail = self.client.get(event_page) eq_(response_fail.status_code, 200) ok_('not scheduled' in response_fail.content) def test_old_slug(self): \"\"\"An old",
"10000})) eq_(response_empty_page.status_code, 200) def test_event(self): \"\"\"Event view page loads correctly if the event",
"self.client.get(event_page) eq_(response_ok.status_code, 200) event.public = False event.save() response_fail = self.client.get(event_page) self.assertRedirects(response_fail, reverse('main:login')) event.public",
"def test_participant_clear(self): \"\"\"Visiting a participant clear token page changes the Participant status as",
"import uuid from django.contrib.auth.models import Group from django.test import TestCase from django.utils.timezone import",
"in response_public.content) ok_('One-liner' in response_public.content) def test_filter_by_tags(self): url = reverse('main:home') delay = datetime.timedelta(days=1)",
"= self.client.get(event_page) eq_(response_fail.status_code, 200) ok_('not scheduled' in response_fail.content) def test_old_slug(self): \"\"\"An old slug",
"self.assertRedirects( response, reverse('main:event', kwargs={'slug': old_event_slug.event.slug}) ) def test_participant(self): \"\"\"Participant pages always respond successfully.\"\"\"",
"participant.cleared = Participant.CLEARED_NO token = str(uuid.uuid4()) participant.clear_token = token participant.save() url = reverse('main:participant_clear',",
"django.test import TestCase from django.utils.timezone import utc from funfactory.urlresolvers import reverse from nose.tools",
"event_change.title = 'Hello cache clear!' event_change.save() response_changed = self.client.get(reverse('main:calendar')) ok_(response_changed.content != response_public.content) ok_('cache",
"'tag2'}) ok_('Test event' in response.content) ok_('Second test event' in response.content) response = self.client.get(url,",
"Participant.objects.get(name='<NAME>') eq_(participant.clear_token, '') eq_(participant.cleared, Participant.CLEARED_YES) def test_calendars(self): \"\"\"Calendars respond successfully.\"\"\" response_public = self.client.get(reverse('main:calendar'))",
"expected.\"\"\" participant = Participant.objects.get(name='<NAME>') participant.cleared = Participant.CLEARED_NO token = str(uuid.uuid4()) participant.clear_token = token",
"Lorem Ipsum has been the industry's standard dummy text ever since the 1500s,",
"response.content) response = self.client.get(url, {'tag': 'tag3'}) ok_('Test event' not in response.content) ok_('Second test",
"Check out the <a href=\"http://example.com\">Example</a> page and <strong>THIS PAGE</strong> here. Lorem Ipsum is",
"Event.objects.create( title='Second test event', description='Anything', start_time=event1.start_time, archive_time=event1.archive_time, public=True, status=event1.status, placeholder_img=event1.placeholder_img, ) eq_(Event.objects.approved().count(), 2)",
"<a href=\"http://example.com\">Example</a> page and <strong>THIS PAGE</strong> here. Lorem Ipsum is simply dummy text",
"participant.clear_token = token participant.save() url = reverse('main:participant_clear', kwargs={'clear_token': token}) response_ok = self.client.get(url) eq_(response_ok.status_code,",
"test_participant(self): \"\"\"Participant pages always respond successfully.\"\"\" participant = Participant.objects.get(name='<NAME>') participant_page = reverse('main:participant', kwargs={'slug':",
"= Event.objects.get(title='Test event') event1.status = Event.STATUS_SCHEDULED event1.start_time -= delay event1.archive_time = event1.start_time event1.save()",
"in response_changed.content) def test_calendars_description(self): event = Event.objects.get(title='Test event') event.description = \"\"\" Check out",
"reverse('main:home') delay = datetime.timedelta(days=1) event1 = Event.objects.get(title='Test event') event1.status = Event.STATUS_SCHEDULED event1.start_time -=",
") eq_(Event.objects.approved().count(), 2) eq_(Event.objects.archived().count(), 2) tag1 = Tag.objects.create(name='tag1') tag2 = Tag.objects.create(name='tag2') tag3 =",
"not in response_public.content) ok_('One-liner' in response_public.content) def test_filter_by_tags(self): url = reverse('main:home') delay =",
"if the event is public and scheduled and approved; request a login otherwise.\"\"\"",
"str(uuid.uuid4()) participant.clear_token = token participant.save() url = reverse('main:participant_clear', kwargs={'clear_token': token}) response_ok = self.client.get(url)",
"= self.client.get(url, {'tag': 'tag3'}) ok_('Test event' not in response.content) ok_('Second test event' in",
"test. event = Event.objects.get(title='Test event') event.start_time = datetime.datetime.utcnow().replace(tzinfo=utc) event.archive_time = None event.save() def",
"approval.save() response_ok = self.client.get(event_page) eq_(response_ok.status_code, 200) event.public = False event.save() response_fail = self.client.get(event_page)",
"eq_(response_fail.status_code, 200) ok_('not scheduled' in response_fail.content) def test_old_slug(self): \"\"\"An old slug will redirect",
"eq_(response_public.status_code, 200) ok_('LOCATION:Mountain View' in response_public.content) response_private = self.client.get(reverse('main:private_calendar')) eq_(response_private.status_code, 200) # Cache",
"a login otherwise.\"\"\" event = Event.objects.get(title='Test event') group = Group.objects.get() approval = Approval(event=event,",
"book. If the text is getting really long it will be truncated. \"\"\".strip()",
"= Participant.CLEARED_NO token = str(uuid.uuid4()) participant.clear_token = token participant.save() url = reverse('main:participant_clear', kwargs={'clear_token':",
"eq_(response_private.status_code, 200) # Cache tests event_change = Event.objects.get(id=22) event_change.title = 'Hello cache clear!'",
"event.public = False event.save() response_fail = self.client.get(event_page) self.assertRedirects(response_fail, reverse('main:login')) event.public = True event.status",
"the text is getting really long it will be truncated. \"\"\".strip() event.save() response_public",
"an unknown printer took a galley of type and scrambled it to make",
"\"\"\".strip() event.save() response_public = self.client.get(reverse('main:calendar')) eq_(response_public.status_code, 200) ok_('Check out the Example page' in",
"old_event_slug.slug}) ) self.assertRedirects( response, reverse('main:event', kwargs={'slug': old_event_slug.event.slug}) ) def test_participant(self): \"\"\"Participant pages always",
"is public and scheduled and approved; request a login otherwise.\"\"\" event = Event.objects.get(title='Test",
"= 'Hello cache clear!' event_change.save() response_changed = self.client.get(reverse('main:calendar')) ok_(response_changed.content != response_public.content) ok_('cache clear'",
"truncated' not in response_public.content) event.short_description = 'One-liner' event.save() response_public = self.client.get(reverse('main:calendar')) eq_(response_public.status_code, 200)",
"ok_('Second test event' in response.content) response = self.client.get(url, {'tag': ['tag1', 'tag3']}) ok_('Test event'",
"approval.processed = True approval.save() response_ok = self.client.get(event_page) eq_(response_ok.status_code, 200) event.public = False event.save()",
"industry's standard dummy text ever since the 1500s, when an unknown printer took",
"always respond successfully.\"\"\" participant = Participant.objects.get(name='<NAME>') participant_page = reverse('main:participant', kwargs={'slug': participant.slug}) response_ok =",
"response.content) response = self.client.get(url, {'tag': ['tag1', 'tag3']}) ok_('Test event' in response.content) ok_('Second test",
"reverse from nose.tools import eq_, ok_ from airmozilla.main.models import ( Approval, Event, EventOldSlug,",
"tag3 = Tag.objects.create(name='tag3') event1.tags.add(tag1) event1.tags.add(tag2) event2.tags.add(tag2) event2.tags.add(tag3) # check that both events appear",
"event', description='Anything', start_time=event1.start_time, archive_time=event1.archive_time, public=True, status=event1.status, placeholder_img=event1.placeholder_img, ) eq_(Event.objects.approved().count(), 2) eq_(Event.objects.archived().count(), 2) tag1",
"= token participant.save() url = reverse('main:participant_clear', kwargs={'clear_token': token}) response_ok = self.client.get(url) eq_(response_ok.status_code, 200)",
"event' in response.content) ok_('Second test event' in response.content) response = self.client.get(url, {'tag': 'tag2'})",
"ok_('not approved' in response_fail_approval.content) approval.approved = True approval.processed = True approval.save() response_ok =",
"event' in response.content) ok_('Second test event' not in response.content) response = self.client.get(url, {'tag':",
"response_public.content) ok_('cache clear' in response_changed.content) def test_calendars_description(self): event = Event.objects.get(title='Test event') event.description =",
"as of the test. event = Event.objects.get(title='Test event') event.start_time = datetime.datetime.utcnow().replace(tzinfo=utc) event.archive_time =",
"= event1.start_time event1.save() eq_(Event.objects.approved().count(), 1) eq_(Event.objects.archived().count(), 1) event2 = Event.objects.create( title='Second test event',",
"ok_('Test event' in response.content) ok_('Second test event' in response.content) response = self.client.get(url, {'tag':",
"from django.test import TestCase from django.utils.timezone import utc from funfactory.urlresolvers import reverse from",
"token = str(uuid.uuid4()) participant.clear_token = token participant.save() url = reverse('main:participant_clear', kwargs={'clear_token': token}) response_ok",
"200) ok_('Check out the' not in response_public.content) ok_('One-liner' in response_public.content) def test_filter_by_tags(self): url",
"uuid from django.contrib.auth.models import Group from django.test import TestCase from django.utils.timezone import utc",
"the 1500s, when an unknown printer took a galley of type and scrambled",
"is getting really long it will be truncated. \"\"\".strip() event.save() response_public = self.client.get(reverse('main:calendar'))",
"event' in response.content) response = self.client.get(url, {'tag': 'Bogus'}) eq_(response.status_code, 301) response = self.client.get(url,",
"the event is public and scheduled and approved; request a login otherwise.\"\"\" event"
] |
[
"self.TOT_TRN_SAMPLES >= num_samples: # If there are enough samples left in the training",
"get_val_split(self, transform=None, num_samples=None): if num_samples is None: num_samples = self.NUM_VAL_SAMPLES if self.TRN_SET_SIZE -",
"of Caltech101. split.dataset is Caltech101. From this we can access the number of",
"file if not os.path.exists(self.CALTECH101_ZIP_PATH): if not self.download: raise(FileNotFoundError(\"Dataset files not found\")) print(\"Downloading {}",
"transform=None, num_samples=None): if num_samples is None: num_samples = self.NUM_VAL_SAMPLES if self.TRN_SET_SIZE - self.TOT_TRN_SAMPLES",
"get_train_split(self, transform=None, num_samples=None): if num_samples is None: num_samples = self.TOT_TRN_SAMPLES return Subset(Caltech101(root=self.DATASET_FOLDER, download=True,",
"number of samples # per class, to be used for weighted random sampling,",
"num_samples = self.NUM_VAL_SAMPLES if self.TRN_SET_SIZE - self.TOT_TRN_SAMPLES >= num_samples: # If there are",
"validation return Subset(Caltech101(root=self.DATASET_FOLDER, download=True, transform=transform), self.indices[self.TRN_SET_SIZE - num_samples:self.TRN_SET_SIZE]) # Validate directly on test",
"self.CALTECH101_FOLDER = os.path.join(self.root, '101_ObjectCategories') if not os.path.exists(self.CALTECH101_FOLDER): # Extract Caltech101 zip file if",
"**kwargs) self.samples_per_class = {k: self.targets.count(k) for k in self.class_to_idx.values()} # Data manager class",
"{} file...\".format(self.CALTECH101_ZIP_FILE)) extract_archive(self.CALTECH101_ZIP_PATH, self.root) print(\"Done!\") super(Caltech101, self).__init__(self.CALTECH101_FOLDER, **kwargs) self.samples_per_class = {k: self.targets.count(k) for",
"is None: num_samples = self.NUM_VAL_SAMPLES if self.TRN_SET_SIZE - self.TOT_TRN_SAMPLES >= num_samples: # If",
"P.KEY_DS_TRN_SET_SIZE: 8144, P.KEY_DS_VAL_SET_SIZE: 1000, P.KEY_DS_TST_SET_SIZE: 1000, P.KEY_DS_INPUT_SHAPE: (3, 224, 224), P.KEY_DS_NUM_CLASSES: 102 }",
"Data manager class for Caltech101 class Caltech101DataManager(DataManager): def __init__(self, config): self.CALTECH101_SIZE = 9144",
"def get_val_split(self, transform=None, num_samples=None): if num_samples is None: num_samples = self.NUM_VAL_SAMPLES if self.TRN_SET_SIZE",
"from torchvision.datasets import ImageFolder from torch.utils.data import Subset, WeightedRandomSampler import random import os",
"transform=transform), self.indices[self.TRN_SET_SIZE:self.TRN_SET_SIZE + num_samples]) def get_test_split(self, transform=None, num_samples=None): if num_samples is None: num_samples",
"class Caltech101DataManager(DataManager): def __init__(self, config): self.CALTECH101_SIZE = 9144 self.indices = list(range(self.CALTECH101_SIZE)) super().__init__(config) def",
"for Caltech101 class Caltech101DataManager(DataManager): def __init__(self, config): self.CALTECH101_SIZE = 9144 self.indices = list(range(self.CALTECH101_SIZE))",
"102 } def prepare_rnd_indices(self): random.shuffle(self.indices) def get_sampler(self, split): # split is a Subset",
"def get_train_split(self, transform=None, num_samples=None): if num_samples is None: num_samples = self.TOT_TRN_SAMPLES return Subset(Caltech101(root=self.DATASET_FOLDER,",
"download=False, **kwargs): self.root = root self.download = download self.CALTECH101_DRIVE_ID = '137RyRjvTBkBiIfeYBNZBtViDHQ6_Ewsp' self.CALTECH101_ZIP_FILE =",
"Caltech101 class Caltech101DataManager(DataManager): def __init__(self, config): self.CALTECH101_SIZE = 9144 self.indices = list(range(self.CALTECH101_SIZE)) super().__init__(config)",
"num_samples=None): if num_samples is None: num_samples = self.NUM_TST_SAMPLES return Subset(Caltech101(root=self.DATASET_FOLDER, download=True, transform=transform), self.indices[self.TRN_SET_SIZE:self.TRN_SET_SIZE",
"# many samples to fetch. return WeightedRandomSampler([w for w in split.dataset.samples_per_class.values()], len(split)) def",
"224, 224), P.KEY_DS_NUM_CLASSES: 102 } def prepare_rnd_indices(self): random.shuffle(self.indices) def get_sampler(self, split): # split",
"from torch.utils.data import Subset, WeightedRandomSampler import random import os from ..utils import download_large_file_from_drive",
"fetch. return WeightedRandomSampler([w for w in split.dataset.samples_per_class.values()], len(split)) def get_train_split(self, transform=None, num_samples=None): if",
"not found\")) print(\"Downloading {} file...\".format(self.CALTECH101_ZIP_FILE)) download_large_file_from_drive(self.CALTECH101_DRIVE_ID, self.CALTECH101_ZIP_PATH) print(\"Done!\") print(\"Extracting {} file...\".format(self.CALTECH101_ZIP_FILE)) extract_archive(self.CALTECH101_ZIP_PATH, self.root)",
"k in self.class_to_idx.values()} # Data manager class for Caltech101 class Caltech101DataManager(DataManager): def __init__(self,",
"with the length of the split, to determine how # many samples to",
"together with the length of the split, to determine how # many samples",
"test set otherwise return Subset(Caltech101(root=self.DATASET_FOLDER, download=True, transform=transform), self.indices[self.TRN_SET_SIZE:self.TRN_SET_SIZE + num_samples]) def get_test_split(self, transform=None,",
"} def prepare_rnd_indices(self): random.shuffle(self.indices) def get_sampler(self, split): # split is a Subset of",
"Caltech101(ImageFolder): def __init__(self, root, download=False, **kwargs): self.root = root self.download = download self.CALTECH101_DRIVE_ID",
"them for validation return Subset(Caltech101(root=self.DATASET_FOLDER, download=True, transform=transform), self.indices[self.TRN_SET_SIZE - num_samples:self.TRN_SET_SIZE]) # Validate directly",
"download=True, transform=transform), self.indices[self.TRN_SET_SIZE - num_samples:self.TRN_SET_SIZE]) # Validate directly on test set otherwise return",
"1000, P.KEY_DS_INPUT_SHAPE: (3, 224, 224), P.KEY_DS_NUM_CLASSES: 102 } def prepare_rnd_indices(self): random.shuffle(self.indices) def get_sampler(self,",
"if not self.download: raise(FileNotFoundError(\"Dataset files not found\")) print(\"Downloading {} file...\".format(self.CALTECH101_ZIP_FILE)) download_large_file_from_drive(self.CALTECH101_DRIVE_ID, self.CALTECH101_ZIP_PATH) print(\"Done!\")",
"root, download=False, **kwargs): self.root = root self.download = download self.CALTECH101_DRIVE_ID = '137RyRjvTBkBiIfeYBNZBtViDHQ6_Ewsp' self.CALTECH101_ZIP_FILE",
"random.shuffle(self.indices) def get_sampler(self, split): # split is a Subset of Caltech101. split.dataset is",
"file...\".format(self.CALTECH101_ZIP_FILE)) download_large_file_from_drive(self.CALTECH101_DRIVE_ID, self.CALTECH101_ZIP_PATH) print(\"Done!\") print(\"Extracting {} file...\".format(self.CALTECH101_ZIP_FILE)) extract_archive(self.CALTECH101_ZIP_PATH, self.root) print(\"Done!\") super(Caltech101, self).__init__(self.CALTECH101_FOLDER, **kwargs)",
"self.class_to_idx.values()} # Data manager class for Caltech101 class Caltech101DataManager(DataManager): def __init__(self, config): self.CALTECH101_SIZE",
"self.CALTECH101_SIZE = 9144 self.indices = list(range(self.CALTECH101_SIZE)) super().__init__(config) def get_dataset_metadata(self): return { P.KEY_DATASET: 'caltech101',",
"P.KEY_DS_TST_SET_SIZE: 1000, P.KEY_DS_INPUT_SHAPE: (3, 224, 224), P.KEY_DS_NUM_CLASSES: 102 } def prepare_rnd_indices(self): random.shuffle(self.indices) def",
"be used for weighted random sampling, together with the length of the split,",
"samples to fetch. return WeightedRandomSampler([w for w in split.dataset.samples_per_class.values()], len(split)) def get_train_split(self, transform=None,",
"= self.TOT_TRN_SAMPLES return Subset(Caltech101(root=self.DATASET_FOLDER, download=True, transform=transform), self.indices[:num_samples]) def get_val_split(self, transform=None, num_samples=None): if num_samples",
"= os.path.join(self.root, self.CALTECH101_ZIP_FILE) self.CALTECH101_FOLDER = os.path.join(self.root, '101_ObjectCategories') if not os.path.exists(self.CALTECH101_FOLDER): # Extract Caltech101",
"the training set, use them for validation return Subset(Caltech101(root=self.DATASET_FOLDER, download=True, transform=transform), self.indices[self.TRN_SET_SIZE -",
"DataManager from .. import params as P # Caltech101 Dataset class Caltech101(ImageFolder): def",
"download_large_file_from_drive(self.CALTECH101_DRIVE_ID, self.CALTECH101_ZIP_PATH) print(\"Done!\") print(\"Extracting {} file...\".format(self.CALTECH101_ZIP_FILE)) extract_archive(self.CALTECH101_ZIP_PATH, self.root) print(\"Done!\") super(Caltech101, self).__init__(self.CALTECH101_FOLDER, **kwargs) self.samples_per_class",
"we can access the number of samples # per class, to be used",
"def get_test_split(self, transform=None, num_samples=None): if num_samples is None: num_samples = self.NUM_TST_SAMPLES return Subset(Caltech101(root=self.DATASET_FOLDER,",
"if num_samples is None: num_samples = self.NUM_TST_SAMPLES return Subset(Caltech101(root=self.DATASET_FOLDER, download=True, transform=transform), self.indices[self.TRN_SET_SIZE:self.TRN_SET_SIZE +",
"the number of samples # per class, to be used for weighted random",
"return { P.KEY_DATASET: 'caltech101', P.KEY_DS_TRN_SET_SIZE: 8144, P.KEY_DS_VAL_SET_SIZE: 1000, P.KEY_DS_TST_SET_SIZE: 1000, P.KEY_DS_INPUT_SHAPE: (3, 224,",
"num_samples: # If there are enough samples left in the training set, use",
"many samples to fetch. return WeightedRandomSampler([w for w in split.dataset.samples_per_class.values()], len(split)) def get_train_split(self,",
"otherwise return Subset(Caltech101(root=self.DATASET_FOLDER, download=True, transform=transform), self.indices[self.TRN_SET_SIZE:self.TRN_SET_SIZE + num_samples]) def get_test_split(self, transform=None, num_samples=None): if",
"enough samples left in the training set, use them for validation return Subset(Caltech101(root=self.DATASET_FOLDER,",
"download=True, transform=transform), self.indices[self.TRN_SET_SIZE:self.TRN_SET_SIZE + num_samples]) def get_test_split(self, transform=None, num_samples=None): if num_samples is None:",
"WeightedRandomSampler import random import os from ..utils import download_large_file_from_drive from .data import DataManager",
"if not os.path.exists(self.CALTECH101_ZIP_PATH): if not self.download: raise(FileNotFoundError(\"Dataset files not found\")) print(\"Downloading {} file...\".format(self.CALTECH101_ZIP_FILE))",
"self.CALTECH101_ZIP_PATH = os.path.join(self.root, self.CALTECH101_ZIP_FILE) self.CALTECH101_FOLDER = os.path.join(self.root, '101_ObjectCategories') if not os.path.exists(self.CALTECH101_FOLDER): # Extract",
"transform=transform), self.indices[self.TRN_SET_SIZE - num_samples:self.TRN_SET_SIZE]) # Validate directly on test set otherwise return Subset(Caltech101(root=self.DATASET_FOLDER,",
"(3, 224, 224), P.KEY_DS_NUM_CLASSES: 102 } def prepare_rnd_indices(self): random.shuffle(self.indices) def get_sampler(self, split): #",
"in the training set, use them for validation return Subset(Caltech101(root=self.DATASET_FOLDER, download=True, transform=transform), self.indices[self.TRN_SET_SIZE",
"= 9144 self.indices = list(range(self.CALTECH101_SIZE)) super().__init__(config) def get_dataset_metadata(self): return { P.KEY_DATASET: 'caltech101', P.KEY_DS_TRN_SET_SIZE:",
"self.root = root self.download = download self.CALTECH101_DRIVE_ID = '137RyRjvTBkBiIfeYBNZBtViDHQ6_Ewsp' self.CALTECH101_ZIP_FILE = '101_ObjectCategories.tar.gz' self.CALTECH101_ZIP_PATH",
"Subset(Caltech101(root=self.DATASET_FOLDER, download=True, transform=transform), self.indices[self.TRN_SET_SIZE - num_samples:self.TRN_SET_SIZE]) # Validate directly on test set otherwise",
"return Subset(Caltech101(root=self.DATASET_FOLDER, download=True, transform=transform), self.indices[self.TRN_SET_SIZE - num_samples:self.TRN_SET_SIZE]) # Validate directly on test set",
"from torchvision.datasets.utils import extract_archive from torchvision.datasets import ImageFolder from torch.utils.data import Subset, WeightedRandomSampler",
"transform=None, num_samples=None): if num_samples is None: num_samples = self.TOT_TRN_SAMPLES return Subset(Caltech101(root=self.DATASET_FOLDER, download=True, transform=transform),",
"From this we can access the number of samples # per class, to",
"num_samples=None): if num_samples is None: num_samples = self.TOT_TRN_SAMPLES return Subset(Caltech101(root=self.DATASET_FOLDER, download=True, transform=transform), self.indices[:num_samples])",
"len(split)) def get_train_split(self, transform=None, num_samples=None): if num_samples is None: num_samples = self.TOT_TRN_SAMPLES return",
"os.path.join(self.root, self.CALTECH101_ZIP_FILE) self.CALTECH101_FOLDER = os.path.join(self.root, '101_ObjectCategories') if not os.path.exists(self.CALTECH101_FOLDER): # Extract Caltech101 zip",
"download_large_file_from_drive from .data import DataManager from .. import params as P # Caltech101",
"not os.path.exists(self.CALTECH101_FOLDER): # Extract Caltech101 zip file if not os.path.exists(self.CALTECH101_ZIP_PATH): if not self.download:",
"config): self.CALTECH101_SIZE = 9144 self.indices = list(range(self.CALTECH101_SIZE)) super().__init__(config) def get_dataset_metadata(self): return { P.KEY_DATASET:",
"# per class, to be used for weighted random sampling, together with the",
"Subset of Caltech101. split.dataset is Caltech101. From this we can access the number",
"num_samples is None: num_samples = self.NUM_VAL_SAMPLES if self.TRN_SET_SIZE - self.TOT_TRN_SAMPLES >= num_samples: #",
"def __init__(self, config): self.CALTECH101_SIZE = 9144 self.indices = list(range(self.CALTECH101_SIZE)) super().__init__(config) def get_dataset_metadata(self): return",
"224), P.KEY_DS_NUM_CLASSES: 102 } def prepare_rnd_indices(self): random.shuffle(self.indices) def get_sampler(self, split): # split is",
"super(Caltech101, self).__init__(self.CALTECH101_FOLDER, **kwargs) self.samples_per_class = {k: self.targets.count(k) for k in self.class_to_idx.values()} # Data",
"return Subset(Caltech101(root=self.DATASET_FOLDER, download=True, transform=transform), self.indices[:num_samples]) def get_val_split(self, transform=None, num_samples=None): if num_samples is None:",
"self.indices = list(range(self.CALTECH101_SIZE)) super().__init__(config) def get_dataset_metadata(self): return { P.KEY_DATASET: 'caltech101', P.KEY_DS_TRN_SET_SIZE: 8144, P.KEY_DS_VAL_SET_SIZE:",
"self.download: raise(FileNotFoundError(\"Dataset files not found\")) print(\"Downloading {} file...\".format(self.CALTECH101_ZIP_FILE)) download_large_file_from_drive(self.CALTECH101_DRIVE_ID, self.CALTECH101_ZIP_PATH) print(\"Done!\") print(\"Extracting {}",
"file...\".format(self.CALTECH101_ZIP_FILE)) extract_archive(self.CALTECH101_ZIP_PATH, self.root) print(\"Done!\") super(Caltech101, self).__init__(self.CALTECH101_FOLDER, **kwargs) self.samples_per_class = {k: self.targets.count(k) for k",
"'101_ObjectCategories') if not os.path.exists(self.CALTECH101_FOLDER): # Extract Caltech101 zip file if not os.path.exists(self.CALTECH101_ZIP_PATH): if",
"class, to be used for weighted random sampling, together with the length of",
"for validation return Subset(Caltech101(root=self.DATASET_FOLDER, download=True, transform=transform), self.indices[self.TRN_SET_SIZE - num_samples:self.TRN_SET_SIZE]) # Validate directly on",
"'caltech101', P.KEY_DS_TRN_SET_SIZE: 8144, P.KEY_DS_VAL_SET_SIZE: 1000, P.KEY_DS_TST_SET_SIZE: 1000, P.KEY_DS_INPUT_SHAPE: (3, 224, 224), P.KEY_DS_NUM_CLASSES: 102",
"is a Subset of Caltech101. split.dataset is Caltech101. From this we can access",
"Caltech101 zip file if not os.path.exists(self.CALTECH101_ZIP_PATH): if not self.download: raise(FileNotFoundError(\"Dataset files not found\"))",
"1000, P.KEY_DS_TST_SET_SIZE: 1000, P.KEY_DS_INPUT_SHAPE: (3, 224, 224), P.KEY_DS_NUM_CLASSES: 102 } def prepare_rnd_indices(self): random.shuffle(self.indices)",
"if not os.path.exists(self.CALTECH101_FOLDER): # Extract Caltech101 zip file if not os.path.exists(self.CALTECH101_ZIP_PATH): if not",
"in split.dataset.samples_per_class.values()], len(split)) def get_train_split(self, transform=None, num_samples=None): if num_samples is None: num_samples =",
"self.targets.count(k) for k in self.class_to_idx.values()} # Data manager class for Caltech101 class Caltech101DataManager(DataManager):",
"extract_archive from torchvision.datasets import ImageFolder from torch.utils.data import Subset, WeightedRandomSampler import random import",
"manager class for Caltech101 class Caltech101DataManager(DataManager): def __init__(self, config): self.CALTECH101_SIZE = 9144 self.indices",
"if num_samples is None: num_samples = self.TOT_TRN_SAMPLES return Subset(Caltech101(root=self.DATASET_FOLDER, download=True, transform=transform), self.indices[:num_samples]) def",
"samples # per class, to be used for weighted random sampling, together with",
"for weighted random sampling, together with the length of the split, to determine",
"- self.TOT_TRN_SAMPLES >= num_samples: # If there are enough samples left in the",
"list(range(self.CALTECH101_SIZE)) super().__init__(config) def get_dataset_metadata(self): return { P.KEY_DATASET: 'caltech101', P.KEY_DS_TRN_SET_SIZE: 8144, P.KEY_DS_VAL_SET_SIZE: 1000, P.KEY_DS_TST_SET_SIZE:",
"split, to determine how # many samples to fetch. return WeightedRandomSampler([w for w",
"P.KEY_DS_VAL_SET_SIZE: 1000, P.KEY_DS_TST_SET_SIZE: 1000, P.KEY_DS_INPUT_SHAPE: (3, 224, 224), P.KEY_DS_NUM_CLASSES: 102 } def prepare_rnd_indices(self):",
"download=True, transform=transform), self.indices[:num_samples]) def get_val_split(self, transform=None, num_samples=None): if num_samples is None: num_samples =",
"= '101_ObjectCategories.tar.gz' self.CALTECH101_ZIP_PATH = os.path.join(self.root, self.CALTECH101_ZIP_FILE) self.CALTECH101_FOLDER = os.path.join(self.root, '101_ObjectCategories') if not os.path.exists(self.CALTECH101_FOLDER):",
"WeightedRandomSampler([w for w in split.dataset.samples_per_class.values()], len(split)) def get_train_split(self, transform=None, num_samples=None): if num_samples is",
"torchvision.datasets import ImageFolder from torch.utils.data import Subset, WeightedRandomSampler import random import os from",
"import download_large_file_from_drive from .data import DataManager from .. import params as P #",
"import params as P # Caltech101 Dataset class Caltech101(ImageFolder): def __init__(self, root, download=False,",
"a Subset of Caltech101. split.dataset is Caltech101. From this we can access the",
"= list(range(self.CALTECH101_SIZE)) super().__init__(config) def get_dataset_metadata(self): return { P.KEY_DATASET: 'caltech101', P.KEY_DS_TRN_SET_SIZE: 8144, P.KEY_DS_VAL_SET_SIZE: 1000,",
"access the number of samples # per class, to be used for weighted",
"self).__init__(self.CALTECH101_FOLDER, **kwargs) self.samples_per_class = {k: self.targets.count(k) for k in self.class_to_idx.values()} # Data manager",
"{k: self.targets.count(k) for k in self.class_to_idx.values()} # Data manager class for Caltech101 class",
"split.dataset.samples_per_class.values()], len(split)) def get_train_split(self, transform=None, num_samples=None): if num_samples is None: num_samples = self.TOT_TRN_SAMPLES",
"get_test_split(self, transform=None, num_samples=None): if num_samples is None: num_samples = self.NUM_TST_SAMPLES return Subset(Caltech101(root=self.DATASET_FOLDER, download=True,",
"self.CALTECH101_DRIVE_ID = '137RyRjvTBkBiIfeYBNZBtViDHQ6_Ewsp' self.CALTECH101_ZIP_FILE = '101_ObjectCategories.tar.gz' self.CALTECH101_ZIP_PATH = os.path.join(self.root, self.CALTECH101_ZIP_FILE) self.CALTECH101_FOLDER = os.path.join(self.root,",
"Subset(Caltech101(root=self.DATASET_FOLDER, download=True, transform=transform), self.indices[:num_samples]) def get_val_split(self, transform=None, num_samples=None): if num_samples is None: num_samples",
"transform=None, num_samples=None): if num_samples is None: num_samples = self.NUM_TST_SAMPLES return Subset(Caltech101(root=self.DATASET_FOLDER, download=True, transform=transform),",
"torchvision.datasets.utils import extract_archive from torchvision.datasets import ImageFolder from torch.utils.data import Subset, WeightedRandomSampler import",
"from .data import DataManager from .. import params as P # Caltech101 Dataset",
"# split is a Subset of Caltech101. split.dataset is Caltech101. From this we",
"def __init__(self, root, download=False, **kwargs): self.root = root self.download = download self.CALTECH101_DRIVE_ID =",
"self.TRN_SET_SIZE - self.TOT_TRN_SAMPLES >= num_samples: # If there are enough samples left in",
"= os.path.join(self.root, '101_ObjectCategories') if not os.path.exists(self.CALTECH101_FOLDER): # Extract Caltech101 zip file if not",
"self.indices[self.TRN_SET_SIZE:self.TRN_SET_SIZE + num_samples]) def get_test_split(self, transform=None, num_samples=None): if num_samples is None: num_samples =",
"params as P # Caltech101 Dataset class Caltech101(ImageFolder): def __init__(self, root, download=False, **kwargs):",
"how # many samples to fetch. return WeightedRandomSampler([w for w in split.dataset.samples_per_class.values()], len(split))",
"weighted random sampling, together with the length of the split, to determine how",
"os.path.exists(self.CALTECH101_ZIP_PATH): if not self.download: raise(FileNotFoundError(\"Dataset files not found\")) print(\"Downloading {} file...\".format(self.CALTECH101_ZIP_FILE)) download_large_file_from_drive(self.CALTECH101_DRIVE_ID, self.CALTECH101_ZIP_PATH)",
"use them for validation return Subset(Caltech101(root=self.DATASET_FOLDER, download=True, transform=transform), self.indices[self.TRN_SET_SIZE - num_samples:self.TRN_SET_SIZE]) # Validate",
"= '137RyRjvTBkBiIfeYBNZBtViDHQ6_Ewsp' self.CALTECH101_ZIP_FILE = '101_ObjectCategories.tar.gz' self.CALTECH101_ZIP_PATH = os.path.join(self.root, self.CALTECH101_ZIP_FILE) self.CALTECH101_FOLDER = os.path.join(self.root, '101_ObjectCategories')",
"Validate directly on test set otherwise return Subset(Caltech101(root=self.DATASET_FOLDER, download=True, transform=transform), self.indices[self.TRN_SET_SIZE:self.TRN_SET_SIZE + num_samples])",
"# Validate directly on test set otherwise return Subset(Caltech101(root=self.DATASET_FOLDER, download=True, transform=transform), self.indices[self.TRN_SET_SIZE:self.TRN_SET_SIZE +",
"self.root) print(\"Done!\") super(Caltech101, self).__init__(self.CALTECH101_FOLDER, **kwargs) self.samples_per_class = {k: self.targets.count(k) for k in self.class_to_idx.values()}",
"9144 self.indices = list(range(self.CALTECH101_SIZE)) super().__init__(config) def get_dataset_metadata(self): return { P.KEY_DATASET: 'caltech101', P.KEY_DS_TRN_SET_SIZE: 8144,",
"import ImageFolder from torch.utils.data import Subset, WeightedRandomSampler import random import os from ..utils",
"return WeightedRandomSampler([w for w in split.dataset.samples_per_class.values()], len(split)) def get_train_split(self, transform=None, num_samples=None): if num_samples",
"# Caltech101 Dataset class Caltech101(ImageFolder): def __init__(self, root, download=False, **kwargs): self.root = root",
"to determine how # many samples to fetch. return WeightedRandomSampler([w for w in",
"num_samples=None): if num_samples is None: num_samples = self.NUM_VAL_SAMPLES if self.TRN_SET_SIZE - self.TOT_TRN_SAMPLES >=",
"of the split, to determine how # many samples to fetch. return WeightedRandomSampler([w",
"Extract Caltech101 zip file if not os.path.exists(self.CALTECH101_ZIP_PATH): if not self.download: raise(FileNotFoundError(\"Dataset files not",
"def get_dataset_metadata(self): return { P.KEY_DATASET: 'caltech101', P.KEY_DS_TRN_SET_SIZE: 8144, P.KEY_DS_VAL_SET_SIZE: 1000, P.KEY_DS_TST_SET_SIZE: 1000, P.KEY_DS_INPUT_SHAPE:",
"ImageFolder from torch.utils.data import Subset, WeightedRandomSampler import random import os from ..utils import",
"P # Caltech101 Dataset class Caltech101(ImageFolder): def __init__(self, root, download=False, **kwargs): self.root =",
"- num_samples:self.TRN_SET_SIZE]) # Validate directly on test set otherwise return Subset(Caltech101(root=self.DATASET_FOLDER, download=True, transform=transform),",
"to be used for weighted random sampling, together with the length of the",
".. import params as P # Caltech101 Dataset class Caltech101(ImageFolder): def __init__(self, root,",
"super().__init__(config) def get_dataset_metadata(self): return { P.KEY_DATASET: 'caltech101', P.KEY_DS_TRN_SET_SIZE: 8144, P.KEY_DS_VAL_SET_SIZE: 1000, P.KEY_DS_TST_SET_SIZE: 1000,",
"self.samples_per_class = {k: self.targets.count(k) for k in self.class_to_idx.values()} # Data manager class for",
"random import os from ..utils import download_large_file_from_drive from .data import DataManager from ..",
"{ P.KEY_DATASET: 'caltech101', P.KEY_DS_TRN_SET_SIZE: 8144, P.KEY_DS_VAL_SET_SIZE: 1000, P.KEY_DS_TST_SET_SIZE: 1000, P.KEY_DS_INPUT_SHAPE: (3, 224, 224),",
"torch.utils.data import Subset, WeightedRandomSampler import random import os from ..utils import download_large_file_from_drive from",
"the length of the split, to determine how # many samples to fetch.",
"P.KEY_DS_NUM_CLASSES: 102 } def prepare_rnd_indices(self): random.shuffle(self.indices) def get_sampler(self, split): # split is a",
"the split, to determine how # many samples to fetch. return WeightedRandomSampler([w for",
"'101_ObjectCategories.tar.gz' self.CALTECH101_ZIP_PATH = os.path.join(self.root, self.CALTECH101_ZIP_FILE) self.CALTECH101_FOLDER = os.path.join(self.root, '101_ObjectCategories') if not os.path.exists(self.CALTECH101_FOLDER): #",
"transform=transform), self.indices[:num_samples]) def get_val_split(self, transform=None, num_samples=None): if num_samples is None: num_samples = self.NUM_VAL_SAMPLES",
"get_sampler(self, split): # split is a Subset of Caltech101. split.dataset is Caltech101. From",
"left in the training set, use them for validation return Subset(Caltech101(root=self.DATASET_FOLDER, download=True, transform=transform),",
"training set, use them for validation return Subset(Caltech101(root=self.DATASET_FOLDER, download=True, transform=transform), self.indices[self.TRN_SET_SIZE - num_samples:self.TRN_SET_SIZE])",
"import extract_archive from torchvision.datasets import ImageFolder from torch.utils.data import Subset, WeightedRandomSampler import random",
"os from ..utils import download_large_file_from_drive from .data import DataManager from .. import params",
"random sampling, together with the length of the split, to determine how #",
"'137RyRjvTBkBiIfeYBNZBtViDHQ6_Ewsp' self.CALTECH101_ZIP_FILE = '101_ObjectCategories.tar.gz' self.CALTECH101_ZIP_PATH = os.path.join(self.root, self.CALTECH101_ZIP_FILE) self.CALTECH101_FOLDER = os.path.join(self.root, '101_ObjectCategories') if",
"this we can access the number of samples # per class, to be",
"import DataManager from .. import params as P # Caltech101 Dataset class Caltech101(ImageFolder):",
"class for Caltech101 class Caltech101DataManager(DataManager): def __init__(self, config): self.CALTECH101_SIZE = 9144 self.indices =",
"import os from ..utils import download_large_file_from_drive from .data import DataManager from .. import",
"import Subset, WeightedRandomSampler import random import os from ..utils import download_large_file_from_drive from .data",
"num_samples]) def get_test_split(self, transform=None, num_samples=None): if num_samples is None: num_samples = self.NUM_TST_SAMPLES return",
"raise(FileNotFoundError(\"Dataset files not found\")) print(\"Downloading {} file...\".format(self.CALTECH101_ZIP_FILE)) download_large_file_from_drive(self.CALTECH101_DRIVE_ID, self.CALTECH101_ZIP_PATH) print(\"Done!\") print(\"Extracting {} file...\".format(self.CALTECH101_ZIP_FILE))",
"not os.path.exists(self.CALTECH101_ZIP_PATH): if not self.download: raise(FileNotFoundError(\"Dataset files not found\")) print(\"Downloading {} file...\".format(self.CALTECH101_ZIP_FILE)) download_large_file_from_drive(self.CALTECH101_DRIVE_ID,",
"__init__(self, config): self.CALTECH101_SIZE = 9144 self.indices = list(range(self.CALTECH101_SIZE)) super().__init__(config) def get_dataset_metadata(self): return {",
"self.NUM_VAL_SAMPLES if self.TRN_SET_SIZE - self.TOT_TRN_SAMPLES >= num_samples: # If there are enough samples",
"= {k: self.targets.count(k) for k in self.class_to_idx.values()} # Data manager class for Caltech101",
"set otherwise return Subset(Caltech101(root=self.DATASET_FOLDER, download=True, transform=transform), self.indices[self.TRN_SET_SIZE:self.TRN_SET_SIZE + num_samples]) def get_test_split(self, transform=None, num_samples=None):",
"zip file if not os.path.exists(self.CALTECH101_ZIP_PATH): if not self.download: raise(FileNotFoundError(\"Dataset files not found\")) print(\"Downloading",
"as P # Caltech101 Dataset class Caltech101(ImageFolder): def __init__(self, root, download=False, **kwargs): self.root",
"is Caltech101. From this we can access the number of samples # per",
"download self.CALTECH101_DRIVE_ID = '137RyRjvTBkBiIfeYBNZBtViDHQ6_Ewsp' self.CALTECH101_ZIP_FILE = '101_ObjectCategories.tar.gz' self.CALTECH101_ZIP_PATH = os.path.join(self.root, self.CALTECH101_ZIP_FILE) self.CALTECH101_FOLDER =",
"..utils import download_large_file_from_drive from .data import DataManager from .. import params as P",
"used for weighted random sampling, together with the length of the split, to",
"to fetch. return WeightedRandomSampler([w for w in split.dataset.samples_per_class.values()], len(split)) def get_train_split(self, transform=None, num_samples=None):",
"sampling, together with the length of the split, to determine how # many",
"self.TOT_TRN_SAMPLES return Subset(Caltech101(root=self.DATASET_FOLDER, download=True, transform=transform), self.indices[:num_samples]) def get_val_split(self, transform=None, num_samples=None): if num_samples is",
"extract_archive(self.CALTECH101_ZIP_PATH, self.root) print(\"Done!\") super(Caltech101, self).__init__(self.CALTECH101_FOLDER, **kwargs) self.samples_per_class = {k: self.targets.count(k) for k in",
".data import DataManager from .. import params as P # Caltech101 Dataset class",
"Caltech101. From this we can access the number of samples # per class,",
"length of the split, to determine how # many samples to fetch. return",
"8144, P.KEY_DS_VAL_SET_SIZE: 1000, P.KEY_DS_TST_SET_SIZE: 1000, P.KEY_DS_INPUT_SHAPE: (3, 224, 224), P.KEY_DS_NUM_CLASSES: 102 } def",
"print(\"Done!\") print(\"Extracting {} file...\".format(self.CALTECH101_ZIP_FILE)) extract_archive(self.CALTECH101_ZIP_PATH, self.root) print(\"Done!\") super(Caltech101, self).__init__(self.CALTECH101_FOLDER, **kwargs) self.samples_per_class = {k:",
"Caltech101 Dataset class Caltech101(ImageFolder): def __init__(self, root, download=False, **kwargs): self.root = root self.download",
"Caltech101. split.dataset is Caltech101. From this we can access the number of samples",
"num_samples is None: num_samples = self.NUM_TST_SAMPLES return Subset(Caltech101(root=self.DATASET_FOLDER, download=True, transform=transform), self.indices[self.TRN_SET_SIZE:self.TRN_SET_SIZE + num_samples])",
"P.KEY_DATASET: 'caltech101', P.KEY_DS_TRN_SET_SIZE: 8144, P.KEY_DS_VAL_SET_SIZE: 1000, P.KEY_DS_TST_SET_SIZE: 1000, P.KEY_DS_INPUT_SHAPE: (3, 224, 224), P.KEY_DS_NUM_CLASSES:",
"# Data manager class for Caltech101 class Caltech101DataManager(DataManager): def __init__(self, config): self.CALTECH101_SIZE =",
"for k in self.class_to_idx.values()} # Data manager class for Caltech101 class Caltech101DataManager(DataManager): def",
"Caltech101DataManager(DataManager): def __init__(self, config): self.CALTECH101_SIZE = 9144 self.indices = list(range(self.CALTECH101_SIZE)) super().__init__(config) def get_dataset_metadata(self):",
"import random import os from ..utils import download_large_file_from_drive from .data import DataManager from",
"Dataset class Caltech101(ImageFolder): def __init__(self, root, download=False, **kwargs): self.root = root self.download =",
"root self.download = download self.CALTECH101_DRIVE_ID = '137RyRjvTBkBiIfeYBNZBtViDHQ6_Ewsp' self.CALTECH101_ZIP_FILE = '101_ObjectCategories.tar.gz' self.CALTECH101_ZIP_PATH = os.path.join(self.root,",
"P.KEY_DS_INPUT_SHAPE: (3, 224, 224), P.KEY_DS_NUM_CLASSES: 102 } def prepare_rnd_indices(self): random.shuffle(self.indices) def get_sampler(self, split):",
"if self.TRN_SET_SIZE - self.TOT_TRN_SAMPLES >= num_samples: # If there are enough samples left",
"split.dataset is Caltech101. From this we can access the number of samples #",
"self.CALTECH101_ZIP_PATH) print(\"Done!\") print(\"Extracting {} file...\".format(self.CALTECH101_ZIP_FILE)) extract_archive(self.CALTECH101_ZIP_PATH, self.root) print(\"Done!\") super(Caltech101, self).__init__(self.CALTECH101_FOLDER, **kwargs) self.samples_per_class =",
"# If there are enough samples left in the training set, use them",
"self.CALTECH101_ZIP_FILE) self.CALTECH101_FOLDER = os.path.join(self.root, '101_ObjectCategories') if not os.path.exists(self.CALTECH101_FOLDER): # Extract Caltech101 zip file",
"__init__(self, root, download=False, **kwargs): self.root = root self.download = download self.CALTECH101_DRIVE_ID = '137RyRjvTBkBiIfeYBNZBtViDHQ6_Ewsp'",
"split): # split is a Subset of Caltech101. split.dataset is Caltech101. From this",
"None: num_samples = self.NUM_VAL_SAMPLES if self.TRN_SET_SIZE - self.TOT_TRN_SAMPLES >= num_samples: # If there",
"**kwargs): self.root = root self.download = download self.CALTECH101_DRIVE_ID = '137RyRjvTBkBiIfeYBNZBtViDHQ6_Ewsp' self.CALTECH101_ZIP_FILE = '101_ObjectCategories.tar.gz'",
"not self.download: raise(FileNotFoundError(\"Dataset files not found\")) print(\"Downloading {} file...\".format(self.CALTECH101_ZIP_FILE)) download_large_file_from_drive(self.CALTECH101_DRIVE_ID, self.CALTECH101_ZIP_PATH) print(\"Done!\") print(\"Extracting",
"can access the number of samples # per class, to be used for",
"+ num_samples]) def get_test_split(self, transform=None, num_samples=None): if num_samples is None: num_samples = self.NUM_TST_SAMPLES",
"{} file...\".format(self.CALTECH101_ZIP_FILE)) download_large_file_from_drive(self.CALTECH101_DRIVE_ID, self.CALTECH101_ZIP_PATH) print(\"Done!\") print(\"Extracting {} file...\".format(self.CALTECH101_ZIP_FILE)) extract_archive(self.CALTECH101_ZIP_PATH, self.root) print(\"Done!\") super(Caltech101, self).__init__(self.CALTECH101_FOLDER,",
"get_dataset_metadata(self): return { P.KEY_DATASET: 'caltech101', P.KEY_DS_TRN_SET_SIZE: 8144, P.KEY_DS_VAL_SET_SIZE: 1000, P.KEY_DS_TST_SET_SIZE: 1000, P.KEY_DS_INPUT_SHAPE: (3,",
"def get_sampler(self, split): # split is a Subset of Caltech101. split.dataset is Caltech101.",
"files not found\")) print(\"Downloading {} file...\".format(self.CALTECH101_ZIP_FILE)) download_large_file_from_drive(self.CALTECH101_DRIVE_ID, self.CALTECH101_ZIP_PATH) print(\"Done!\") print(\"Extracting {} file...\".format(self.CALTECH101_ZIP_FILE)) extract_archive(self.CALTECH101_ZIP_PATH,",
"w in split.dataset.samples_per_class.values()], len(split)) def get_train_split(self, transform=None, num_samples=None): if num_samples is None: num_samples",
"set, use them for validation return Subset(Caltech101(root=self.DATASET_FOLDER, download=True, transform=transform), self.indices[self.TRN_SET_SIZE - num_samples:self.TRN_SET_SIZE]) #",
"prepare_rnd_indices(self): random.shuffle(self.indices) def get_sampler(self, split): # split is a Subset of Caltech101. split.dataset",
"determine how # many samples to fetch. return WeightedRandomSampler([w for w in split.dataset.samples_per_class.values()],",
"num_samples = self.TOT_TRN_SAMPLES return Subset(Caltech101(root=self.DATASET_FOLDER, download=True, transform=transform), self.indices[:num_samples]) def get_val_split(self, transform=None, num_samples=None): if",
"from ..utils import download_large_file_from_drive from .data import DataManager from .. import params as",
"is None: num_samples = self.TOT_TRN_SAMPLES return Subset(Caltech101(root=self.DATASET_FOLDER, download=True, transform=transform), self.indices[:num_samples]) def get_val_split(self, transform=None,",
"of samples # per class, to be used for weighted random sampling, together",
"are enough samples left in the training set, use them for validation return",
"print(\"Downloading {} file...\".format(self.CALTECH101_ZIP_FILE)) download_large_file_from_drive(self.CALTECH101_DRIVE_ID, self.CALTECH101_ZIP_PATH) print(\"Done!\") print(\"Extracting {} file...\".format(self.CALTECH101_ZIP_FILE)) extract_archive(self.CALTECH101_ZIP_PATH, self.root) print(\"Done!\") super(Caltech101,",
"def prepare_rnd_indices(self): random.shuffle(self.indices) def get_sampler(self, split): # split is a Subset of Caltech101.",
"Subset(Caltech101(root=self.DATASET_FOLDER, download=True, transform=transform), self.indices[self.TRN_SET_SIZE:self.TRN_SET_SIZE + num_samples]) def get_test_split(self, transform=None, num_samples=None): if num_samples is",
"self.indices[:num_samples]) def get_val_split(self, transform=None, num_samples=None): if num_samples is None: num_samples = self.NUM_VAL_SAMPLES if",
"self.download = download self.CALTECH101_DRIVE_ID = '137RyRjvTBkBiIfeYBNZBtViDHQ6_Ewsp' self.CALTECH101_ZIP_FILE = '101_ObjectCategories.tar.gz' self.CALTECH101_ZIP_PATH = os.path.join(self.root, self.CALTECH101_ZIP_FILE)",
"found\")) print(\"Downloading {} file...\".format(self.CALTECH101_ZIP_FILE)) download_large_file_from_drive(self.CALTECH101_DRIVE_ID, self.CALTECH101_ZIP_PATH) print(\"Done!\") print(\"Extracting {} file...\".format(self.CALTECH101_ZIP_FILE)) extract_archive(self.CALTECH101_ZIP_PATH, self.root) print(\"Done!\")",
"# Extract Caltech101 zip file if not os.path.exists(self.CALTECH101_ZIP_PATH): if not self.download: raise(FileNotFoundError(\"Dataset files",
"Subset, WeightedRandomSampler import random import os from ..utils import download_large_file_from_drive from .data import",
"os.path.join(self.root, '101_ObjectCategories') if not os.path.exists(self.CALTECH101_FOLDER): # Extract Caltech101 zip file if not os.path.exists(self.CALTECH101_ZIP_PATH):",
"from .. import params as P # Caltech101 Dataset class Caltech101(ImageFolder): def __init__(self,",
"= root self.download = download self.CALTECH101_DRIVE_ID = '137RyRjvTBkBiIfeYBNZBtViDHQ6_Ewsp' self.CALTECH101_ZIP_FILE = '101_ObjectCategories.tar.gz' self.CALTECH101_ZIP_PATH =",
"print(\"Done!\") super(Caltech101, self).__init__(self.CALTECH101_FOLDER, **kwargs) self.samples_per_class = {k: self.targets.count(k) for k in self.class_to_idx.values()} #",
"samples left in the training set, use them for validation return Subset(Caltech101(root=self.DATASET_FOLDER, download=True,",
"<gh_stars>1-10 from torchvision.datasets.utils import extract_archive from torchvision.datasets import ImageFolder from torch.utils.data import Subset,",
"directly on test set otherwise return Subset(Caltech101(root=self.DATASET_FOLDER, download=True, transform=transform), self.indices[self.TRN_SET_SIZE:self.TRN_SET_SIZE + num_samples]) def",
"class Caltech101(ImageFolder): def __init__(self, root, download=False, **kwargs): self.root = root self.download = download",
"self.CALTECH101_ZIP_FILE = '101_ObjectCategories.tar.gz' self.CALTECH101_ZIP_PATH = os.path.join(self.root, self.CALTECH101_ZIP_FILE) self.CALTECH101_FOLDER = os.path.join(self.root, '101_ObjectCategories') if not",
"for w in split.dataset.samples_per_class.values()], len(split)) def get_train_split(self, transform=None, num_samples=None): if num_samples is None:",
"= download self.CALTECH101_DRIVE_ID = '137RyRjvTBkBiIfeYBNZBtViDHQ6_Ewsp' self.CALTECH101_ZIP_FILE = '101_ObjectCategories.tar.gz' self.CALTECH101_ZIP_PATH = os.path.join(self.root, self.CALTECH101_ZIP_FILE) self.CALTECH101_FOLDER",
"None: num_samples = self.TOT_TRN_SAMPLES return Subset(Caltech101(root=self.DATASET_FOLDER, download=True, transform=transform), self.indices[:num_samples]) def get_val_split(self, transform=None, num_samples=None):",
"self.indices[self.TRN_SET_SIZE - num_samples:self.TRN_SET_SIZE]) # Validate directly on test set otherwise return Subset(Caltech101(root=self.DATASET_FOLDER, download=True,",
"if num_samples is None: num_samples = self.NUM_VAL_SAMPLES if self.TRN_SET_SIZE - self.TOT_TRN_SAMPLES >= num_samples:",
"os.path.exists(self.CALTECH101_FOLDER): # Extract Caltech101 zip file if not os.path.exists(self.CALTECH101_ZIP_PATH): if not self.download: raise(FileNotFoundError(\"Dataset",
"= self.NUM_VAL_SAMPLES if self.TRN_SET_SIZE - self.TOT_TRN_SAMPLES >= num_samples: # If there are enough",
"on test set otherwise return Subset(Caltech101(root=self.DATASET_FOLDER, download=True, transform=transform), self.indices[self.TRN_SET_SIZE:self.TRN_SET_SIZE + num_samples]) def get_test_split(self,",
"print(\"Extracting {} file...\".format(self.CALTECH101_ZIP_FILE)) extract_archive(self.CALTECH101_ZIP_PATH, self.root) print(\"Done!\") super(Caltech101, self).__init__(self.CALTECH101_FOLDER, **kwargs) self.samples_per_class = {k: self.targets.count(k)",
"num_samples:self.TRN_SET_SIZE]) # Validate directly on test set otherwise return Subset(Caltech101(root=self.DATASET_FOLDER, download=True, transform=transform), self.indices[self.TRN_SET_SIZE:self.TRN_SET_SIZE",
"in self.class_to_idx.values()} # Data manager class for Caltech101 class Caltech101DataManager(DataManager): def __init__(self, config):",
"split is a Subset of Caltech101. split.dataset is Caltech101. From this we can",
"per class, to be used for weighted random sampling, together with the length",
"there are enough samples left in the training set, use them for validation",
">= num_samples: # If there are enough samples left in the training set,",
"num_samples is None: num_samples = self.TOT_TRN_SAMPLES return Subset(Caltech101(root=self.DATASET_FOLDER, download=True, transform=transform), self.indices[:num_samples]) def get_val_split(self,",
"If there are enough samples left in the training set, use them for",
"return Subset(Caltech101(root=self.DATASET_FOLDER, download=True, transform=transform), self.indices[self.TRN_SET_SIZE:self.TRN_SET_SIZE + num_samples]) def get_test_split(self, transform=None, num_samples=None): if num_samples"
] |
[
"graphene.String(required=True) user = graphene.Field(UserType) def mutate(self, info, email): user = User.objects.get(email=email) user.is_active =",
"import DjangoFilterConnectionField from graphql_jwt.decorators import login_required from .models import User class UserType(DjangoObjectType): class",
"= True #shop.slug = slug.replace('_deleted', '') user.save() return UndeleteUserMutation(user=user) class Mutation(graphene.ObjectType): register_user =",
"user = graphene.Field(UserType) def mutate(self, info, user_data=None): user = User.objects.create( email=user_data.email, first_name=user_data.first_name, last_name=user_data.last_name",
"class UndeleteUserMutation(graphene.Mutation): class Arguments: email = graphene.String(required=True) user = graphene.Field(UserType) def mutate(self, info,",
"return CreateUserMutation(user=user) class UpdateUserMutation(graphene.Mutation): class Arguments: user_data = UserInput(required=True) user = graphene.Field(UserType) def",
"False #shop.slug = slug+'_deleted' user.save() return DeleteUserMutation(user=user) class UndeleteUserMutation(graphene.Mutation): class Arguments: email =",
"class RegisterUserMutation(graphene.Mutation): class Arguments: user_data = UserInput(required=True) user = graphene.Field(UserType) def mutate(self, info,",
"def resolve_me(self, info): user = info.context.user return user class RegisterUserMutation(graphene.Mutation): class Arguments: user_data",
"user = graphene.Field(UserType) def mutate(self, info, user_data): user = User.objects.get(email=user_data.email) user.first_name = user_data.first_name",
"Query: me = graphene.Field(UserType) all_users = DjangoFilterConnectionField(UserType) @login_required def resolve_me(self, info): user =",
"UndeleteUserMutation(user=user) class Mutation(graphene.ObjectType): register_user = RegisterUserMutation.Field() create_user = CreateUserMutation.Field() update_user = UpdateUserMutation.Field() delete_user",
"= graphene.Field(UserType) def mutate(self, info, user_data=None): user = User.objects.create( email=user_data.email ) user.set_password(user_data.password) user.save()",
"= graphene.Field(UserType) def mutate(self, info, user_data): user = User.objects.get(email=user_data.email) user.first_name = user_data.first_name user.last_name",
"interfaces = (graphene.relay.Node, ) class UserInput(graphene.InputObjectType): email = graphene.String(required=True) password = graphene.String(required=True) first_name",
"user_data=None): user = User.objects.create( email=user_data.email ) user.set_password(user_data.password) user.save() return RegisterUserMutation(user=user) class CreateUserMutation(graphene.Mutation): class",
"'') user.save() return UndeleteUserMutation(user=user) class Mutation(graphene.ObjectType): register_user = RegisterUserMutation.Field() create_user = CreateUserMutation.Field() update_user",
"class Arguments: user_data = UserInput(required=True) user = graphene.Field(UserType) def mutate(self, info, user_data=None): user",
"class Mutation(graphene.ObjectType): register_user = RegisterUserMutation.Field() create_user = CreateUserMutation.Field() update_user = UpdateUserMutation.Field() delete_user =",
"login_required from .models import User class UserType(DjangoObjectType): class Meta: model = User fields",
"graphene.Field(UserType) def mutate(self, info, email): user = User.objects.get(email=email) user.is_active = False #shop.slug =",
"password = graphene.String(required=True) first_name = graphene.String() last_name = graphene.String() class Query: me =",
"user = User.objects.get(email=email) user.is_active = False #shop.slug = slug+'_deleted' user.save() return DeleteUserMutation(user=user) class",
"graphene_django import DjangoObjectType, DjangoListField from graphene_django.filter import DjangoFilterConnectionField from graphql_jwt.decorators import login_required from",
"User fields = '__all__' filter_fields = ['email'] interfaces = (graphene.relay.Node, ) class UserInput(graphene.InputObjectType):",
"UndeleteUserMutation(graphene.Mutation): class Arguments: email = graphene.String(required=True) user = graphene.Field(UserType) def mutate(self, info, email):",
"user = User.objects.create( email=user_data.email ) user.set_password(user_data.password) user.save() return RegisterUserMutation(user=user) class CreateUserMutation(graphene.Mutation): class Arguments:",
"CreateUserMutation(graphene.Mutation): class Arguments: user_data = UserInput(required=True) user = graphene.Field(UserType) def mutate(self, info, user_data=None):",
"DeleteUserMutation(graphene.Mutation): class Arguments: email = graphene.String(required=True) user = graphene.Field(UserType) def mutate(self, info, email):",
"= graphene.String(required=True) first_name = graphene.String() last_name = graphene.String() class Query: me = graphene.Field(UserType)",
"first_name = graphene.String() last_name = graphene.String() class Query: me = graphene.Field(UserType) all_users =",
"class DeleteUserMutation(graphene.Mutation): class Arguments: email = graphene.String(required=True) user = graphene.Field(UserType) def mutate(self, info,",
"User.objects.get(email=email) user.is_active = False #shop.slug = slug+'_deleted' user.save() return DeleteUserMutation(user=user) class UndeleteUserMutation(graphene.Mutation): class",
"User.objects.get(email=email) user.is_active = True #shop.slug = slug.replace('_deleted', '') user.save() return UndeleteUserMutation(user=user) class Mutation(graphene.ObjectType):",
"class UpdateUserMutation(graphene.Mutation): class Arguments: user_data = UserInput(required=True) user = graphene.Field(UserType) def mutate(self, info,",
"True #shop.slug = slug.replace('_deleted', '') user.save() return UndeleteUserMutation(user=user) class Mutation(graphene.ObjectType): register_user = RegisterUserMutation.Field()",
"User.objects.get(email=user_data.email) user.first_name = user_data.first_name user.last_name = user_data.last_name user.save() return UpdateUserMutation(user=user) class DeleteUserMutation(graphene.Mutation): class",
"RegisterUserMutation(user=user) class CreateUserMutation(graphene.Mutation): class Arguments: user_data = UserInput(required=True) user = graphene.Field(UserType) def mutate(self,",
"info.context.user return user class RegisterUserMutation(graphene.Mutation): class Arguments: user_data = UserInput(required=True) user = graphene.Field(UserType)",
"user = User.objects.create( email=user_data.email, first_name=user_data.first_name, last_name=user_data.last_name ) user.set_password(user_data.password) user.save() return CreateUserMutation(user=user) class UpdateUserMutation(graphene.Mutation):",
"= User.objects.get(email=email) user.is_active = False #shop.slug = slug+'_deleted' user.save() return DeleteUserMutation(user=user) class UndeleteUserMutation(graphene.Mutation):",
"info, user_data): user = User.objects.get(email=user_data.email) user.first_name = user_data.first_name user.last_name = user_data.last_name user.save() return",
"class CreateUserMutation(graphene.Mutation): class Arguments: user_data = UserInput(required=True) user = graphene.Field(UserType) def mutate(self, info,",
"= graphene.String(required=True) password = graphene.String(required=True) first_name = graphene.String() last_name = graphene.String() class Query:",
"register_user = RegisterUserMutation.Field() create_user = CreateUserMutation.Field() update_user = UpdateUserMutation.Field() delete_user = DeleteUserMutation.Field() undelete_user",
"graphene.String(required=True) first_name = graphene.String() last_name = graphene.String() class Query: me = graphene.Field(UserType) all_users",
"user.is_active = True #shop.slug = slug.replace('_deleted', '') user.save() return UndeleteUserMutation(user=user) class Mutation(graphene.ObjectType): register_user",
"'__all__' filter_fields = ['email'] interfaces = (graphene.relay.Node, ) class UserInput(graphene.InputObjectType): email = graphene.String(required=True)",
"return user class RegisterUserMutation(graphene.Mutation): class Arguments: user_data = UserInput(required=True) user = graphene.Field(UserType) def",
"first_name=user_data.first_name, last_name=user_data.last_name ) user.set_password(user_data.password) user.save() return CreateUserMutation(user=user) class UpdateUserMutation(graphene.Mutation): class Arguments: user_data =",
"slug.replace('_deleted', '') user.save() return UndeleteUserMutation(user=user) class Mutation(graphene.ObjectType): register_user = RegisterUserMutation.Field() create_user = CreateUserMutation.Field()",
"= User.objects.get(email=user_data.email) user.first_name = user_data.first_name user.last_name = user_data.last_name user.save() return UpdateUserMutation(user=user) class DeleteUserMutation(graphene.Mutation):",
"last_name = graphene.String() class Query: me = graphene.Field(UserType) all_users = DjangoFilterConnectionField(UserType) @login_required def",
"graphene.Field(UserType) def mutate(self, info, user_data=None): user = User.objects.create( email=user_data.email, first_name=user_data.first_name, last_name=user_data.last_name ) user.set_password(user_data.password)",
"UserInput(required=True) user = graphene.Field(UserType) def mutate(self, info, user_data=None): user = User.objects.create( email=user_data.email, first_name=user_data.first_name,",
"email=user_data.email, first_name=user_data.first_name, last_name=user_data.last_name ) user.set_password(user_data.password) user.save() return CreateUserMutation(user=user) class UpdateUserMutation(graphene.Mutation): class Arguments: user_data",
"= graphene.String(required=True) user = graphene.Field(UserType) def mutate(self, info, email): user = User.objects.get(email=email) user.is_active",
"= False #shop.slug = slug+'_deleted' user.save() return DeleteUserMutation(user=user) class UndeleteUserMutation(graphene.Mutation): class Arguments: email",
"import django_filters from graphene_django import DjangoObjectType, DjangoListField from graphene_django.filter import DjangoFilterConnectionField from graphql_jwt.decorators",
"Arguments: user_data = UserInput(required=True) user = graphene.Field(UserType) def mutate(self, info, user_data): user =",
"Meta: model = User fields = '__all__' filter_fields = ['email'] interfaces = (graphene.relay.Node,",
"= User.objects.create( email=user_data.email, first_name=user_data.first_name, last_name=user_data.last_name ) user.set_password(user_data.password) user.save() return CreateUserMutation(user=user) class UpdateUserMutation(graphene.Mutation): class",
"class Meta: model = User fields = '__all__' filter_fields = ['email'] interfaces =",
"DjangoFilterConnectionField from graphql_jwt.decorators import login_required from .models import User class UserType(DjangoObjectType): class Meta:",
"DjangoListField from graphene_django.filter import DjangoFilterConnectionField from graphql_jwt.decorators import login_required from .models import User",
"UserType(DjangoObjectType): class Meta: model = User fields = '__all__' filter_fields = ['email'] interfaces",
") user.set_password(user_data.password) user.save() return CreateUserMutation(user=user) class UpdateUserMutation(graphene.Mutation): class Arguments: user_data = UserInput(required=True) user",
"graphene_django.filter import DjangoFilterConnectionField from graphql_jwt.decorators import login_required from .models import User class UserType(DjangoObjectType):",
"import User class UserType(DjangoObjectType): class Meta: model = User fields = '__all__' filter_fields",
"Mutation(graphene.ObjectType): register_user = RegisterUserMutation.Field() create_user = CreateUserMutation.Field() update_user = UpdateUserMutation.Field() delete_user = DeleteUserMutation.Field()",
"def mutate(self, info, email): user = User.objects.get(email=email) user.is_active = True #shop.slug = slug.replace('_deleted',",
"= slug+'_deleted' user.save() return DeleteUserMutation(user=user) class UndeleteUserMutation(graphene.Mutation): class Arguments: email = graphene.String(required=True) user",
"email): user = User.objects.get(email=email) user.is_active = True #shop.slug = slug.replace('_deleted', '') user.save() return",
"email=user_data.email ) user.set_password(user_data.password) user.save() return RegisterUserMutation(user=user) class CreateUserMutation(graphene.Mutation): class Arguments: user_data = UserInput(required=True)",
"from .models import User class UserType(DjangoObjectType): class Meta: model = User fields =",
"= graphene.Field(UserType) def mutate(self, info, email): user = User.objects.get(email=email) user.is_active = False #shop.slug",
"graphene.Field(UserType) all_users = DjangoFilterConnectionField(UserType) @login_required def resolve_me(self, info): user = info.context.user return user",
"class UserType(DjangoObjectType): class Meta: model = User fields = '__all__' filter_fields = ['email']",
"user.is_active = False #shop.slug = slug+'_deleted' user.save() return DeleteUserMutation(user=user) class UndeleteUserMutation(graphene.Mutation): class Arguments:",
"def mutate(self, info, user_data=None): user = User.objects.create( email=user_data.email ) user.set_password(user_data.password) user.save() return RegisterUserMutation(user=user)",
"mutate(self, info, email): user = User.objects.get(email=email) user.is_active = True #shop.slug = slug.replace('_deleted', '')",
"= graphene.Field(UserType) def mutate(self, info, user_data=None): user = User.objects.create( email=user_data.email, first_name=user_data.first_name, last_name=user_data.last_name )",
"import graphene import django_filters from graphene_django import DjangoObjectType, DjangoListField from graphene_django.filter import DjangoFilterConnectionField",
"def mutate(self, info, email): user = User.objects.get(email=email) user.is_active = False #shop.slug = slug+'_deleted'",
"user = graphene.Field(UserType) def mutate(self, info, email): user = User.objects.get(email=email) user.is_active = True",
"info): user = info.context.user return user class RegisterUserMutation(graphene.Mutation): class Arguments: user_data = UserInput(required=True)",
"Arguments: user_data = UserInput(required=True) user = graphene.Field(UserType) def mutate(self, info, user_data=None): user =",
"info, email): user = User.objects.get(email=email) user.is_active = True #shop.slug = slug.replace('_deleted', '') user.save()",
"import DjangoObjectType, DjangoListField from graphene_django.filter import DjangoFilterConnectionField from graphql_jwt.decorators import login_required from .models",
"graphene import django_filters from graphene_django import DjangoObjectType, DjangoListField from graphene_django.filter import DjangoFilterConnectionField from",
"user = User.objects.get(email=user_data.email) user.first_name = user_data.first_name user.last_name = user_data.last_name user.save() return UpdateUserMutation(user=user) class",
"DjangoObjectType, DjangoListField from graphene_django.filter import DjangoFilterConnectionField from graphql_jwt.decorators import login_required from .models import",
"UpdateUserMutation(graphene.Mutation): class Arguments: user_data = UserInput(required=True) user = graphene.Field(UserType) def mutate(self, info, user_data):",
"user_data.last_name user.save() return UpdateUserMutation(user=user) class DeleteUserMutation(graphene.Mutation): class Arguments: email = graphene.String(required=True) user =",
"info, user_data=None): user = User.objects.create( email=user_data.email, first_name=user_data.first_name, last_name=user_data.last_name ) user.set_password(user_data.password) user.save() return CreateUserMutation(user=user)",
"last_name=user_data.last_name ) user.set_password(user_data.password) user.save() return CreateUserMutation(user=user) class UpdateUserMutation(graphene.Mutation): class Arguments: user_data = UserInput(required=True)",
") user.set_password(user_data.password) user.save() return RegisterUserMutation(user=user) class CreateUserMutation(graphene.Mutation): class Arguments: user_data = UserInput(required=True) user",
"= '__all__' filter_fields = ['email'] interfaces = (graphene.relay.Node, ) class UserInput(graphene.InputObjectType): email =",
"email = graphene.String(required=True) user = graphene.Field(UserType) def mutate(self, info, email): user = User.objects.get(email=email)",
"user.first_name = user_data.first_name user.last_name = user_data.last_name user.save() return UpdateUserMutation(user=user) class DeleteUserMutation(graphene.Mutation): class Arguments:",
"user = info.context.user return user class RegisterUserMutation(graphene.Mutation): class Arguments: user_data = UserInput(required=True) user",
"user.save() return UndeleteUserMutation(user=user) class Mutation(graphene.ObjectType): register_user = RegisterUserMutation.Field() create_user = CreateUserMutation.Field() update_user =",
"user.last_name = user_data.last_name user.save() return UpdateUserMutation(user=user) class DeleteUserMutation(graphene.Mutation): class Arguments: email = graphene.String(required=True)",
"UserInput(graphene.InputObjectType): email = graphene.String(required=True) password = graphene.String(required=True) first_name = graphene.String() last_name = graphene.String()",
"= graphene.String() class Query: me = graphene.Field(UserType) all_users = DjangoFilterConnectionField(UserType) @login_required def resolve_me(self,",
"@login_required def resolve_me(self, info): user = info.context.user return user class RegisterUserMutation(graphene.Mutation): class Arguments:",
"= UserInput(required=True) user = graphene.Field(UserType) def mutate(self, info, user_data): user = User.objects.get(email=user_data.email) user.first_name",
"info, email): user = User.objects.get(email=email) user.is_active = False #shop.slug = slug+'_deleted' user.save() return",
"#shop.slug = slug.replace('_deleted', '') user.save() return UndeleteUserMutation(user=user) class Mutation(graphene.ObjectType): register_user = RegisterUserMutation.Field() create_user",
"fields = '__all__' filter_fields = ['email'] interfaces = (graphene.relay.Node, ) class UserInput(graphene.InputObjectType): email",
"user.save() return DeleteUserMutation(user=user) class UndeleteUserMutation(graphene.Mutation): class Arguments: email = graphene.String(required=True) user = graphene.Field(UserType)",
"graphene.String() last_name = graphene.String() class Query: me = graphene.Field(UserType) all_users = DjangoFilterConnectionField(UserType) @login_required",
"class Arguments: email = graphene.String(required=True) user = graphene.Field(UserType) def mutate(self, info, email): user",
"user_data=None): user = User.objects.create( email=user_data.email, first_name=user_data.first_name, last_name=user_data.last_name ) user.set_password(user_data.password) user.save() return CreateUserMutation(user=user) class",
"info, user_data=None): user = User.objects.create( email=user_data.email ) user.set_password(user_data.password) user.save() return RegisterUserMutation(user=user) class CreateUserMutation(graphene.Mutation):",
"= info.context.user return user class RegisterUserMutation(graphene.Mutation): class Arguments: user_data = UserInput(required=True) user =",
"user_data): user = User.objects.get(email=user_data.email) user.first_name = user_data.first_name user.last_name = user_data.last_name user.save() return UpdateUserMutation(user=user)",
"user.set_password(user_data.password) user.save() return CreateUserMutation(user=user) class UpdateUserMutation(graphene.Mutation): class Arguments: user_data = UserInput(required=True) user =",
"return RegisterUserMutation(user=user) class CreateUserMutation(graphene.Mutation): class Arguments: user_data = UserInput(required=True) user = graphene.Field(UserType) def",
"Arguments: email = graphene.String(required=True) user = graphene.Field(UserType) def mutate(self, info, email): user =",
"authenticate, login import graphene import django_filters from graphene_django import DjangoObjectType, DjangoListField from graphene_django.filter",
"= user_data.first_name user.last_name = user_data.last_name user.save() return UpdateUserMutation(user=user) class DeleteUserMutation(graphene.Mutation): class Arguments: email",
"DeleteUserMutation(user=user) class UndeleteUserMutation(graphene.Mutation): class Arguments: email = graphene.String(required=True) user = graphene.Field(UserType) def mutate(self,",
"mutate(self, info, user_data=None): user = User.objects.create( email=user_data.email, first_name=user_data.first_name, last_name=user_data.last_name ) user.set_password(user_data.password) user.save() return",
"UserInput(required=True) user = graphene.Field(UserType) def mutate(self, info, user_data=None): user = User.objects.create( email=user_data.email )",
"return UndeleteUserMutation(user=user) class Mutation(graphene.ObjectType): register_user = RegisterUserMutation.Field() create_user = CreateUserMutation.Field() update_user = UpdateUserMutation.Field()",
"= user_data.last_name user.save() return UpdateUserMutation(user=user) class DeleteUserMutation(graphene.Mutation): class Arguments: email = graphene.String(required=True) user",
"email = graphene.String(required=True) password = graphene.String(required=True) first_name = graphene.String() last_name = graphene.String() class",
") class UserInput(graphene.InputObjectType): email = graphene.String(required=True) password = graphene.String(required=True) first_name = graphene.String() last_name",
"model = User fields = '__all__' filter_fields = ['email'] interfaces = (graphene.relay.Node, )",
"user = User.objects.get(email=email) user.is_active = True #shop.slug = slug.replace('_deleted', '') user.save() return UndeleteUserMutation(user=user)",
"RegisterUserMutation(graphene.Mutation): class Arguments: user_data = UserInput(required=True) user = graphene.Field(UserType) def mutate(self, info, user_data=None):",
"= ['email'] interfaces = (graphene.relay.Node, ) class UserInput(graphene.InputObjectType): email = graphene.String(required=True) password =",
"User.objects.create( email=user_data.email, first_name=user_data.first_name, last_name=user_data.last_name ) user.set_password(user_data.password) user.save() return CreateUserMutation(user=user) class UpdateUserMutation(graphene.Mutation): class Arguments:",
"login import graphene import django_filters from graphene_django import DjangoObjectType, DjangoListField from graphene_django.filter import",
"user_data.first_name user.last_name = user_data.last_name user.save() return UpdateUserMutation(user=user) class DeleteUserMutation(graphene.Mutation): class Arguments: email =",
"slug+'_deleted' user.save() return DeleteUserMutation(user=user) class UndeleteUserMutation(graphene.Mutation): class Arguments: email = graphene.String(required=True) user =",
"import authenticate, login import graphene import django_filters from graphene_django import DjangoObjectType, DjangoListField from",
"class Query: me = graphene.Field(UserType) all_users = DjangoFilterConnectionField(UserType) @login_required def resolve_me(self, info): user",
"return DeleteUserMutation(user=user) class UndeleteUserMutation(graphene.Mutation): class Arguments: email = graphene.String(required=True) user = graphene.Field(UserType) def",
"class Arguments: user_data = UserInput(required=True) user = graphene.Field(UserType) def mutate(self, info, user_data): user",
"return UpdateUserMutation(user=user) class DeleteUserMutation(graphene.Mutation): class Arguments: email = graphene.String(required=True) user = graphene.Field(UserType) def",
"= UserInput(required=True) user = graphene.Field(UserType) def mutate(self, info, user_data=None): user = User.objects.create( email=user_data.email,",
"graphene.Field(UserType) def mutate(self, info, user_data): user = User.objects.get(email=user_data.email) user.first_name = user_data.first_name user.last_name =",
"UserInput(required=True) user = graphene.Field(UserType) def mutate(self, info, user_data): user = User.objects.get(email=user_data.email) user.first_name =",
"= User.objects.get(email=email) user.is_active = True #shop.slug = slug.replace('_deleted', '') user.save() return UndeleteUserMutation(user=user) class",
"user_data = UserInput(required=True) user = graphene.Field(UserType) def mutate(self, info, user_data): user = User.objects.get(email=user_data.email)",
"= slug.replace('_deleted', '') user.save() return UndeleteUserMutation(user=user) class Mutation(graphene.ObjectType): register_user = RegisterUserMutation.Field() create_user =",
"user.save() return RegisterUserMutation(user=user) class CreateUserMutation(graphene.Mutation): class Arguments: user_data = UserInput(required=True) user = graphene.Field(UserType)",
"UpdateUserMutation(user=user) class DeleteUserMutation(graphene.Mutation): class Arguments: email = graphene.String(required=True) user = graphene.Field(UserType) def mutate(self,",
"= (graphene.relay.Node, ) class UserInput(graphene.InputObjectType): email = graphene.String(required=True) password = graphene.String(required=True) first_name =",
"user_data = UserInput(required=True) user = graphene.Field(UserType) def mutate(self, info, user_data=None): user = User.objects.create(",
"= User fields = '__all__' filter_fields = ['email'] interfaces = (graphene.relay.Node, ) class",
"mutate(self, info, email): user = User.objects.get(email=email) user.is_active = False #shop.slug = slug+'_deleted' user.save()",
"from graphene_django import DjangoObjectType, DjangoListField from graphene_django.filter import DjangoFilterConnectionField from graphql_jwt.decorators import login_required",
"me = graphene.Field(UserType) all_users = DjangoFilterConnectionField(UserType) @login_required def resolve_me(self, info): user = info.context.user",
"email): user = User.objects.get(email=email) user.is_active = False #shop.slug = slug+'_deleted' user.save() return DeleteUserMutation(user=user)",
"= graphene.Field(UserType) def mutate(self, info, email): user = User.objects.get(email=email) user.is_active = True #shop.slug",
"= UserInput(required=True) user = graphene.Field(UserType) def mutate(self, info, user_data=None): user = User.objects.create( email=user_data.email",
"user.save() return UpdateUserMutation(user=user) class DeleteUserMutation(graphene.Mutation): class Arguments: email = graphene.String(required=True) user = graphene.Field(UserType)",
"user class RegisterUserMutation(graphene.Mutation): class Arguments: user_data = UserInput(required=True) user = graphene.Field(UserType) def mutate(self,",
"class UserInput(graphene.InputObjectType): email = graphene.String(required=True) password = graphene.String(required=True) first_name = graphene.String() last_name =",
"from django.contrib.auth import authenticate, login import graphene import django_filters from graphene_django import DjangoObjectType,",
"= RegisterUserMutation.Field() create_user = CreateUserMutation.Field() update_user = UpdateUserMutation.Field() delete_user = DeleteUserMutation.Field() undelete_user =",
"all_users = DjangoFilterConnectionField(UserType) @login_required def resolve_me(self, info): user = info.context.user return user class",
"User.objects.create( email=user_data.email ) user.set_password(user_data.password) user.save() return RegisterUserMutation(user=user) class CreateUserMutation(graphene.Mutation): class Arguments: user_data =",
"django_filters from graphene_django import DjangoObjectType, DjangoListField from graphene_django.filter import DjangoFilterConnectionField from graphql_jwt.decorators import",
"= graphene.Field(UserType) all_users = DjangoFilterConnectionField(UserType) @login_required def resolve_me(self, info): user = info.context.user return",
"user = graphene.Field(UserType) def mutate(self, info, user_data=None): user = User.objects.create( email=user_data.email ) user.set_password(user_data.password)",
"#shop.slug = slug+'_deleted' user.save() return DeleteUserMutation(user=user) class UndeleteUserMutation(graphene.Mutation): class Arguments: email = graphene.String(required=True)",
"graphene.Field(UserType) def mutate(self, info, user_data=None): user = User.objects.create( email=user_data.email ) user.set_password(user_data.password) user.save() return",
"graphene.String() class Query: me = graphene.Field(UserType) all_users = DjangoFilterConnectionField(UserType) @login_required def resolve_me(self, info):",
"resolve_me(self, info): user = info.context.user return user class RegisterUserMutation(graphene.Mutation): class Arguments: user_data =",
"filter_fields = ['email'] interfaces = (graphene.relay.Node, ) class UserInput(graphene.InputObjectType): email = graphene.String(required=True) password",
"user.set_password(user_data.password) user.save() return RegisterUserMutation(user=user) class CreateUserMutation(graphene.Mutation): class Arguments: user_data = UserInput(required=True) user =",
"= User.objects.create( email=user_data.email ) user.set_password(user_data.password) user.save() return RegisterUserMutation(user=user) class CreateUserMutation(graphene.Mutation): class Arguments: user_data",
"from graphql_jwt.decorators import login_required from .models import User class UserType(DjangoObjectType): class Meta: model",
"mutate(self, info, user_data): user = User.objects.get(email=user_data.email) user.first_name = user_data.first_name user.last_name = user_data.last_name user.save()",
"graphene.String(required=True) password = graphene.String(required=True) first_name = graphene.String() last_name = graphene.String() class Query: me",
"from graphene_django.filter import DjangoFilterConnectionField from graphql_jwt.decorators import login_required from .models import User class",
"CreateUserMutation(user=user) class UpdateUserMutation(graphene.Mutation): class Arguments: user_data = UserInput(required=True) user = graphene.Field(UserType) def mutate(self,",
"graphql_jwt.decorators import login_required from .models import User class UserType(DjangoObjectType): class Meta: model =",
"import login_required from .models import User class UserType(DjangoObjectType): class Meta: model = User",
"user.save() return CreateUserMutation(user=user) class UpdateUserMutation(graphene.Mutation): class Arguments: user_data = UserInput(required=True) user = graphene.Field(UserType)",
"= graphene.String() last_name = graphene.String() class Query: me = graphene.Field(UserType) all_users = DjangoFilterConnectionField(UserType)",
"DjangoFilterConnectionField(UserType) @login_required def resolve_me(self, info): user = info.context.user return user class RegisterUserMutation(graphene.Mutation): class",
"RegisterUserMutation.Field() create_user = CreateUserMutation.Field() update_user = UpdateUserMutation.Field() delete_user = DeleteUserMutation.Field() undelete_user = UndeleteUserMutation.Field()",
".models import User class UserType(DjangoObjectType): class Meta: model = User fields = '__all__'",
"def mutate(self, info, user_data): user = User.objects.get(email=user_data.email) user.first_name = user_data.first_name user.last_name = user_data.last_name",
"graphene.Field(UserType) def mutate(self, info, email): user = User.objects.get(email=email) user.is_active = True #shop.slug =",
"django.contrib.auth import authenticate, login import graphene import django_filters from graphene_django import DjangoObjectType, DjangoListField",
"User class UserType(DjangoObjectType): class Meta: model = User fields = '__all__' filter_fields =",
"['email'] interfaces = (graphene.relay.Node, ) class UserInput(graphene.InputObjectType): email = graphene.String(required=True) password = graphene.String(required=True)",
"user = graphene.Field(UserType) def mutate(self, info, email): user = User.objects.get(email=email) user.is_active = False",
"mutate(self, info, user_data=None): user = User.objects.create( email=user_data.email ) user.set_password(user_data.password) user.save() return RegisterUserMutation(user=user) class",
"def mutate(self, info, user_data=None): user = User.objects.create( email=user_data.email, first_name=user_data.first_name, last_name=user_data.last_name ) user.set_password(user_data.password) user.save()",
"(graphene.relay.Node, ) class UserInput(graphene.InputObjectType): email = graphene.String(required=True) password = graphene.String(required=True) first_name = graphene.String()",
"= DjangoFilterConnectionField(UserType) @login_required def resolve_me(self, info): user = info.context.user return user class RegisterUserMutation(graphene.Mutation):"
] |
[
"{item.new_slot.starts_at}') if solution is not None: allocations = defn.allocations(resources) unbounded = defn.unbounded(resources) defn.add_allocations(events,",
"'error', 'warning', 'info', 'debug']), help='Logging verbosity') def scheduler(verbosity): pass @scheduler.command() @click.option( '--verbosity', '-v',",
"in original_solution if item[0] < len(events)] else: solution = io.import_solution(session.folders['solution']) definition = io.import_schedule_definition(session.folders['solution'])",
"algorithm') @click.option( '--objective', '-o', default=None, type=click.Choice(['efficiency', 'equity', 'consistency']), help='Objective Function') @click.option('--diff/--no-diff', default=False, help='Show",
"= [ item for item in original_solution if item[0] < len(events)] original_schedule =",
"None: allocations = defn.allocations(resources) unbounded = defn.unbounded(resources) defn.add_allocations(events, slots, solution, allocations, unbounded) logger.debug(convert.schedule_to_text(solution,",
"= defn.resources() events, slots = events_and_slots(resources) slots_by_index = { idx: f'{slot.starts_at} {slot.venue}' for",
"'info', 'debug']), help='Logging verbosity') @click.option( '--input_dir', '-i', default=None, help='Directory for input files') @click.option(",
"pathlib import Path import click from conference_scheduler.scheduler import event_schedule_difference from conference_scheduler.converter import solution_to_schedule",
"'--verbosity', '-v', default='info', type=click.Choice(['critical', 'error', 'warning', 'info', 'debug']), help='Logging verbosity') @click.option( '--input_dir', '-i',",
"== 'simulated_annealing' or diff: original_solution = io.import_solution(session.folders['solution']) revised_solution = [ item for item",
"= io.import_solution(session.folders['solution']) solution = [ item for item in original_solution if item[0] <",
"solution, session.folders['solution']) @scheduler.command() @click.option( '--verbosity', '-v', default='info', type=click.Choice(['critical', 'error', 'warning', 'info', 'debug']), help='Logging",
"for output yaml files') @timed def build( verbosity, algorithm, objective, diff, input_dir, solution_dir,",
"'--build_dir', '-b', default=None, help='Directory for output yaml files') @timed def build( verbosity, algorithm,",
"= defn.unavailability(resources, slots) clashes = defn.clashes(resources) unsuitability = defn.unsuitability(resources, slots) defn.add_unavailability_to_events(events, slots, unavailability)",
"help='Logging verbosity') def scheduler(verbosity): pass @scheduler.command() @click.option( '--verbosity', '-v', default='info', type=click.Choice(['critical', 'error', 'warning',",
"events = definition['events'] slots = definition['slots'] logger.info('Validating schedule...') if is_valid_solution(solution, events, slots): logger.info('Imported",
"import ( is_valid_solution, solution_violations) import daiquiri import scheduler.calculate as calc from scheduler.decorators import",
"slots, unavailability) defn.add_clashes_to_events(events, clashes) defn.add_unsuitability_to_events(events, slots, unsuitability) return events, slots @click.version_option(message='%(prog)s %(version)s ::",
"'-v', default='info', type=click.Choice(['critical', 'error', 'warning', 'info', 'debug']), help='Logging verbosity') @click.option( '--algorithm', '-a', default='pulp_cbc_cmd',",
"( is_valid_solution, solution_violations) import daiquiri import scheduler.calculate as calc from scheduler.decorators import timed",
"from pathlib import Path import click from conference_scheduler.scheduler import event_schedule_difference from conference_scheduler.converter import",
"diff: schedule = solution_to_schedule(solution, events, slots) event_diff = event_schedule_difference(original_schedule, schedule) logger.debug(f'\\nevent_diff:') for item",
"defn.add_allocations(events, slots, solution, allocations, unbounded) logger.debug(convert.schedule_to_text(solution, events, slots)) io.export_solution_and_definition( resources, events, slots, allocations,",
"return events, slots @click.version_option(message='%(prog)s %(version)s :: UK Python Association') @click.group() @click.option( '--verbosity', '-v',",
"'-v', default='info', type=click.Choice(['critical', 'error', 'warning', 'info', 'debug']), help='Logging verbosity') @click.option( '--input_dir', '-i', default=None,",
"defn.unavailability(resources, slots) clashes = defn.clashes(resources) unsuitability = defn.unsuitability(resources, slots) defn.add_unavailability_to_events(events, slots, unavailability) defn.add_clashes_to_events(events,",
"item for item in original_solution if item[0] < len(events)] else: solution = io.import_solution(session.folders['solution'])",
"{} if objective == 'consistency' or algorithm == 'simulated_annealing' or diff: original_solution =",
"at {item.old_slot.starts_at} to {item.new_slot.venue} at {item.new_slot.starts_at}') if solution is not None: allocations =",
"for idx, slot in enumerate(slots)} logger.debug(f'\\nSlots List:\\n{slots_by_index}') kwargs = {} if objective ==",
"io.import_solution(session.folders['solution']) if reload: resources = defn.resources() events, slots = events_and_slots(resources) original_solution = io.import_solution(session.folders['solution'])",
"help='Objective Function') @click.option('--diff/--no-diff', default=False, help='Show schedule diff') @click.option( '--input_dir', '-i', default=None, help='Directory for",
"import scheduler.define as defn from scheduler import convert, io, logging, session logger =",
"'debug']), help='Logging verbosity') def scheduler(verbosity): pass @scheduler.command() @click.option( '--verbosity', '-v', default='info', type=click.Choice(['critical', 'error',",
"type=click.Choice(['critical', 'error', 'warning', 'info', 'debug']), help='Logging verbosity') @click.option( '--input_dir', '-i', default=None, help='Directory for",
"original_solution = io.import_solution(session.folders['solution']) revised_solution = [ item for item in original_solution if item[0]",
"solution_dir: session.folders['solution'] = Path(solution_dir) if build_dir: session.folders['build'] = Path(build_dir) resources = defn.resources() events,",
"or algorithm == 'simulated_annealing' or diff: original_solution = io.import_solution(session.folders['solution']) revised_solution = [ item",
"input_dir, solution_dir, reload): logging.setup(verbosity) if solution_dir: session.folders['solution'] = Path(solution_dir) solution = io.import_solution(session.folders['solution']) if",
"help='Logging verbosity') @click.option( '--algorithm', '-a', default='pulp_cbc_cmd', type=click.Choice( ['pulp_cbc_cmd', 'glpk', 'hill_climber', 'simulated_annealing']), help='Solver algorithm')",
"solution_to_schedule from conference_scheduler.validator import ( is_valid_solution, solution_violations) import daiquiri import scheduler.calculate as calc",
"type=click.Choice( ['pulp_cbc_cmd', 'glpk', 'hill_climber', 'simulated_annealing']), help='Solver algorithm') @click.option( '--objective', '-o', default=None, type=click.Choice(['efficiency', 'equity',",
"< len(events)] original_schedule = solution_to_schedule( revised_solution, events, slots) diff = True kwargs['original_schedule'] =",
"solution_to_schedule(solution, events, slots) event_diff = event_schedule_difference(original_schedule, schedule) logger.debug(f'\\nevent_diff:') for item in event_diff: logger.debug(f'{item.event.name}",
"import event_schedule_difference from conference_scheduler.converter import solution_to_schedule from conference_scheduler.validator import ( is_valid_solution, solution_violations) import",
"solution_dir: session.folders['solution'] = Path(solution_dir) solution = io.import_solution(session.folders['solution']) if reload: resources = defn.resources() events,",
"original_schedule = solution_to_schedule( revised_solution, events, slots) diff = True kwargs['original_schedule'] = original_schedule solution",
"objective, diff, input_dir, solution_dir, build_dir ): logging.setup(verbosity) if input_dir: session.folders['input'] = Path(input_dir) if",
"@click.option( '--verbosity', '-v', default='info', type=click.Choice(['critical', 'error', 'warning', 'info', 'debug']), help='Logging verbosity') @click.option( '--input_dir',",
"diff') @click.option( '--input_dir', '-i', default=None, help='Directory for input files') @click.option( '--solution_dir', '-s', default=None,",
"default='pulp_cbc_cmd', type=click.Choice( ['pulp_cbc_cmd', 'glpk', 'hill_climber', 'simulated_annealing']), help='Solver algorithm') @click.option( '--objective', '-o', default=None, type=click.Choice(['efficiency',",
"io.import_solution(session.folders['solution']) revised_solution = [ item for item in original_solution if item[0] < len(events)]",
"session logger = daiquiri.getLogger(__name__) def events_and_slots(resources): slots = defn.slots(resources) events = defn.events(resources) unavailability",
"slots)) io.export_solution_and_definition( resources, events, slots, allocations, solution, session.folders['solution']) @scheduler.command() @click.option( '--verbosity', '-v', default='info',",
"session.folders['solution'] = Path(solution_dir) if build_dir: session.folders['build'] = Path(build_dir) resources = defn.resources() events, slots",
"events, slots)) io.export_solution_and_definition( resources, events, slots, allocations, solution, session.folders['solution']) @scheduler.command() @click.option( '--verbosity', '-v',",
"input_dir: session.folders['input'] = Path(input_dir) if solution_dir: session.folders['solution'] = Path(solution_dir) if build_dir: session.folders['build'] =",
"kwargs['original_schedule'] = original_schedule solution = calc.solution(events, slots, algorithm, objective, **kwargs) if diff: schedule",
"'--solution_dir', '-s', default=None, help='Directory for solution files') @click.option( '--build_dir', '-b', default=None, help='Directory for",
"from {item.old_slot.venue} at {item.old_slot.starts_at} to {item.new_slot.venue} at {item.new_slot.starts_at}') if solution is not None:",
"unavailability = defn.unavailability(resources, slots) clashes = defn.clashes(resources) unsuitability = defn.unsuitability(resources, slots) defn.add_unavailability_to_events(events, slots,",
"original_solution = io.import_solution(session.folders['solution']) solution = [ item for item in original_solution if item[0]",
"= event_schedule_difference(original_schedule, schedule) logger.debug(f'\\nevent_diff:') for item in event_diff: logger.debug(f'{item.event.name} has moved from {item.old_slot.venue}",
"import click from conference_scheduler.scheduler import event_schedule_difference from conference_scheduler.converter import solution_to_schedule from conference_scheduler.validator import",
"events, slots = events_and_slots(resources) slots_by_index = { idx: f'{slot.starts_at} {slot.venue}' for idx, slot",
"events, slots) event_diff = event_schedule_difference(original_schedule, schedule) logger.debug(f'\\nevent_diff:') for item in event_diff: logger.debug(f'{item.event.name} has",
"@click.option( '--reload/--no-reload', default=False, help='Reload YAML definition') @timed def validate(verbosity, input_dir, solution_dir, reload): logging.setup(verbosity)",
"event_schedule_difference(original_schedule, schedule) logger.debug(f'\\nevent_diff:') for item in event_diff: logger.debug(f'{item.event.name} has moved from {item.old_slot.venue} at",
"is not None: allocations = defn.allocations(resources) unbounded = defn.unbounded(resources) defn.add_allocations(events, slots, solution, allocations,",
"help='Solver algorithm') @click.option( '--objective', '-o', default=None, type=click.Choice(['efficiency', 'equity', 'consistency']), help='Objective Function') @click.option('--diff/--no-diff', default=False,",
"scheduler import convert, io, logging, session logger = daiquiri.getLogger(__name__) def events_and_slots(resources): slots =",
"= io.import_schedule_definition(session.folders['solution']) events = definition['events'] slots = definition['slots'] logger.info('Validating schedule...') if is_valid_solution(solution, events,",
"@scheduler.command() @click.option( '--verbosity', '-v', default='info', type=click.Choice(['critical', 'error', 'warning', 'info', 'debug']), help='Logging verbosity') @click.option(",
"= Path(input_dir) if solution_dir: session.folders['solution'] = Path(solution_dir) if build_dir: session.folders['build'] = Path(build_dir) resources",
"= defn.slots(resources) events = defn.events(resources) unavailability = defn.unavailability(resources, slots) clashes = defn.clashes(resources) unsuitability",
"files') @click.option( '--solution_dir', '-s', default=None, help='Directory for solution files') @click.option( '--build_dir', '-b', default=None,",
"input_dir, solution_dir, build_dir ): logging.setup(verbosity) if input_dir: session.folders['input'] = Path(input_dir) if solution_dir: session.folders['solution']",
"default=None, help='Directory for solution files') @click.option( '--reload/--no-reload', default=False, help='Reload YAML definition') @timed def",
"'simulated_annealing']), help='Solver algorithm') @click.option( '--objective', '-o', default=None, type=click.Choice(['efficiency', 'equity', 'consistency']), help='Objective Function') @click.option('--diff/--no-diff',",
"help='Directory for solution files') @click.option( '--build_dir', '-b', default=None, help='Directory for output yaml files')",
":: UK Python Association') @click.group() @click.option( '--verbosity', '-v', default='info', type=click.Choice(['critical', 'error', 'warning', 'info',",
"= Path(build_dir) resources = defn.resources() events, slots = events_and_slots(resources) slots_by_index = { idx:",
"for item in original_solution if item[0] < len(events)] else: solution = io.import_solution(session.folders['solution']) definition",
"'--algorithm', '-a', default='pulp_cbc_cmd', type=click.Choice( ['pulp_cbc_cmd', 'glpk', 'hill_climber', 'simulated_annealing']), help='Solver algorithm') @click.option( '--objective', '-o',",
"item[0] < len(events)] else: solution = io.import_solution(session.folders['solution']) definition = io.import_schedule_definition(session.folders['solution']) events = definition['events']",
"%(version)s :: UK Python Association') @click.group() @click.option( '--verbosity', '-v', default='info', type=click.Choice(['critical', 'error', 'warning',",
"if item[0] < len(events)] original_schedule = solution_to_schedule( revised_solution, events, slots) diff = True",
"for item in event_diff: logger.debug(f'{item.event.name} has moved from {item.old_slot.venue} at {item.old_slot.starts_at} to {item.new_slot.venue}",
"'consistency' or algorithm == 'simulated_annealing' or diff: original_solution = io.import_solution(session.folders['solution']) revised_solution = [",
"solution = io.import_solution(session.folders['solution']) definition = io.import_schedule_definition(session.folders['solution']) events = definition['events'] slots = definition['slots'] logger.info('Validating",
"the Command Line Interface (cli)\"\"\" from pathlib import Path import click from conference_scheduler.scheduler",
"pass @scheduler.command() @click.option( '--verbosity', '-v', default='info', type=click.Choice(['critical', 'error', 'warning', 'info', 'debug']), help='Logging verbosity')",
"events, slots, allocations, solution, session.folders['solution']) @scheduler.command() @click.option( '--verbosity', '-v', default='info', type=click.Choice(['critical', 'error', 'warning',",
"Python Association') @click.group() @click.option( '--verbosity', '-v', default='info', type=click.Choice(['critical', 'error', 'warning', 'info', 'debug']), help='Logging",
"unsuitability) return events, slots @click.version_option(message='%(prog)s %(version)s :: UK Python Association') @click.group() @click.option( '--verbosity',",
"objective == 'consistency' or algorithm == 'simulated_annealing' or diff: original_solution = io.import_solution(session.folders['solution']) revised_solution",
"item in original_solution if item[0] < len(events)] original_schedule = solution_to_schedule( revised_solution, events, slots)",
"definition['slots'] logger.info('Validating schedule...') if is_valid_solution(solution, events, slots): logger.info('Imported solution is valid') else: for",
"'--objective', '-o', default=None, type=click.Choice(['efficiency', 'equity', 'consistency']), help='Objective Function') @click.option('--diff/--no-diff', default=False, help='Show schedule diff')",
"'simulated_annealing' or diff: original_solution = io.import_solution(session.folders['solution']) revised_solution = [ item for item in",
"default=False, help='Show schedule diff') @click.option( '--input_dir', '-i', default=None, help='Directory for input files') @click.option(",
"@click.option( '--verbosity', '-v', default='info', type=click.Choice(['critical', 'error', 'warning', 'info', 'debug']), help='Logging verbosity') @click.option( '--algorithm',",
"item in event_diff: logger.debug(f'{item.event.name} has moved from {item.old_slot.venue} at {item.old_slot.starts_at} to {item.new_slot.venue} at",
"defn.allocations(resources) unbounded = defn.unbounded(resources) defn.add_allocations(events, slots, solution, allocations, unbounded) logger.debug(convert.schedule_to_text(solution, events, slots)) io.export_solution_and_definition(",
"allocations, solution, session.folders['solution']) @scheduler.command() @click.option( '--verbosity', '-v', default='info', type=click.Choice(['critical', 'error', 'warning', 'info', 'debug']),",
"slots = events_and_slots(resources) slots_by_index = { idx: f'{slot.starts_at} {slot.venue}' for idx, slot in",
"event_diff: logger.debug(f'{item.event.name} has moved from {item.old_slot.venue} at {item.old_slot.starts_at} to {item.new_slot.venue} at {item.new_slot.starts_at}') if",
"calc from scheduler.decorators import timed import scheduler.define as defn from scheduler import convert,",
"schedule...') if is_valid_solution(solution, events, slots): logger.info('Imported solution is valid') else: for v in",
"original_solution if item[0] < len(events)] else: solution = io.import_solution(session.folders['solution']) definition = io.import_schedule_definition(session.folders['solution']) events",
"logger = daiquiri.getLogger(__name__) def events_and_slots(resources): slots = defn.slots(resources) events = defn.events(resources) unavailability =",
"help='Show schedule diff') @click.option( '--input_dir', '-i', default=None, help='Directory for input files') @click.option( '--solution_dir',",
"events_and_slots(resources) slots_by_index = { idx: f'{slot.starts_at} {slot.venue}' for idx, slot in enumerate(slots)} logger.debug(f'\\nSlots",
"Function') @click.option('--diff/--no-diff', default=False, help='Show schedule diff') @click.option( '--input_dir', '-i', default=None, help='Directory for input",
"solution files') @click.option( '--build_dir', '-b', default=None, help='Directory for output yaml files') @timed def",
"slots) defn.add_unavailability_to_events(events, slots, unavailability) defn.add_clashes_to_events(events, clashes) defn.add_unsuitability_to_events(events, slots, unsuitability) return events, slots @click.version_option(message='%(prog)s",
"slots) clashes = defn.clashes(resources) unsuitability = defn.unsuitability(resources, slots) defn.add_unavailability_to_events(events, slots, unavailability) defn.add_clashes_to_events(events, clashes)",
"schedule = solution_to_schedule(solution, events, slots) event_diff = event_schedule_difference(original_schedule, schedule) logger.debug(f'\\nevent_diff:') for item in",
"'error', 'warning', 'info', 'debug']), help='Logging verbosity') @click.option( '--algorithm', '-a', default='pulp_cbc_cmd', type=click.Choice( ['pulp_cbc_cmd', 'glpk',",
"= io.import_solution(session.folders['solution']) definition = io.import_schedule_definition(session.folders['solution']) events = definition['events'] slots = definition['slots'] logger.info('Validating schedule...')",
"UK Python Association') @click.group() @click.option( '--verbosity', '-v', default='info', type=click.Choice(['critical', 'error', 'warning', 'info', 'debug']),",
"events, slots @click.version_option(message='%(prog)s %(version)s :: UK Python Association') @click.group() @click.option( '--verbosity', '-v', default='info',",
"logging, session logger = daiquiri.getLogger(__name__) def events_and_slots(resources): slots = defn.slots(resources) events = defn.events(resources)",
"'info', 'debug']), help='Logging verbosity') @click.option( '--algorithm', '-a', default='pulp_cbc_cmd', type=click.Choice( ['pulp_cbc_cmd', 'glpk', 'hill_climber', 'simulated_annealing']),",
"solution, allocations, unbounded) logger.debug(convert.schedule_to_text(solution, events, slots)) io.export_solution_and_definition( resources, events, slots, allocations, solution, session.folders['solution'])",
"if item[0] < len(events)] else: solution = io.import_solution(session.folders['solution']) definition = io.import_schedule_definition(session.folders['solution']) events =",
"if diff: schedule = solution_to_schedule(solution, events, slots) event_diff = event_schedule_difference(original_schedule, schedule) logger.debug(f'\\nevent_diff:') for",
"solution_dir, reload): logging.setup(verbosity) if solution_dir: session.folders['solution'] = Path(solution_dir) solution = io.import_solution(session.folders['solution']) if reload:",
"for item in original_solution if item[0] < len(events)] original_schedule = solution_to_schedule( revised_solution, events,",
"'consistency']), help='Objective Function') @click.option('--diff/--no-diff', default=False, help='Show schedule diff') @click.option( '--input_dir', '-i', default=None, help='Directory",
"schedule) logger.debug(f'\\nevent_diff:') for item in event_diff: logger.debug(f'{item.event.name} has moved from {item.old_slot.venue} at {item.old_slot.starts_at}",
"build( verbosity, algorithm, objective, diff, input_dir, solution_dir, build_dir ): logging.setup(verbosity) if input_dir: session.folders['input']",
"if solution_dir: session.folders['solution'] = Path(solution_dir) if build_dir: session.folders['build'] = Path(build_dir) resources = defn.resources()",
"import scheduler.calculate as calc from scheduler.decorators import timed import scheduler.define as defn from",
"clashes) defn.add_unsuitability_to_events(events, slots, unsuitability) return events, slots @click.version_option(message='%(prog)s %(version)s :: UK Python Association')",
"@click.option( '--objective', '-o', default=None, type=click.Choice(['efficiency', 'equity', 'consistency']), help='Objective Function') @click.option('--diff/--no-diff', default=False, help='Show schedule",
"as calc from scheduler.decorators import timed import scheduler.define as defn from scheduler import",
"logging.setup(verbosity) if input_dir: session.folders['input'] = Path(input_dir) if solution_dir: session.folders['solution'] = Path(solution_dir) if build_dir:",
"conference_scheduler.converter import solution_to_schedule from conference_scheduler.validator import ( is_valid_solution, solution_violations) import daiquiri import scheduler.calculate",
"= io.import_solution(session.folders['solution']) if reload: resources = defn.resources() events, slots = events_and_slots(resources) original_solution =",
"event_schedule_difference from conference_scheduler.converter import solution_to_schedule from conference_scheduler.validator import ( is_valid_solution, solution_violations) import daiquiri",
"= defn.unsuitability(resources, slots) defn.add_unavailability_to_events(events, slots, unavailability) defn.add_clashes_to_events(events, clashes) defn.add_unsuitability_to_events(events, slots, unsuitability) return events,",
"if reload: resources = defn.resources() events, slots = events_and_slots(resources) original_solution = io.import_solution(session.folders['solution']) solution",
"events_and_slots(resources) original_solution = io.import_solution(session.folders['solution']) solution = [ item for item in original_solution if",
"slots, solution, allocations, unbounded) logger.debug(convert.schedule_to_text(solution, events, slots)) io.export_solution_and_definition( resources, events, slots, allocations, solution,",
"import timed import scheduler.define as defn from scheduler import convert, io, logging, session",
"'hill_climber', 'simulated_annealing']), help='Solver algorithm') @click.option( '--objective', '-o', default=None, type=click.Choice(['efficiency', 'equity', 'consistency']), help='Objective Function')",
"'glpk', 'hill_climber', 'simulated_annealing']), help='Solver algorithm') @click.option( '--objective', '-o', default=None, type=click.Choice(['efficiency', 'equity', 'consistency']), help='Objective",
"from conference_scheduler.scheduler import event_schedule_difference from conference_scheduler.converter import solution_to_schedule from conference_scheduler.validator import ( is_valid_solution,",
"def scheduler(verbosity): pass @scheduler.command() @click.option( '--verbosity', '-v', default='info', type=click.Choice(['critical', 'error', 'warning', 'info', 'debug']),",
"= io.import_solution(session.folders['solution']) revised_solution = [ item for item in original_solution if item[0] <",
"= definition['events'] slots = definition['slots'] logger.info('Validating schedule...') if is_valid_solution(solution, events, slots): logger.info('Imported solution",
"= [ item for item in original_solution if item[0] < len(events)] else: solution",
"scheduler.define as defn from scheduler import convert, io, logging, session logger = daiquiri.getLogger(__name__)",
"or diff: original_solution = io.import_solution(session.folders['solution']) revised_solution = [ item for item in original_solution",
"logger.info('Imported solution is valid') else: for v in solution_violations( solution, definition['events'], definition['slots']): logger.error(v)",
"= daiquiri.getLogger(__name__) def events_and_slots(resources): slots = defn.slots(resources) events = defn.events(resources) unavailability = defn.unavailability(resources,",
"defn.slots(resources) events = defn.events(resources) unavailability = defn.unavailability(resources, slots) clashes = defn.clashes(resources) unsuitability =",
"slots, algorithm, objective, **kwargs) if diff: schedule = solution_to_schedule(solution, events, slots) event_diff =",
"conference_scheduler.scheduler import event_schedule_difference from conference_scheduler.converter import solution_to_schedule from conference_scheduler.validator import ( is_valid_solution, solution_violations)",
"{item.new_slot.venue} at {item.new_slot.starts_at}') if solution is not None: allocations = defn.allocations(resources) unbounded =",
"**kwargs) if diff: schedule = solution_to_schedule(solution, events, slots) event_diff = event_schedule_difference(original_schedule, schedule) logger.debug(f'\\nevent_diff:')",
"solution_dir, build_dir ): logging.setup(verbosity) if input_dir: session.folders['input'] = Path(input_dir) if solution_dir: session.folders['solution'] =",
"event_diff = event_schedule_difference(original_schedule, schedule) logger.debug(f'\\nevent_diff:') for item in event_diff: logger.debug(f'{item.event.name} has moved from",
"as defn from scheduler import convert, io, logging, session logger = daiquiri.getLogger(__name__) def",
"convert, io, logging, session logger = daiquiri.getLogger(__name__) def events_and_slots(resources): slots = defn.slots(resources) events",
"original_solution if item[0] < len(events)] original_schedule = solution_to_schedule( revised_solution, events, slots) diff =",
"= Path(solution_dir) if build_dir: session.folders['build'] = Path(build_dir) resources = defn.resources() events, slots =",
"Path(solution_dir) if build_dir: session.folders['build'] = Path(build_dir) resources = defn.resources() events, slots = events_and_slots(resources)",
"revised_solution, events, slots) diff = True kwargs['original_schedule'] = original_schedule solution = calc.solution(events, slots,",
"'-b', default=None, help='Directory for output yaml files') @timed def build( verbosity, algorithm, objective,",
"diff: original_solution = io.import_solution(session.folders['solution']) revised_solution = [ item for item in original_solution if",
"slots): logger.info('Imported solution is valid') else: for v in solution_violations( solution, definition['events'], definition['slots']):",
"= defn.allocations(resources) unbounded = defn.unbounded(resources) defn.add_allocations(events, slots, solution, allocations, unbounded) logger.debug(convert.schedule_to_text(solution, events, slots))",
"default=None, type=click.Choice(['efficiency', 'equity', 'consistency']), help='Objective Function') @click.option('--diff/--no-diff', default=False, help='Show schedule diff') @click.option( '--input_dir',",
"to define the Command Line Interface (cli)\"\"\" from pathlib import Path import click",
"'info', 'debug']), help='Logging verbosity') def scheduler(verbosity): pass @scheduler.command() @click.option( '--verbosity', '-v', default='info', type=click.Choice(['critical',",
"'equity', 'consistency']), help='Objective Function') @click.option('--diff/--no-diff', default=False, help='Show schedule diff') @click.option( '--input_dir', '-i', default=None,",
"default='info', type=click.Choice(['critical', 'error', 'warning', 'info', 'debug']), help='Logging verbosity') def scheduler(verbosity): pass @scheduler.command() @click.option(",
"'debug']), help='Logging verbosity') @click.option( '--algorithm', '-a', default='pulp_cbc_cmd', type=click.Choice( ['pulp_cbc_cmd', 'glpk', 'hill_climber', 'simulated_annealing']), help='Solver",
"default=None, help='Directory for input files') @click.option( '--solution_dir', '-s', default=None, help='Directory for solution files')",
"events = defn.events(resources) unavailability = defn.unavailability(resources, slots) clashes = defn.clashes(resources) unsuitability = defn.unsuitability(resources,",
"= solution_to_schedule( revised_solution, events, slots) diff = True kwargs['original_schedule'] = original_schedule solution =",
"verbosity') @click.option( '--input_dir', '-i', default=None, help='Directory for input files') @click.option( '--solution_dir', '-s', default=None,",
"revised_solution = [ item for item in original_solution if item[0] < len(events)] original_schedule",
"solution_to_schedule( revised_solution, events, slots) diff = True kwargs['original_schedule'] = original_schedule solution = calc.solution(events,",
"resources = defn.resources() events, slots = events_and_slots(resources) original_solution = io.import_solution(session.folders['solution']) solution = [",
"default=None, help='Directory for output yaml files') @timed def build( verbosity, algorithm, objective, diff,",
"logger.debug(f'\\nevent_diff:') for item in event_diff: logger.debug(f'{item.event.name} has moved from {item.old_slot.venue} at {item.old_slot.starts_at} to",
"Association') @click.group() @click.option( '--verbosity', '-v', default='info', type=click.Choice(['critical', 'error', 'warning', 'info', 'debug']), help='Logging verbosity')",
"definition = io.import_schedule_definition(session.folders['solution']) events = definition['events'] slots = definition['slots'] logger.info('Validating schedule...') if is_valid_solution(solution,",
"logging.setup(verbosity) if solution_dir: session.folders['solution'] = Path(solution_dir) solution = io.import_solution(session.folders['solution']) if reload: resources =",
"def build( verbosity, algorithm, objective, diff, input_dir, solution_dir, build_dir ): logging.setup(verbosity) if input_dir:",
"for input files') @click.option( '--solution_dir', '-s', default=None, help='Directory for solution files') @click.option( '--build_dir',",
"== 'consistency' or algorithm == 'simulated_annealing' or diff: original_solution = io.import_solution(session.folders['solution']) revised_solution =",
"solution = calc.solution(events, slots, algorithm, objective, **kwargs) if diff: schedule = solution_to_schedule(solution, events,",
"is_valid_solution, solution_violations) import daiquiri import scheduler.calculate as calc from scheduler.decorators import timed import",
"= defn.clashes(resources) unsuitability = defn.unsuitability(resources, slots) defn.add_unavailability_to_events(events, slots, unavailability) defn.add_clashes_to_events(events, clashes) defn.add_unsuitability_to_events(events, slots,",
"{ idx: f'{slot.starts_at} {slot.venue}' for idx, slot in enumerate(slots)} logger.debug(f'\\nSlots List:\\n{slots_by_index}') kwargs =",
"calc.solution(events, slots, algorithm, objective, **kwargs) if diff: schedule = solution_to_schedule(solution, events, slots) event_diff",
"slots, allocations, solution, session.folders['solution']) @scheduler.command() @click.option( '--verbosity', '-v', default='info', type=click.Choice(['critical', 'error', 'warning', 'info',",
"{slot.venue}' for idx, slot in enumerate(slots)} logger.debug(f'\\nSlots List:\\n{slots_by_index}') kwargs = {} if objective",
"has moved from {item.old_slot.venue} at {item.old_slot.starts_at} to {item.new_slot.venue} at {item.new_slot.starts_at}') if solution is",
"import convert, io, logging, session logger = daiquiri.getLogger(__name__) def events_and_slots(resources): slots = defn.slots(resources)",
"{item.old_slot.venue} at {item.old_slot.starts_at} to {item.new_slot.venue} at {item.new_slot.starts_at}') if solution is not None: allocations",
"'warning', 'info', 'debug']), help='Logging verbosity') def scheduler(verbosity): pass @scheduler.command() @click.option( '--verbosity', '-v', default='info',",
"defn.add_unsuitability_to_events(events, slots, unsuitability) return events, slots @click.version_option(message='%(prog)s %(version)s :: UK Python Association') @click.group()",
"if objective == 'consistency' or algorithm == 'simulated_annealing' or diff: original_solution = io.import_solution(session.folders['solution'])",
"= defn.events(resources) unavailability = defn.unavailability(resources, slots) clashes = defn.clashes(resources) unsuitability = defn.unsuitability(resources, slots)",
"help='Directory for input files') @click.option( '--solution_dir', '-s', default=None, help='Directory for solution files') @click.option(",
"help='Directory for solution files') @click.option( '--reload/--no-reload', default=False, help='Reload YAML definition') @timed def validate(verbosity,",
"define the Command Line Interface (cli)\"\"\" from pathlib import Path import click from",
"Path(input_dir) if solution_dir: session.folders['solution'] = Path(solution_dir) if build_dir: session.folders['build'] = Path(build_dir) resources =",
"not None: allocations = defn.allocations(resources) unbounded = defn.unbounded(resources) defn.add_allocations(events, slots, solution, allocations, unbounded)",
"io.import_solution(session.folders['solution']) definition = io.import_schedule_definition(session.folders['solution']) events = definition['events'] slots = definition['slots'] logger.info('Validating schedule...') if",
"defn.resources() events, slots = events_and_slots(resources) original_solution = io.import_solution(session.folders['solution']) solution = [ item for",
"original_schedule solution = calc.solution(events, slots, algorithm, objective, **kwargs) if diff: schedule = solution_to_schedule(solution,",
"= calc.solution(events, slots, algorithm, objective, **kwargs) if diff: schedule = solution_to_schedule(solution, events, slots)",
"'warning', 'info', 'debug']), help='Logging verbosity') @click.option( '--input_dir', '-i', default=None, help='Directory for input files')",
"events, slots): logger.info('Imported solution is valid') else: for v in solution_violations( solution, definition['events'],",
"validate(verbosity, input_dir, solution_dir, reload): logging.setup(verbosity) if solution_dir: session.folders['solution'] = Path(solution_dir) solution = io.import_solution(session.folders['solution'])",
"session.folders['build'] = Path(build_dir) resources = defn.resources() events, slots = events_and_slots(resources) slots_by_index = {",
"'--solution_dir', '-s', default=None, help='Directory for solution files') @click.option( '--reload/--no-reload', default=False, help='Reload YAML definition')",
"len(events)] original_schedule = solution_to_schedule( revised_solution, events, slots) diff = True kwargs['original_schedule'] = original_schedule",
"scheduler.calculate as calc from scheduler.decorators import timed import scheduler.define as defn from scheduler",
"moved from {item.old_slot.venue} at {item.old_slot.starts_at} to {item.new_slot.venue} at {item.new_slot.starts_at}') if solution is not",
"item in original_solution if item[0] < len(events)] else: solution = io.import_solution(session.folders['solution']) definition =",
"= definition['slots'] logger.info('Validating schedule...') if is_valid_solution(solution, events, slots): logger.info('Imported solution is valid') else:",
"@click.option( '--input_dir', '-i', default=None, help='Directory for input files') @click.option( '--solution_dir', '-s', default=None, help='Directory",
"verbosity') def scheduler(verbosity): pass @scheduler.command() @click.option( '--verbosity', '-v', default='info', type=click.Choice(['critical', 'error', 'warning', 'info',",
"in enumerate(slots)} logger.debug(f'\\nSlots List:\\n{slots_by_index}') kwargs = {} if objective == 'consistency' or algorithm",
"'debug']), help='Logging verbosity') @click.option( '--input_dir', '-i', default=None, help='Directory for input files') @click.option( '--solution_dir',",
"'-v', default='info', type=click.Choice(['critical', 'error', 'warning', 'info', 'debug']), help='Logging verbosity') def scheduler(verbosity): pass @scheduler.command()",
"scheduler.decorators import timed import scheduler.define as defn from scheduler import convert, io, logging,",
"defn from scheduler import convert, io, logging, session logger = daiquiri.getLogger(__name__) def events_and_slots(resources):",
"at {item.new_slot.starts_at}') if solution is not None: allocations = defn.allocations(resources) unbounded = defn.unbounded(resources)",
"Line Interface (cli)\"\"\" from pathlib import Path import click from conference_scheduler.scheduler import event_schedule_difference",
"= original_schedule solution = calc.solution(events, slots, algorithm, objective, **kwargs) if diff: schedule =",
"in event_diff: logger.debug(f'{item.event.name} has moved from {item.old_slot.venue} at {item.old_slot.starts_at} to {item.new_slot.venue} at {item.new_slot.starts_at}')",
"events_and_slots(resources): slots = defn.slots(resources) events = defn.events(resources) unavailability = defn.unavailability(resources, slots) clashes =",
"@timed def validate(verbosity, input_dir, solution_dir, reload): logging.setup(verbosity) if solution_dir: session.folders['solution'] = Path(solution_dir) solution",
"logger.debug(f'\\nSlots List:\\n{slots_by_index}') kwargs = {} if objective == 'consistency' or algorithm == 'simulated_annealing'",
"'-o', default=None, type=click.Choice(['efficiency', 'equity', 'consistency']), help='Objective Function') @click.option('--diff/--no-diff', default=False, help='Show schedule diff') @click.option(",
"'--reload/--no-reload', default=False, help='Reload YAML definition') @timed def validate(verbosity, input_dir, solution_dir, reload): logging.setup(verbosity) if",
"session.folders['input'] = Path(input_dir) if solution_dir: session.folders['solution'] = Path(solution_dir) if build_dir: session.folders['build'] = Path(build_dir)",
"from conference_scheduler.validator import ( is_valid_solution, solution_violations) import daiquiri import scheduler.calculate as calc from",
"= events_and_slots(resources) slots_by_index = { idx: f'{slot.starts_at} {slot.venue}' for idx, slot in enumerate(slots)}",
"slot in enumerate(slots)} logger.debug(f'\\nSlots List:\\n{slots_by_index}') kwargs = {} if objective == 'consistency' or",
"click from conference_scheduler.scheduler import event_schedule_difference from conference_scheduler.converter import solution_to_schedule from conference_scheduler.validator import (",
"Interface (cli)\"\"\" from pathlib import Path import click from conference_scheduler.scheduler import event_schedule_difference from",
"logger.debug(convert.schedule_to_text(solution, events, slots)) io.export_solution_and_definition( resources, events, slots, allocations, solution, session.folders['solution']) @scheduler.command() @click.option( '--verbosity',",
"defn.resources() events, slots = events_and_slots(resources) slots_by_index = { idx: f'{slot.starts_at} {slot.venue}' for idx,",
"algorithm, objective, diff, input_dir, solution_dir, build_dir ): logging.setup(verbosity) if input_dir: session.folders['input'] = Path(input_dir)",
"solution_violations) import daiquiri import scheduler.calculate as calc from scheduler.decorators import timed import scheduler.define",
"True kwargs['original_schedule'] = original_schedule solution = calc.solution(events, slots, algorithm, objective, **kwargs) if diff:",
"logger.info('Validating schedule...') if is_valid_solution(solution, events, slots): logger.info('Imported solution is valid') else: for v",
"scheduler(verbosity): pass @scheduler.command() @click.option( '--verbosity', '-v', default='info', type=click.Choice(['critical', 'error', 'warning', 'info', 'debug']), help='Logging",
"schedule diff') @click.option( '--input_dir', '-i', default=None, help='Directory for input files') @click.option( '--solution_dir', '-s',",
"[ item for item in original_solution if item[0] < len(events)] else: solution =",
"help='Logging verbosity') @click.option( '--input_dir', '-i', default=None, help='Directory for input files') @click.option( '--solution_dir', '-s',",
"daiquiri.getLogger(__name__) def events_and_slots(resources): slots = defn.slots(resources) events = defn.events(resources) unavailability = defn.unavailability(resources, slots)",
"reload: resources = defn.resources() events, slots = events_and_slots(resources) original_solution = io.import_solution(session.folders['solution']) solution =",
"defn.clashes(resources) unsuitability = defn.unsuitability(resources, slots) defn.add_unavailability_to_events(events, slots, unavailability) defn.add_clashes_to_events(events, clashes) defn.add_unsuitability_to_events(events, slots, unsuitability)",
"resources = defn.resources() events, slots = events_and_slots(resources) slots_by_index = { idx: f'{slot.starts_at} {slot.venue}'",
"f'{slot.starts_at} {slot.venue}' for idx, slot in enumerate(slots)} logger.debug(f'\\nSlots List:\\n{slots_by_index}') kwargs = {} if",
"@click.option( '--algorithm', '-a', default='pulp_cbc_cmd', type=click.Choice( ['pulp_cbc_cmd', 'glpk', 'hill_climber', 'simulated_annealing']), help='Solver algorithm') @click.option( '--objective',",
"unavailability) defn.add_clashes_to_events(events, clashes) defn.add_unsuitability_to_events(events, slots, unsuitability) return events, slots @click.version_option(message='%(prog)s %(version)s :: UK",
"import daiquiri import scheduler.calculate as calc from scheduler.decorators import timed import scheduler.define as",
"objective, **kwargs) if diff: schedule = solution_to_schedule(solution, events, slots) event_diff = event_schedule_difference(original_schedule, schedule)",
"type=click.Choice(['critical', 'error', 'warning', 'info', 'debug']), help='Logging verbosity') def scheduler(verbosity): pass @scheduler.command() @click.option( '--verbosity',",
"algorithm == 'simulated_annealing' or diff: original_solution = io.import_solution(session.folders['solution']) revised_solution = [ item for",
"List:\\n{slots_by_index}') kwargs = {} if objective == 'consistency' or algorithm == 'simulated_annealing' or",
"item for item in original_solution if item[0] < len(events)] original_schedule = solution_to_schedule( revised_solution,",
"enumerate(slots)} logger.debug(f'\\nSlots List:\\n{slots_by_index}') kwargs = {} if objective == 'consistency' or algorithm ==",
"idx: f'{slot.starts_at} {slot.venue}' for idx, slot in enumerate(slots)} logger.debug(f'\\nSlots List:\\n{slots_by_index}') kwargs = {}",
"item[0] < len(events)] original_schedule = solution_to_schedule( revised_solution, events, slots) diff = True kwargs['original_schedule']",
"slots = defn.slots(resources) events = defn.events(resources) unavailability = defn.unavailability(resources, slots) clashes = defn.clashes(resources)",
"is_valid_solution(solution, events, slots): logger.info('Imported solution is valid') else: for v in solution_violations( solution,",
"default=False, help='Reload YAML definition') @timed def validate(verbosity, input_dir, solution_dir, reload): logging.setup(verbosity) if solution_dir:",
"defn.add_unavailability_to_events(events, slots, unavailability) defn.add_clashes_to_events(events, clashes) defn.add_unsuitability_to_events(events, slots, unsuitability) return events, slots @click.version_option(message='%(prog)s %(version)s",
"unbounded) logger.debug(convert.schedule_to_text(solution, events, slots)) io.export_solution_and_definition( resources, events, slots, allocations, solution, session.folders['solution']) @scheduler.command() @click.option(",
"in original_solution if item[0] < len(events)] original_schedule = solution_to_schedule( revised_solution, events, slots) diff",
"@click.option( '--solution_dir', '-s', default=None, help='Directory for solution files') @click.option( '--reload/--no-reload', default=False, help='Reload YAML",
"files') @click.option( '--reload/--no-reload', default=False, help='Reload YAML definition') @timed def validate(verbosity, input_dir, solution_dir, reload):",
"@timed def build( verbosity, algorithm, objective, diff, input_dir, solution_dir, build_dir ): logging.setup(verbosity) if",
"solution = [ item for item in original_solution if item[0] < len(events)] else:",
"'-s', default=None, help='Directory for solution files') @click.option( '--reload/--no-reload', default=False, help='Reload YAML definition') @timed",
"default='info', type=click.Choice(['critical', 'error', 'warning', 'info', 'debug']), help='Logging verbosity') @click.option( '--input_dir', '-i', default=None, help='Directory",
"clashes = defn.clashes(resources) unsuitability = defn.unsuitability(resources, slots) defn.add_unavailability_to_events(events, slots, unavailability) defn.add_clashes_to_events(events, clashes) defn.add_unsuitability_to_events(events,",
"len(events)] else: solution = io.import_solution(session.folders['solution']) definition = io.import_schedule_definition(session.folders['solution']) events = definition['events'] slots =",
"help='Reload YAML definition') @timed def validate(verbosity, input_dir, solution_dir, reload): logging.setup(verbosity) if solution_dir: session.folders['solution']",
"definition['events'] slots = definition['slots'] logger.info('Validating schedule...') if is_valid_solution(solution, events, slots): logger.info('Imported solution is",
"= { idx: f'{slot.starts_at} {slot.venue}' for idx, slot in enumerate(slots)} logger.debug(f'\\nSlots List:\\n{slots_by_index}') kwargs",
"YAML definition') @timed def validate(verbosity, input_dir, solution_dir, reload): logging.setup(verbosity) if solution_dir: session.folders['solution'] =",
"def events_and_slots(resources): slots = defn.slots(resources) events = defn.events(resources) unavailability = defn.unavailability(resources, slots) clashes",
"for input files') @click.option( '--solution_dir', '-s', default=None, help='Directory for solution files') @click.option( '--reload/--no-reload',",
"Command Line Interface (cli)\"\"\" from pathlib import Path import click from conference_scheduler.scheduler import",
"(cli)\"\"\" from pathlib import Path import click from conference_scheduler.scheduler import event_schedule_difference from conference_scheduler.converter",
"diff, input_dir, solution_dir, build_dir ): logging.setup(verbosity) if input_dir: session.folders['input'] = Path(input_dir) if solution_dir:",
"if solution_dir: session.folders['solution'] = Path(solution_dir) solution = io.import_solution(session.folders['solution']) if reload: resources = defn.resources()",
"'--verbosity', '-v', default='info', type=click.Choice(['critical', 'error', 'warning', 'info', 'debug']), help='Logging verbosity') def scheduler(verbosity): pass",
"): logging.setup(verbosity) if input_dir: session.folders['input'] = Path(input_dir) if solution_dir: session.folders['solution'] = Path(solution_dir) if",
"slots_by_index = { idx: f'{slot.starts_at} {slot.venue}' for idx, slot in enumerate(slots)} logger.debug(f'\\nSlots List:\\n{slots_by_index}')",
"import solution_to_schedule from conference_scheduler.validator import ( is_valid_solution, solution_violations) import daiquiri import scheduler.calculate as",
"= defn.resources() events, slots = events_and_slots(resources) original_solution = io.import_solution(session.folders['solution']) solution = [ item",
"@click.group() @click.option( '--verbosity', '-v', default='info', type=click.Choice(['critical', 'error', 'warning', 'info', 'debug']), help='Logging verbosity') def",
"from conference_scheduler.converter import solution_to_schedule from conference_scheduler.validator import ( is_valid_solution, solution_violations) import daiquiri import",
"'--input_dir', '-i', default=None, help='Directory for input files') @click.option( '--solution_dir', '-s', default=None, help='Directory for",
"resources, events, slots, allocations, solution, session.folders['solution']) @scheduler.command() @click.option( '--verbosity', '-v', default='info', type=click.Choice(['critical', 'error',",
"Path import click from conference_scheduler.scheduler import event_schedule_difference from conference_scheduler.converter import solution_to_schedule from conference_scheduler.validator",
"unsuitability = defn.unsuitability(resources, slots) defn.add_unavailability_to_events(events, slots, unavailability) defn.add_clashes_to_events(events, clashes) defn.add_unsuitability_to_events(events, slots, unsuitability) return",
"if is_valid_solution(solution, events, slots): logger.info('Imported solution is valid') else: for v in solution_violations(",
"Path(build_dir) resources = defn.resources() events, slots = events_and_slots(resources) slots_by_index = { idx: f'{slot.starts_at}",
"defn.add_clashes_to_events(events, clashes) defn.add_unsuitability_to_events(events, slots, unsuitability) return events, slots @click.version_option(message='%(prog)s %(version)s :: UK Python",
"'-a', default='pulp_cbc_cmd', type=click.Choice( ['pulp_cbc_cmd', 'glpk', 'hill_climber', 'simulated_annealing']), help='Solver algorithm') @click.option( '--objective', '-o', default=None,",
"events, slots = events_and_slots(resources) original_solution = io.import_solution(session.folders['solution']) solution = [ item for item",
"if build_dir: session.folders['build'] = Path(build_dir) resources = defn.resources() events, slots = events_and_slots(resources) slots_by_index",
"daiquiri import scheduler.calculate as calc from scheduler.decorators import timed import scheduler.define as defn",
"slots = definition['slots'] logger.info('Validating schedule...') if is_valid_solution(solution, events, slots): logger.info('Imported solution is valid')",
"\"\"\"Procedures to define the Command Line Interface (cli)\"\"\" from pathlib import Path import",
"= defn.unbounded(resources) defn.add_allocations(events, slots, solution, allocations, unbounded) logger.debug(convert.schedule_to_text(solution, events, slots)) io.export_solution_and_definition( resources, events,",
"verbosity, algorithm, objective, diff, input_dir, solution_dir, build_dir ): logging.setup(verbosity) if input_dir: session.folders['input'] =",
"diff = True kwargs['original_schedule'] = original_schedule solution = calc.solution(events, slots, algorithm, objective, **kwargs)",
"Path(solution_dir) solution = io.import_solution(session.folders['solution']) if reload: resources = defn.resources() events, slots = events_and_slots(resources)",
"to {item.new_slot.venue} at {item.new_slot.starts_at}') if solution is not None: allocations = defn.allocations(resources) unbounded",
"defn.unbounded(resources) defn.add_allocations(events, slots, solution, allocations, unbounded) logger.debug(convert.schedule_to_text(solution, events, slots)) io.export_solution_and_definition( resources, events, slots,",
"input files') @click.option( '--solution_dir', '-s', default=None, help='Directory for solution files') @click.option( '--reload/--no-reload', default=False,",
"io.import_schedule_definition(session.folders['solution']) events = definition['events'] slots = definition['slots'] logger.info('Validating schedule...') if is_valid_solution(solution, events, slots):",
"solution is not None: allocations = defn.allocations(resources) unbounded = defn.unbounded(resources) defn.add_allocations(events, slots, solution,",
"output yaml files') @timed def build( verbosity, algorithm, objective, diff, input_dir, solution_dir, build_dir",
"type=click.Choice(['efficiency', 'equity', 'consistency']), help='Objective Function') @click.option('--diff/--no-diff', default=False, help='Show schedule diff') @click.option( '--input_dir', '-i',",
"input files') @click.option( '--solution_dir', '-s', default=None, help='Directory for solution files') @click.option( '--build_dir', '-b',",
"reload): logging.setup(verbosity) if solution_dir: session.folders['solution'] = Path(solution_dir) solution = io.import_solution(session.folders['solution']) if reload: resources",
"build_dir ): logging.setup(verbosity) if input_dir: session.folders['input'] = Path(input_dir) if solution_dir: session.folders['solution'] = Path(solution_dir)",
"solution files') @click.option( '--reload/--no-reload', default=False, help='Reload YAML definition') @timed def validate(verbosity, input_dir, solution_dir,",
"conference_scheduler.validator import ( is_valid_solution, solution_violations) import daiquiri import scheduler.calculate as calc from scheduler.decorators",
"slots) event_diff = event_schedule_difference(original_schedule, schedule) logger.debug(f'\\nevent_diff:') for item in event_diff: logger.debug(f'{item.event.name} has moved",
"defn.unsuitability(resources, slots) defn.add_unavailability_to_events(events, slots, unavailability) defn.add_clashes_to_events(events, clashes) defn.add_unsuitability_to_events(events, slots, unsuitability) return events, slots",
"idx, slot in enumerate(slots)} logger.debug(f'\\nSlots List:\\n{slots_by_index}') kwargs = {} if objective == 'consistency'",
"@click.version_option(message='%(prog)s %(version)s :: UK Python Association') @click.group() @click.option( '--verbosity', '-v', default='info', type=click.Choice(['critical', 'error',",
"slots = events_and_slots(resources) original_solution = io.import_solution(session.folders['solution']) solution = [ item for item in",
"events, slots) diff = True kwargs['original_schedule'] = original_schedule solution = calc.solution(events, slots, algorithm,",
"io.export_solution_and_definition( resources, events, slots, allocations, solution, session.folders['solution']) @scheduler.command() @click.option( '--verbosity', '-v', default='info', type=click.Choice(['critical',",
"from scheduler import convert, io, logging, session logger = daiquiri.getLogger(__name__) def events_and_slots(resources): slots",
"{item.old_slot.starts_at} to {item.new_slot.venue} at {item.new_slot.starts_at}') if solution is not None: allocations = defn.allocations(resources)",
"for solution files') @click.option( '--build_dir', '-b', default=None, help='Directory for output yaml files') @timed",
"allocations = defn.allocations(resources) unbounded = defn.unbounded(resources) defn.add_allocations(events, slots, solution, allocations, unbounded) logger.debug(convert.schedule_to_text(solution, events,",
"session.folders['solution']) @scheduler.command() @click.option( '--verbosity', '-v', default='info', type=click.Choice(['critical', 'error', 'warning', 'info', 'debug']), help='Logging verbosity')",
"slots @click.version_option(message='%(prog)s %(version)s :: UK Python Association') @click.group() @click.option( '--verbosity', '-v', default='info', type=click.Choice(['critical',",
"timed import scheduler.define as defn from scheduler import convert, io, logging, session logger",
"help='Directory for output yaml files') @timed def build( verbosity, algorithm, objective, diff, input_dir,",
"io.import_solution(session.folders['solution']) solution = [ item for item in original_solution if item[0] < len(events)]",
"if solution is not None: allocations = defn.allocations(resources) unbounded = defn.unbounded(resources) defn.add_allocations(events, slots,",
"else: solution = io.import_solution(session.folders['solution']) definition = io.import_schedule_definition(session.folders['solution']) events = definition['events'] slots = definition['slots']",
"yaml files') @timed def build( verbosity, algorithm, objective, diff, input_dir, solution_dir, build_dir ):",
"slots, unsuitability) return events, slots @click.version_option(message='%(prog)s %(version)s :: UK Python Association') @click.group() @click.option(",
"default=None, help='Directory for solution files') @click.option( '--build_dir', '-b', default=None, help='Directory for output yaml",
"@click.option('--diff/--no-diff', default=False, help='Show schedule diff') @click.option( '--input_dir', '-i', default=None, help='Directory for input files')",
"algorithm, objective, **kwargs) if diff: schedule = solution_to_schedule(solution, events, slots) event_diff = event_schedule_difference(original_schedule,",
"def validate(verbosity, input_dir, solution_dir, reload): logging.setup(verbosity) if solution_dir: session.folders['solution'] = Path(solution_dir) solution =",
"= True kwargs['original_schedule'] = original_schedule solution = calc.solution(events, slots, algorithm, objective, **kwargs) if",
"'--verbosity', '-v', default='info', type=click.Choice(['critical', 'error', 'warning', 'info', 'debug']), help='Logging verbosity') @click.option( '--algorithm', '-a',",
"'error', 'warning', 'info', 'debug']), help='Logging verbosity') @click.option( '--input_dir', '-i', default=None, help='Directory for input",
"from scheduler.decorators import timed import scheduler.define as defn from scheduler import convert, io,",
"type=click.Choice(['critical', 'error', 'warning', 'info', 'debug']), help='Logging verbosity') @click.option( '--algorithm', '-a', default='pulp_cbc_cmd', type=click.Choice( ['pulp_cbc_cmd',",
"verbosity') @click.option( '--algorithm', '-a', default='pulp_cbc_cmd', type=click.Choice( ['pulp_cbc_cmd', 'glpk', 'hill_climber', 'simulated_annealing']), help='Solver algorithm') @click.option(",
"definition') @timed def validate(verbosity, input_dir, solution_dir, reload): logging.setup(verbosity) if solution_dir: session.folders['solution'] = Path(solution_dir)",
"[ item for item in original_solution if item[0] < len(events)] original_schedule = solution_to_schedule(",
"< len(events)] else: solution = io.import_solution(session.folders['solution']) definition = io.import_schedule_definition(session.folders['solution']) events = definition['events'] slots",
"if input_dir: session.folders['input'] = Path(input_dir) if solution_dir: session.folders['solution'] = Path(solution_dir) if build_dir: session.folders['build']",
"solution = io.import_solution(session.folders['solution']) if reload: resources = defn.resources() events, slots = events_and_slots(resources) original_solution",
"session.folders['solution'] = Path(solution_dir) solution = io.import_solution(session.folders['solution']) if reload: resources = defn.resources() events, slots",
"unbounded = defn.unbounded(resources) defn.add_allocations(events, slots, solution, allocations, unbounded) logger.debug(convert.schedule_to_text(solution, events, slots)) io.export_solution_and_definition( resources,",
"allocations, unbounded) logger.debug(convert.schedule_to_text(solution, events, slots)) io.export_solution_and_definition( resources, events, slots, allocations, solution, session.folders['solution']) @scheduler.command()",
"@click.option( '--verbosity', '-v', default='info', type=click.Choice(['critical', 'error', 'warning', 'info', 'debug']), help='Logging verbosity') def scheduler(verbosity):",
"logger.debug(f'{item.event.name} has moved from {item.old_slot.venue} at {item.old_slot.starts_at} to {item.new_slot.venue} at {item.new_slot.starts_at}') if solution",
"files') @click.option( '--solution_dir', '-s', default=None, help='Directory for solution files') @click.option( '--reload/--no-reload', default=False, help='Reload",
"@click.option( '--build_dir', '-b', default=None, help='Directory for output yaml files') @timed def build( verbosity,",
"build_dir: session.folders['build'] = Path(build_dir) resources = defn.resources() events, slots = events_and_slots(resources) slots_by_index =",
"= Path(solution_dir) solution = io.import_solution(session.folders['solution']) if reload: resources = defn.resources() events, slots =",
"= events_and_slots(resources) original_solution = io.import_solution(session.folders['solution']) solution = [ item for item in original_solution",
"defn.events(resources) unavailability = defn.unavailability(resources, slots) clashes = defn.clashes(resources) unsuitability = defn.unsuitability(resources, slots) defn.add_unavailability_to_events(events,",
"for solution files') @click.option( '--reload/--no-reload', default=False, help='Reload YAML definition') @timed def validate(verbosity, input_dir,",
"= solution_to_schedule(solution, events, slots) event_diff = event_schedule_difference(original_schedule, schedule) logger.debug(f'\\nevent_diff:') for item in event_diff:",
"= {} if objective == 'consistency' or algorithm == 'simulated_annealing' or diff: original_solution",
"files') @timed def build( verbosity, algorithm, objective, diff, input_dir, solution_dir, build_dir ): logging.setup(verbosity)",
"'-s', default=None, help='Directory for solution files') @click.option( '--build_dir', '-b', default=None, help='Directory for output",
"kwargs = {} if objective == 'consistency' or algorithm == 'simulated_annealing' or diff:",
"@click.option( '--solution_dir', '-s', default=None, help='Directory for solution files') @click.option( '--build_dir', '-b', default=None, help='Directory",
"io, logging, session logger = daiquiri.getLogger(__name__) def events_and_slots(resources): slots = defn.slots(resources) events =",
"files') @click.option( '--build_dir', '-b', default=None, help='Directory for output yaml files') @timed def build(",
"slots) diff = True kwargs['original_schedule'] = original_schedule solution = calc.solution(events, slots, algorithm, objective,",
"['pulp_cbc_cmd', 'glpk', 'hill_climber', 'simulated_annealing']), help='Solver algorithm') @click.option( '--objective', '-o', default=None, type=click.Choice(['efficiency', 'equity', 'consistency']),",
"'warning', 'info', 'debug']), help='Logging verbosity') @click.option( '--algorithm', '-a', default='pulp_cbc_cmd', type=click.Choice( ['pulp_cbc_cmd', 'glpk', 'hill_climber',",
"default='info', type=click.Choice(['critical', 'error', 'warning', 'info', 'debug']), help='Logging verbosity') @click.option( '--algorithm', '-a', default='pulp_cbc_cmd', type=click.Choice(",
"'-i', default=None, help='Directory for input files') @click.option( '--solution_dir', '-s', default=None, help='Directory for solution",
"import Path import click from conference_scheduler.scheduler import event_schedule_difference from conference_scheduler.converter import solution_to_schedule from"
] |
[
"db_connection.get_database() containers = container_service.get_all() for container in containers: stats = container_service.get_stats(container, True, False)",
"save_containers_stats(): db_connection = DBConnection() db = db_connection.get_database() containers = container_service.get_all() for container in",
"import datetime from src.database.connection import DBConnection from src.helpers.docker_helper import extract_stats_container_data from src.services import",
"stats = container_service.get_stats(container, True, False) stats_data = extract_stats_container_data(container, stats) db['container_stats'].insert_one(stats_data) print(datetime.utcnow()) time_to_wait =",
"import DBConnection from src.helpers.docker_helper import extract_stats_container_data from src.services import container_service import schedule import",
"datetime import datetime from src.database.connection import DBConnection from src.helpers.docker_helper import extract_stats_container_data from src.services",
"def save_containers_stats(): db_connection = DBConnection() db = db_connection.get_database() containers = container_service.get_all() for container",
"from src.helpers.docker_helper import extract_stats_container_data from src.services import container_service import schedule import time def",
"= DBConnection() db = db_connection.get_database() containers = container_service.get_all() for container in containers: stats",
"container in containers: stats = container_service.get_stats(container, True, False) stats_data = extract_stats_container_data(container, stats) db['container_stats'].insert_one(stats_data)",
"time def save_containers_stats(): db_connection = DBConnection() db = db_connection.get_database() containers = container_service.get_all() for",
"import schedule import time def save_containers_stats(): db_connection = DBConnection() db = db_connection.get_database() containers",
"containers: stats = container_service.get_stats(container, True, False) stats_data = extract_stats_container_data(container, stats) db['container_stats'].insert_one(stats_data) print(datetime.utcnow()) time_to_wait",
"from datetime import datetime from src.database.connection import DBConnection from src.helpers.docker_helper import extract_stats_container_data from",
"src.database.connection import DBConnection from src.helpers.docker_helper import extract_stats_container_data from src.services import container_service import schedule",
"for container in containers: stats = container_service.get_stats(container, True, False) stats_data = extract_stats_container_data(container, stats)",
"True, False) stats_data = extract_stats_container_data(container, stats) db['container_stats'].insert_one(stats_data) print(datetime.utcnow()) time_to_wait = 10 schedule.every(time_to_wait).seconds.do(save_containers_stats) while",
"stats_data = extract_stats_container_data(container, stats) db['container_stats'].insert_one(stats_data) print(datetime.utcnow()) time_to_wait = 10 schedule.every(time_to_wait).seconds.do(save_containers_stats) while True: schedule.run_pending()",
"<reponame>NathanReis/BaleiaAzul from datetime import datetime from src.database.connection import DBConnection from src.helpers.docker_helper import extract_stats_container_data",
"container_service import schedule import time def save_containers_stats(): db_connection = DBConnection() db = db_connection.get_database()",
"= container_service.get_stats(container, True, False) stats_data = extract_stats_container_data(container, stats) db['container_stats'].insert_one(stats_data) print(datetime.utcnow()) time_to_wait = 10",
"import time def save_containers_stats(): db_connection = DBConnection() db = db_connection.get_database() containers = container_service.get_all()",
"DBConnection() db = db_connection.get_database() containers = container_service.get_all() for container in containers: stats =",
"= container_service.get_all() for container in containers: stats = container_service.get_stats(container, True, False) stats_data =",
"container_service.get_all() for container in containers: stats = container_service.get_stats(container, True, False) stats_data = extract_stats_container_data(container,",
"schedule import time def save_containers_stats(): db_connection = DBConnection() db = db_connection.get_database() containers =",
"src.services import container_service import schedule import time def save_containers_stats(): db_connection = DBConnection() db",
"DBConnection from src.helpers.docker_helper import extract_stats_container_data from src.services import container_service import schedule import time",
"False) stats_data = extract_stats_container_data(container, stats) db['container_stats'].insert_one(stats_data) print(datetime.utcnow()) time_to_wait = 10 schedule.every(time_to_wait).seconds.do(save_containers_stats) while True:",
"db = db_connection.get_database() containers = container_service.get_all() for container in containers: stats = container_service.get_stats(container,",
"container_service.get_stats(container, True, False) stats_data = extract_stats_container_data(container, stats) db['container_stats'].insert_one(stats_data) print(datetime.utcnow()) time_to_wait = 10 schedule.every(time_to_wait).seconds.do(save_containers_stats)",
"db_connection = DBConnection() db = db_connection.get_database() containers = container_service.get_all() for container in containers:",
"import extract_stats_container_data from src.services import container_service import schedule import time def save_containers_stats(): db_connection",
"containers = container_service.get_all() for container in containers: stats = container_service.get_stats(container, True, False) stats_data",
"in containers: stats = container_service.get_stats(container, True, False) stats_data = extract_stats_container_data(container, stats) db['container_stats'].insert_one(stats_data) print(datetime.utcnow())",
"= db_connection.get_database() containers = container_service.get_all() for container in containers: stats = container_service.get_stats(container, True,",
"src.helpers.docker_helper import extract_stats_container_data from src.services import container_service import schedule import time def save_containers_stats():",
"from src.services import container_service import schedule import time def save_containers_stats(): db_connection = DBConnection()",
"= extract_stats_container_data(container, stats) db['container_stats'].insert_one(stats_data) print(datetime.utcnow()) time_to_wait = 10 schedule.every(time_to_wait).seconds.do(save_containers_stats) while True: schedule.run_pending() time.sleep(time_to_wait)",
"from src.database.connection import DBConnection from src.helpers.docker_helper import extract_stats_container_data from src.services import container_service import",
"import container_service import schedule import time def save_containers_stats(): db_connection = DBConnection() db =",
"extract_stats_container_data from src.services import container_service import schedule import time def save_containers_stats(): db_connection =",
"datetime from src.database.connection import DBConnection from src.helpers.docker_helper import extract_stats_container_data from src.services import container_service"
] |
[
"None: s = payload.decode('utf8') j = json.loads(s) if 'quotes' in j: quotes =",
"under the License. ''' from Observer import Observer import json class JSONStreamObserver(Observer): def",
"the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in",
"pattern. This observer prints the JSON object returned from the stream. @see: http://www.questrade.com/api/documentation/streaming",
"design pattern. This observer prints the JSON object returned from the stream. @see:",
"from the stream. @see: http://www.questrade.com/api/documentation/streaming @copyright: 2016 @author: <NAME> @license: Licensed under the",
"CONDITIONS OF ANY KIND, either express or implied. See the License for the",
"OR CONDITIONS OF ANY KIND, either express or implied. See the License for",
"OF ANY KIND, either express or implied. See the License for the specific",
"http://www.questrade.com/api/documentation/streaming @copyright: 2016 @author: <NAME> @license: Licensed under the Apache License, Version 2.0",
"to in writing, software distributed under the License is distributed on an \"AS",
"payload is not None: s = payload.decode('utf8') j = json.loads(s) if 'quotes' in",
"returned from the stream. @see: http://www.questrade.com/api/documentation/streaming @copyright: 2016 @author: <NAME> @license: Licensed under",
"distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,",
"not use this file except in compliance with the License. You may obtain",
"quotes: symbol = q.get('symbol', '_na_') if symbol != '_na_': self.dict_symbs[symbol] = q def",
"License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required",
"'_na_': self.dict_symbs[symbol] = q def get_symbols(self): return self.dict_symbs.keys() def get_latest_quote(self, symbol): return self.dict_symbs[symbol]",
"stream. @see: http://www.questrade.com/api/documentation/streaming @copyright: 2016 @author: <NAME> @license: Licensed under the Apache License,",
"= j.get('quotes') for q in quotes: symbol = q.get('symbol', '_na_') if symbol !=",
"Observer @summary: An Observer in the Publish/Subscriber design pattern. This observer prints the",
"except in compliance with the License. You may obtain a copy of the",
"@license: Licensed under the Apache License, Version 2.0 (the \"License\"); you may not",
"may not use this file except in compliance with the License. You may",
"WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the",
"symbol = q.get('symbol', '_na_') if symbol != '_na_': self.dict_symbs[symbol] = q def get_symbols(self):",
"under the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR",
"JSONStreamObserver(Observer): def __init__(self): self.dict_symbs = {} def update(self, payload, isBinary): if not isBinary",
"isBinary): if not isBinary and payload is not None: s = payload.decode('utf8') j",
"an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express",
"@copyright: 2016 @author: <NAME> @license: Licensed under the Apache License, Version 2.0 (the",
"on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either",
"!= '_na_': self.dict_symbs[symbol] = q def get_symbols(self): return self.dict_symbs.keys() def get_latest_quote(self, symbol): return",
"from Observer import Observer import json class JSONStreamObserver(Observer): def __init__(self): self.dict_symbs = {}",
"not None: s = payload.decode('utf8') j = json.loads(s) if 'quotes' in j: quotes",
"if symbol != '_na_': self.dict_symbs[symbol] = q def get_symbols(self): return self.dict_symbs.keys() def get_latest_quote(self,",
"obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law",
"import json class JSONStreamObserver(Observer): def __init__(self): self.dict_symbs = {} def update(self, payload, isBinary):",
"the License for the specific language governing permissions and limitations under the License.",
"json.loads(s) if 'quotes' in j: quotes = j.get('quotes') for q in quotes: symbol",
"Observer in the Publish/Subscriber design pattern. This observer prints the JSON object returned",
"@see: http://www.questrade.com/api/documentation/streaming @copyright: 2016 @author: <NAME> @license: Licensed under the Apache License, Version",
"ANY KIND, either express or implied. See the License for the specific language",
"Observer import json class JSONStreamObserver(Observer): def __init__(self): self.dict_symbs = {} def update(self, payload,",
"file except in compliance with the License. You may obtain a copy of",
"for q in quotes: symbol = q.get('symbol', '_na_') if symbol != '_na_': self.dict_symbs[symbol]",
"object returned from the stream. @see: http://www.questrade.com/api/documentation/streaming @copyright: 2016 @author: <NAME> @license: Licensed",
"q.get('symbol', '_na_') if symbol != '_na_': self.dict_symbs[symbol] = q def get_symbols(self): return self.dict_symbs.keys()",
"Unless required by applicable law or agreed to in writing, software distributed under",
"q in quotes: symbol = q.get('symbol', '_na_') if symbol != '_na_': self.dict_symbs[symbol] =",
"'''JSON Stream Observer @summary: An Observer in the Publish/Subscriber design pattern. This observer",
"j: quotes = j.get('quotes') for q in quotes: symbol = q.get('symbol', '_na_') if",
"License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing,",
"j = json.loads(s) if 'quotes' in j: quotes = j.get('quotes') for q in",
"'_na_') if symbol != '_na_': self.dict_symbs[symbol] = q def get_symbols(self): return self.dict_symbs.keys() def",
"2.0 (the \"License\"); you may not use this file except in compliance with",
"\"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or",
"payload, isBinary): if not isBinary and payload is not None: s = payload.decode('utf8')",
"An Observer in the Publish/Subscriber design pattern. This observer prints the JSON object",
"See the License for the specific language governing permissions and limitations under the",
"copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed",
"'quotes' in j: quotes = j.get('quotes') for q in quotes: symbol = q.get('symbol',",
"Publish/Subscriber design pattern. This observer prints the JSON object returned from the stream.",
"symbol != '_na_': self.dict_symbs[symbol] = q def get_symbols(self): return self.dict_symbs.keys() def get_latest_quote(self, symbol):",
"the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless",
"the Publish/Subscriber design pattern. This observer prints the JSON object returned from the",
"the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS",
"governing permissions and limitations under the License. ''' from Observer import Observer import",
"License, Version 2.0 (the \"License\"); you may not use this file except in",
"the specific language governing permissions and limitations under the License. ''' from Observer",
"compliance with the License. You may obtain a copy of the License at",
"if not isBinary and payload is not None: s = payload.decode('utf8') j =",
"(the \"License\"); you may not use this file except in compliance with the",
"@author: <NAME> @license: Licensed under the Apache License, Version 2.0 (the \"License\"); you",
"This observer prints the JSON object returned from the stream. @see: http://www.questrade.com/api/documentation/streaming @copyright:",
"this file except in compliance with the License. You may obtain a copy",
"__init__(self): self.dict_symbs = {} def update(self, payload, isBinary): if not isBinary and payload",
"Stream Observer @summary: An Observer in the Publish/Subscriber design pattern. This observer prints",
"j.get('quotes') for q in quotes: symbol = q.get('symbol', '_na_') if symbol != '_na_':",
"specific language governing permissions and limitations under the License. ''' from Observer import",
"prints the JSON object returned from the stream. @see: http://www.questrade.com/api/documentation/streaming @copyright: 2016 @author:",
"\"License\"); you may not use this file except in compliance with the License.",
"express or implied. See the License for the specific language governing permissions and",
"in quotes: symbol = q.get('symbol', '_na_') if symbol != '_na_': self.dict_symbs[symbol] = q",
"License for the specific language governing permissions and limitations under the License. '''",
"permissions and limitations under the License. ''' from Observer import Observer import json",
"is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY",
"self.dict_symbs = {} def update(self, payload, isBinary): if not isBinary and payload is",
"import Observer import json class JSONStreamObserver(Observer): def __init__(self): self.dict_symbs = {} def update(self,",
"and limitations under the License. ''' from Observer import Observer import json class",
"you may not use this file except in compliance with the License. You",
"limitations under the License. ''' from Observer import Observer import json class JSONStreamObserver(Observer):",
"not isBinary and payload is not None: s = payload.decode('utf8') j = json.loads(s)",
"agreed to in writing, software distributed under the License is distributed on an",
"2016 @author: <NAME> @license: Licensed under the Apache License, Version 2.0 (the \"License\");",
"if 'quotes' in j: quotes = j.get('quotes') for q in quotes: symbol =",
"distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES",
"is not None: s = payload.decode('utf8') j = json.loads(s) if 'quotes' in j:",
"You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by",
"def update(self, payload, isBinary): if not isBinary and payload is not None: s",
"may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable",
"software distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT",
"by applicable law or agreed to in writing, software distributed under the License",
"applicable law or agreed to in writing, software distributed under the License is",
"implied. See the License for the specific language governing permissions and limitations under",
"the stream. @see: http://www.questrade.com/api/documentation/streaming @copyright: 2016 @author: <NAME> @license: Licensed under the Apache",
"http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed",
"WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License",
"<NAME> @license: Licensed under the Apache License, Version 2.0 (the \"License\"); you may",
"observer prints the JSON object returned from the stream. @see: http://www.questrade.com/api/documentation/streaming @copyright: 2016",
"License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF",
"def __init__(self): self.dict_symbs = {} def update(self, payload, isBinary): if not isBinary and",
"@summary: An Observer in the Publish/Subscriber design pattern. This observer prints the JSON",
"law or agreed to in writing, software distributed under the License is distributed",
"IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.",
"the JSON object returned from the stream. @see: http://www.questrade.com/api/documentation/streaming @copyright: 2016 @author: <NAME>",
"BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See",
"Version 2.0 (the \"License\"); you may not use this file except in compliance",
"= json.loads(s) if 'quotes' in j: quotes = j.get('quotes') for q in quotes:",
"in compliance with the License. You may obtain a copy of the License",
"for the specific language governing permissions and limitations under the License. ''' from",
"the Apache License, Version 2.0 (the \"License\"); you may not use this file",
"= q.get('symbol', '_na_') if symbol != '_na_': self.dict_symbs[symbol] = q def get_symbols(self): return",
"use this file except in compliance with the License. You may obtain a",
"= payload.decode('utf8') j = json.loads(s) if 'quotes' in j: quotes = j.get('quotes') for",
"KIND, either express or implied. See the License for the specific language governing",
"of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to",
"isBinary and payload is not None: s = payload.decode('utf8') j = json.loads(s) if",
"in j: quotes = j.get('quotes') for q in quotes: symbol = q.get('symbol', '_na_')",
"Licensed under the Apache License, Version 2.0 (the \"License\"); you may not use",
"and payload is not None: s = payload.decode('utf8') j = json.loads(s) if 'quotes'",
"Observer import Observer import json class JSONStreamObserver(Observer): def __init__(self): self.dict_symbs = {} def",
"s = payload.decode('utf8') j = json.loads(s) if 'quotes' in j: quotes = j.get('quotes')",
"in writing, software distributed under the License is distributed on an \"AS IS\"",
"json class JSONStreamObserver(Observer): def __init__(self): self.dict_symbs = {} def update(self, payload, isBinary): if",
"under the Apache License, Version 2.0 (the \"License\"); you may not use this",
"update(self, payload, isBinary): if not isBinary and payload is not None: s =",
"writing, software distributed under the License is distributed on an \"AS IS\" BASIS,",
"a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or",
"either express or implied. See the License for the specific language governing permissions",
"the License. ''' from Observer import Observer import json class JSONStreamObserver(Observer): def __init__(self):",
"class JSONStreamObserver(Observer): def __init__(self): self.dict_symbs = {} def update(self, payload, isBinary): if not",
"or agreed to in writing, software distributed under the License is distributed on",
"License. ''' from Observer import Observer import json class JSONStreamObserver(Observer): def __init__(self): self.dict_symbs",
"<filename>src/questrade/api/streamer/JSONStreamObserver.py '''JSON Stream Observer @summary: An Observer in the Publish/Subscriber design pattern. This",
"in the Publish/Subscriber design pattern. This observer prints the JSON object returned from",
"Apache License, Version 2.0 (the \"License\"); you may not use this file except",
"or implied. See the License for the specific language governing permissions and limitations",
"= {} def update(self, payload, isBinary): if not isBinary and payload is not",
"with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0",
"required by applicable law or agreed to in writing, software distributed under the",
"language governing permissions and limitations under the License. ''' from Observer import Observer",
"at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software",
"{} def update(self, payload, isBinary): if not isBinary and payload is not None:",
"quotes = j.get('quotes') for q in quotes: symbol = q.get('symbol', '_na_') if symbol",
"''' from Observer import Observer import json class JSONStreamObserver(Observer): def __init__(self): self.dict_symbs =",
"payload.decode('utf8') j = json.loads(s) if 'quotes' in j: quotes = j.get('quotes') for q",
"JSON object returned from the stream. @see: http://www.questrade.com/api/documentation/streaming @copyright: 2016 @author: <NAME> @license:"
] |
[
"API endpoint that allows CRUD operations on Topic objects \"\"\" queryset = Topic.objects.all().order_by('-created_at')",
"operations on Document objects \"\"\" queryset = Document.objects.all().order_by('-created_at') serializer_class = DocumentSerializer permission_classes =",
"objects \"\"\" queryset = Topic.objects.all().order_by('-created_at') serializer_class = TopicSerializer permission_classes = [permissions.IsAuthenticatedOrReadOnly] filterset_class =",
"from documents.models import Document, Folder, Topic from documents.serializers import DocumentSerializer, FolderSerializer, TopicSerializer from",
"Folder.objects.all().order_by('-created_at') serializer_class = FolderSerializer permission_classes = [permissions.IsAuthenticatedOrReadOnly] filterset_class = FolderFilter class DocumentViewSet(viewsets.ModelViewSet): \"\"\"",
"on Folder objects \"\"\" queryset = Folder.objects.all().order_by('-created_at') serializer_class = FolderSerializer permission_classes = [permissions.IsAuthenticatedOrReadOnly]",
"\"\"\" queryset = Topic.objects.all().order_by('-created_at') serializer_class = TopicSerializer permission_classes = [permissions.IsAuthenticatedOrReadOnly] filterset_class = TopicFilter",
"Document.objects.all().order_by('-created_at') serializer_class = DocumentSerializer permission_classes = [permissions.IsAuthenticatedOrReadOnly] filterset_class = DocumentFilter class TopicViewSet(viewsets.ModelViewSet): \"\"\"",
"endpoint that allows CRUD operations on Document objects \"\"\" queryset = Document.objects.all().order_by('-created_at') serializer_class",
"Folder objects \"\"\" queryset = Folder.objects.all().order_by('-created_at') serializer_class = FolderSerializer permission_classes = [permissions.IsAuthenticatedOrReadOnly] filterset_class",
"filterset_class = DocumentFilter class TopicViewSet(viewsets.ModelViewSet): \"\"\" API endpoint that allows CRUD operations on",
"import DocumentSerializer, FolderSerializer, TopicSerializer from documents.filters import DocumentFilter, FolderFilter, TopicFilter class FolderViewSet(viewsets.ModelViewSet): \"\"\"",
"queryset = Folder.objects.all().order_by('-created_at') serializer_class = FolderSerializer permission_classes = [permissions.IsAuthenticatedOrReadOnly] filterset_class = FolderFilter class",
"class FolderViewSet(viewsets.ModelViewSet): \"\"\" API endpoint that allows CRUD operations on Folder objects \"\"\"",
"that allows CRUD operations on Document objects \"\"\" queryset = Document.objects.all().order_by('-created_at') serializer_class =",
"allows CRUD operations on Document objects \"\"\" queryset = Document.objects.all().order_by('-created_at') serializer_class = DocumentSerializer",
"API endpoint that allows CRUD operations on Document objects \"\"\" queryset = Document.objects.all().order_by('-created_at')",
"allows CRUD operations on Folder objects \"\"\" queryset = Folder.objects.all().order_by('-created_at') serializer_class = FolderSerializer",
"FolderFilter, TopicFilter class FolderViewSet(viewsets.ModelViewSet): \"\"\" API endpoint that allows CRUD operations on Folder",
"\"\"\" API endpoint that allows CRUD operations on Folder objects \"\"\" queryset =",
"FolderSerializer permission_classes = [permissions.IsAuthenticatedOrReadOnly] filterset_class = FolderFilter class DocumentViewSet(viewsets.ModelViewSet): \"\"\" API endpoint that",
"= FolderFilter class DocumentViewSet(viewsets.ModelViewSet): \"\"\" API endpoint that allows CRUD operations on Document",
"DocumentSerializer, FolderSerializer, TopicSerializer from documents.filters import DocumentFilter, FolderFilter, TopicFilter class FolderViewSet(viewsets.ModelViewSet): \"\"\" API",
"on Document objects \"\"\" queryset = Document.objects.all().order_by('-created_at') serializer_class = DocumentSerializer permission_classes = [permissions.IsAuthenticatedOrReadOnly]",
"\"\"\" API endpoint that allows CRUD operations on Topic objects \"\"\" queryset =",
"DocumentSerializer permission_classes = [permissions.IsAuthenticatedOrReadOnly] filterset_class = DocumentFilter class TopicViewSet(viewsets.ModelViewSet): \"\"\" API endpoint that",
"permission_classes = [permissions.IsAuthenticatedOrReadOnly] filterset_class = DocumentFilter class TopicViewSet(viewsets.ModelViewSet): \"\"\" API endpoint that allows",
"allows CRUD operations on Topic objects \"\"\" queryset = Topic.objects.all().order_by('-created_at') serializer_class = TopicSerializer",
"CRUD operations on Folder objects \"\"\" queryset = Folder.objects.all().order_by('-created_at') serializer_class = FolderSerializer permission_classes",
"viewsets from rest_framework import permissions from documents.models import Document, Folder, Topic from documents.serializers",
"that allows CRUD operations on Folder objects \"\"\" queryset = Folder.objects.all().order_by('-created_at') serializer_class =",
"permission_classes = [permissions.IsAuthenticatedOrReadOnly] filterset_class = FolderFilter class DocumentViewSet(viewsets.ModelViewSet): \"\"\" API endpoint that allows",
"DocumentViewSet(viewsets.ModelViewSet): \"\"\" API endpoint that allows CRUD operations on Document objects \"\"\" queryset",
"Topic objects \"\"\" queryset = Topic.objects.all().order_by('-created_at') serializer_class = TopicSerializer permission_classes = [permissions.IsAuthenticatedOrReadOnly] filterset_class",
"CRUD operations on Document objects \"\"\" queryset = Document.objects.all().order_by('-created_at') serializer_class = DocumentSerializer permission_classes",
"operations on Folder objects \"\"\" queryset = Folder.objects.all().order_by('-created_at') serializer_class = FolderSerializer permission_classes =",
"from documents.filters import DocumentFilter, FolderFilter, TopicFilter class FolderViewSet(viewsets.ModelViewSet): \"\"\" API endpoint that allows",
"\"\"\" queryset = Folder.objects.all().order_by('-created_at') serializer_class = FolderSerializer permission_classes = [permissions.IsAuthenticatedOrReadOnly] filterset_class = FolderFilter",
"<reponame>livcarman/spekit<gh_stars>0 from rest_framework import viewsets from rest_framework import permissions from documents.models import Document,",
"import permissions from documents.models import Document, Folder, Topic from documents.serializers import DocumentSerializer, FolderSerializer,",
"= Document.objects.all().order_by('-created_at') serializer_class = DocumentSerializer permission_classes = [permissions.IsAuthenticatedOrReadOnly] filterset_class = DocumentFilter class TopicViewSet(viewsets.ModelViewSet):",
"FolderViewSet(viewsets.ModelViewSet): \"\"\" API endpoint that allows CRUD operations on Folder objects \"\"\" queryset",
"TopicSerializer from documents.filters import DocumentFilter, FolderFilter, TopicFilter class FolderViewSet(viewsets.ModelViewSet): \"\"\" API endpoint that",
"from rest_framework import viewsets from rest_framework import permissions from documents.models import Document, Folder,",
"endpoint that allows CRUD operations on Folder objects \"\"\" queryset = Folder.objects.all().order_by('-created_at') serializer_class",
"TopicViewSet(viewsets.ModelViewSet): \"\"\" API endpoint that allows CRUD operations on Topic objects \"\"\" queryset",
"Folder, Topic from documents.serializers import DocumentSerializer, FolderSerializer, TopicSerializer from documents.filters import DocumentFilter, FolderFilter,",
"endpoint that allows CRUD operations on Topic objects \"\"\" queryset = Topic.objects.all().order_by('-created_at') serializer_class",
"= [permissions.IsAuthenticatedOrReadOnly] filterset_class = DocumentFilter class TopicViewSet(viewsets.ModelViewSet): \"\"\" API endpoint that allows CRUD",
"objects \"\"\" queryset = Document.objects.all().order_by('-created_at') serializer_class = DocumentSerializer permission_classes = [permissions.IsAuthenticatedOrReadOnly] filterset_class =",
"filterset_class = FolderFilter class DocumentViewSet(viewsets.ModelViewSet): \"\"\" API endpoint that allows CRUD operations on",
"rest_framework import permissions from documents.models import Document, Folder, Topic from documents.serializers import DocumentSerializer,",
"serializer_class = FolderSerializer permission_classes = [permissions.IsAuthenticatedOrReadOnly] filterset_class = FolderFilter class DocumentViewSet(viewsets.ModelViewSet): \"\"\" API",
"objects \"\"\" queryset = Folder.objects.all().order_by('-created_at') serializer_class = FolderSerializer permission_classes = [permissions.IsAuthenticatedOrReadOnly] filterset_class =",
"queryset = Document.objects.all().order_by('-created_at') serializer_class = DocumentSerializer permission_classes = [permissions.IsAuthenticatedOrReadOnly] filterset_class = DocumentFilter class",
"class DocumentViewSet(viewsets.ModelViewSet): \"\"\" API endpoint that allows CRUD operations on Document objects \"\"\"",
"Document, Folder, Topic from documents.serializers import DocumentSerializer, FolderSerializer, TopicSerializer from documents.filters import DocumentFilter,",
"DocumentFilter, FolderFilter, TopicFilter class FolderViewSet(viewsets.ModelViewSet): \"\"\" API endpoint that allows CRUD operations on",
"import Document, Folder, Topic from documents.serializers import DocumentSerializer, FolderSerializer, TopicSerializer from documents.filters import",
"FolderFilter class DocumentViewSet(viewsets.ModelViewSet): \"\"\" API endpoint that allows CRUD operations on Document objects",
"[permissions.IsAuthenticatedOrReadOnly] filterset_class = FolderFilter class DocumentViewSet(viewsets.ModelViewSet): \"\"\" API endpoint that allows CRUD operations",
"operations on Topic objects \"\"\" queryset = Topic.objects.all().order_by('-created_at') serializer_class = TopicSerializer permission_classes =",
"[permissions.IsAuthenticatedOrReadOnly] filterset_class = DocumentFilter class TopicViewSet(viewsets.ModelViewSet): \"\"\" API endpoint that allows CRUD operations",
"documents.models import Document, Folder, Topic from documents.serializers import DocumentSerializer, FolderSerializer, TopicSerializer from documents.filters",
"documents.serializers import DocumentSerializer, FolderSerializer, TopicSerializer from documents.filters import DocumentFilter, FolderFilter, TopicFilter class FolderViewSet(viewsets.ModelViewSet):",
"import viewsets from rest_framework import permissions from documents.models import Document, Folder, Topic from",
"= Folder.objects.all().order_by('-created_at') serializer_class = FolderSerializer permission_classes = [permissions.IsAuthenticatedOrReadOnly] filterset_class = FolderFilter class DocumentViewSet(viewsets.ModelViewSet):",
"import DocumentFilter, FolderFilter, TopicFilter class FolderViewSet(viewsets.ModelViewSet): \"\"\" API endpoint that allows CRUD operations",
"DocumentFilter class TopicViewSet(viewsets.ModelViewSet): \"\"\" API endpoint that allows CRUD operations on Topic objects",
"from documents.serializers import DocumentSerializer, FolderSerializer, TopicSerializer from documents.filters import DocumentFilter, FolderFilter, TopicFilter class",
"= DocumentFilter class TopicViewSet(viewsets.ModelViewSet): \"\"\" API endpoint that allows CRUD operations on Topic",
"permissions from documents.models import Document, Folder, Topic from documents.serializers import DocumentSerializer, FolderSerializer, TopicSerializer",
"= [permissions.IsAuthenticatedOrReadOnly] filterset_class = FolderFilter class DocumentViewSet(viewsets.ModelViewSet): \"\"\" API endpoint that allows CRUD",
"class TopicViewSet(viewsets.ModelViewSet): \"\"\" API endpoint that allows CRUD operations on Topic objects \"\"\"",
"serializer_class = DocumentSerializer permission_classes = [permissions.IsAuthenticatedOrReadOnly] filterset_class = DocumentFilter class TopicViewSet(viewsets.ModelViewSet): \"\"\" API",
"CRUD operations on Topic objects \"\"\" queryset = Topic.objects.all().order_by('-created_at') serializer_class = TopicSerializer permission_classes",
"from rest_framework import permissions from documents.models import Document, Folder, Topic from documents.serializers import",
"\"\"\" queryset = Document.objects.all().order_by('-created_at') serializer_class = DocumentSerializer permission_classes = [permissions.IsAuthenticatedOrReadOnly] filterset_class = DocumentFilter",
"= FolderSerializer permission_classes = [permissions.IsAuthenticatedOrReadOnly] filterset_class = FolderFilter class DocumentViewSet(viewsets.ModelViewSet): \"\"\" API endpoint",
"on Topic objects \"\"\" queryset = Topic.objects.all().order_by('-created_at') serializer_class = TopicSerializer permission_classes = [permissions.IsAuthenticatedOrReadOnly]",
"TopicFilter class FolderViewSet(viewsets.ModelViewSet): \"\"\" API endpoint that allows CRUD operations on Folder objects",
"FolderSerializer, TopicSerializer from documents.filters import DocumentFilter, FolderFilter, TopicFilter class FolderViewSet(viewsets.ModelViewSet): \"\"\" API endpoint",
"that allows CRUD operations on Topic objects \"\"\" queryset = Topic.objects.all().order_by('-created_at') serializer_class =",
"= DocumentSerializer permission_classes = [permissions.IsAuthenticatedOrReadOnly] filterset_class = DocumentFilter class TopicViewSet(viewsets.ModelViewSet): \"\"\" API endpoint",
"Document objects \"\"\" queryset = Document.objects.all().order_by('-created_at') serializer_class = DocumentSerializer permission_classes = [permissions.IsAuthenticatedOrReadOnly] filterset_class",
"API endpoint that allows CRUD operations on Folder objects \"\"\" queryset = Folder.objects.all().order_by('-created_at')",
"Topic from documents.serializers import DocumentSerializer, FolderSerializer, TopicSerializer from documents.filters import DocumentFilter, FolderFilter, TopicFilter",
"rest_framework import viewsets from rest_framework import permissions from documents.models import Document, Folder, Topic",
"\"\"\" API endpoint that allows CRUD operations on Document objects \"\"\" queryset =",
"documents.filters import DocumentFilter, FolderFilter, TopicFilter class FolderViewSet(viewsets.ModelViewSet): \"\"\" API endpoint that allows CRUD"
] |
[
"# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A",
"THE COPYRIGHT # HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, #",
"Input file: %s\" % infile print \"# Output file: %s\" % outfile print",
"ANY # WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED",
"IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. ## # \\file perf_summarize_file.py",
"file names. (infile_head, infile_tail) = os.path.split(infile) merged_in_fname = infile_head + merge_type + \"_\"",
"All rights reserved. # # Redistribution and use in source and binary forms,",
"software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY",
"merged_in_fname = infile_head + merge_type + \"_\" + infile_tail (outfile_head, outfile_tail) = os.path.split(outfile)",
"# \\author <NAME> # \\version 1.02 import os import sys from PerfDataPoint import",
"THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE",
"CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY",
"PerfDataPoint.MERGE_SUM input_data = PerfDataParser.parse_data_file(infile, default_desc=merged_in_fname, merge_type=merge_val, compute_average=True) input_data.output_to_file(merged_out_fname) # Run if we aren't",
"if we aren't importing. # Right now, we can't really import this file...",
"outfile_tail print \"Generating output file %s\" % merged_out_fname if (merge_type == \"min\"): merge_val",
"outfile_head + merge_type + \"_\" + outfile_tail print \"Generating output file %s\" %",
"DAMAGES (INCLUDING, # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;",
"following conditions # are met: # # * Redistributions of source code must",
"= os.path.split(outfile) merged_out_fname = outfile_head + merge_type + \"_\" + outfile_tail print \"Generating",
"HOWEVER CAUSED # AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT",
"* Redistributions of source code must retain the above copyright # notice, this",
"\"# Output file: %s\" % outfile print \"# Merge type: %s\" % merge_type",
"Output file: %s\" % outfile print \"# Merge type: %s\" % merge_type #",
"print \"# Merge type: %s\" % merge_type # Compute a merged input/output file",
"print \" <merge_type> is \\\"avg\\\" by default (can be \\\"min\\\")\" exit(0) if (len(sys.argv)",
"together. # # \\author <NAME> # \\version 1.02 import os import sys from",
"IN NO EVENT SHALL THE COPYRIGHT # HOLDER OR CONTRIBUTORS BE LIABLE FOR",
"SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. ## #",
"% outfile print \"# Merge type: %s\" % merge_type # Compute a merged",
"Script to read in input file, and merge all data points with the",
"else: merge_val = PerfDataPoint.MERGE_SUM input_data = PerfDataParser.parse_data_file(infile, default_desc=merged_in_fname, merge_type=merge_val, compute_average=True) input_data.output_to_file(merged_out_fname) # Run",
"of conditions and the following disclaimer. # * Redistributions in binary form must",
"default\" print \" <merge_type> is \\\"avg\\\" by default (can be \\\"min\\\")\" exit(0) if",
"IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY",
"ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING",
"main(): infile = None outfile = \"tmp_summary_output.dat\" merge_type = \"avg\" if (len(sys.argv) >",
"PerfDataParser; ## # Script to read in input file, and merge all data",
"= \"avg\" print \"# Input file: %s\" % infile print \"# Output file:",
"+ infile_tail (outfile_head, outfile_tail) = os.path.split(outfile) merged_out_fname = outfile_head + merge_type + \"_\"",
"ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. ## # \\file perf_summarize_file.py #",
"test script</i>]: Reads in a file of performance # data, and merges all",
"infile print \"# Output file: %s\" % outfile print \"# Merge type: %s\"",
"be \\\"min\\\")\" # def main(): infile = None outfile = \"tmp_summary_output.dat\" merge_type =",
"SUCH DAMAGE. ## # \\file perf_summarize_file.py # # \\brief [<i>Performance test script</i>]: Reads",
"else: print \"Usage: <this script> <infile> <outfile> <merge_type>\" print \" <infile> is a",
"also be \\\"min\\\")\" # def main(): infile = None outfile = \"tmp_summary_output.dat\" merge_type",
"NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS # OF USE,",
"+ merge_type + \"_\" + outfile_tail print \"Generating output file %s\" % merged_out_fname",
"this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED",
"INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, # BUT NOT LIMITED",
"this list of conditions and the following disclaimer. # * Redistributions in binary",
"input/output file names. (infile_head, infile_tail) = os.path.split(infile) merged_in_fname = infile_head + merge_type +",
"DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED # AND ON ANY THEORY",
"ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED",
"\"avg\" if (len(sys.argv) > 1): infile = sys.argv[1] else: print \"Usage: <this script>",
"in input file, and merge all data points with the # same key",
"and/or other materials provided with the # distribution. # * Neither the name",
"not in { \"avg\", \"min\" }): merge_type = \"avg\" print \"# Input file:",
"% merged_out_fname if (merge_type == \"min\"): merge_val = PerfDataPoint.MERGE_MIN elif (merge_type == \"max\"):",
"\\author <NAME> # \\version 1.02 import os import sys from PerfDataPoint import *;",
"conditions and the following disclaimer. # * Redistributions in binary form must reproduce",
"other materials provided with the # distribution. # * Neither the name of",
"points with the same key together. # # \\author <NAME> # \\version 1.02",
"IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED.",
"the # distribution. # * Neither the name of Intel Corporation nor the",
"# from this software without specific prior written permission. # # THIS SOFTWARE",
"# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, # BUT NOT LIMITED TO,",
"# \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT #",
"# the documentation and/or other materials provided with the # distribution. # *",
"sys.argv[1] else: print \"Usage: <this script> <infile> <outfile> <merge_type>\" print \" <infile> is",
"## # \\file perf_summarize_file.py # # \\brief [<i>Performance test script</i>]: Reads in a",
"following disclaimer. # * Redistributions in binary form must reproduce the above copyright",
"# data, and merges all data points with the same key together. #",
"\"Usage: <this script> <infile> <outfile> <merge_type>\" print \" <infile> is a required argument.\"",
"are permitted provided that the following conditions # are met: # # *",
"== \"max\"): merge_val = PerfDataPoint.MERGE_MAX else: merge_val = PerfDataPoint.MERGE_SUM input_data = PerfDataParser.parse_data_file(infile, default_desc=merged_in_fname,",
"importing. # Right now, we can't really import this file... if __name__ ==",
"+ merge_type + \"_\" + infile_tail (outfile_head, outfile_tail) = os.path.split(outfile) merged_out_fname = outfile_head",
"or without # modification, are permitted provided that the following conditions # are",
"merge_type = sys.argv[3] if (merge_type not in { \"avg\", \"min\" }): merge_type =",
"file: %s\" % infile print \"# Output file: %s\" % outfile print \"#",
"the documentation and/or other materials provided with the # distribution. # * Neither",
"type: %s\" % merge_type # Compute a merged input/output file names. (infile_head, infile_tail)",
"data points with the same key together. # # \\author <NAME> # \\version",
"(outfile_head, outfile_tail) = os.path.split(outfile) merged_out_fname = outfile_head + merge_type + \"_\" + outfile_tail",
"= \"tmp_summary_output.dat\" merge_type = \"avg\" if (len(sys.argv) > 1): infile = sys.argv[1] else:",
"merges all data points with the same key together. # # \\author <NAME>",
"STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY #",
"above copyright # notice, this list of conditions and the following disclaimer. #",
"CAUSED # AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT #",
"NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR #",
"list of conditions and the following disclaimer. # * Redistributions in binary form",
"rights reserved. # # Redistribution and use in source and binary forms, with",
"input_data = PerfDataParser.parse_data_file(infile, default_desc=merged_in_fname, merge_type=merge_val, compute_average=True) input_data.output_to_file(merged_out_fname) # Run if we aren't importing.",
"OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY",
"{ \"avg\", \"min\" }): merge_type = \"avg\" print \"# Input file: %s\" %",
"= PerfDataPoint.MERGE_MAX else: merge_val = PerfDataPoint.MERGE_SUM input_data = PerfDataParser.parse_data_file(infile, default_desc=merged_in_fname, merge_type=merge_val, compute_average=True) input_data.output_to_file(merged_out_fname)",
"permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS",
"Redistributions in binary form must reproduce the above copyright # notice, this list",
"products derived # from this software without specific prior written permission. # #",
"OR OTHERWISE) ARISING IN ANY # WAY OUT OF THE USE OF THIS",
"infile = None outfile = \"tmp_summary_output.dat\" merge_type = \"avg\" if (len(sys.argv) > 1):",
"merge_type + \"_\" + infile_tail (outfile_head, outfile_tail) = os.path.split(outfile) merged_out_fname = outfile_head +",
"or promote products derived # from this software without specific prior written permission.",
"provided that the following conditions # are met: # # * Redistributions of",
"default (can be \\\"min\\\")\" exit(0) if (len(sys.argv) > 2): outfile = sys.argv[2] if",
"conditions # are met: # # * Redistributions of source code must retain",
"# POSSIBILITY OF SUCH DAMAGE. ## # \\file perf_summarize_file.py # # \\brief [<i>Performance",
"EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE",
"materials provided with the # distribution. # * Neither the name of Intel",
"os import sys from PerfDataPoint import *; from PerfDataSet import *; import PerfDataParser;",
"(len(sys.argv) > 1): infile = sys.argv[1] else: print \"Usage: <this script> <infile> <outfile>",
"with or without # modification, are permitted provided that the following conditions #",
"\" <outfile> is \\\"tmp_summary_output.dat\\\" by default\" print \" <merge_type> is \\\"avg\\\" by default",
"a required argument.\" print \" <outfile> is \\\"tmp_summary_output.dat\\\" by default\" print \" <merge_type>",
"SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # \"AS IS\" AND",
"compute_average=True) input_data.output_to_file(merged_out_fname) # Run if we aren't importing. # Right now, we can't",
"+ \"_\" + outfile_tail print \"Generating output file %s\" % merged_out_fname if (merge_type",
"\"_\" + infile_tail (outfile_head, outfile_tail) = os.path.split(outfile) merged_out_fname = outfile_head + merge_type +",
"merge_type + \"_\" + outfile_tail print \"Generating output file %s\" % merged_out_fname if",
"all data points with the same key together. # # \\author <NAME> #",
"required argument.\" print \" <outfile> is \\\"tmp_summary_output.dat\\\" by default\" print \" <merge_type> is",
"COPYRIGHT HOLDERS AND CONTRIBUTORS # \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES,",
"* Redistributions in binary form must reproduce the above copyright # notice, this",
"argument.\" print \" <outfile> is \\\"tmp_summary_output.dat\\\" by default\" print \" <merge_type> is \\\"avg\\\"",
"without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE",
"\\\"avg\\\" by default (can also be \\\"min\\\")\" # def main(): infile = None",
"merge all data points with the # same key together. # # Usage:",
"a required argument.\" # <outfile> is \\\"tmp_summary_output.dat\\\" by default\" # [merge_type] is \\\"avg\\\"",
"\" <infile> is a required argument.\" print \" <outfile> is \\\"tmp_summary_output.dat\\\" by default\"",
"outfile_tail) = os.path.split(outfile) merged_out_fname = outfile_head + merge_type + \"_\" + outfile_tail print",
"and merges all data points with the same key together. # # \\author",
"PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # HOLDER OR CONTRIBUTORS",
"code must retain the above copyright # notice, this list of conditions and",
"# * Redistributions in binary form must reproduce the above copyright # notice,",
"\"Generating output file %s\" % merged_out_fname if (merge_type == \"min\"): merge_val = PerfDataPoint.MERGE_MIN",
"## # Script to read in input file, and merge all data points",
"(merge_type not in { \"avg\", \"min\" }): merge_type = \"avg\" print \"# Input",
"= PerfDataParser.parse_data_file(infile, default_desc=merged_in_fname, merge_type=merge_val, compute_average=True) input_data.output_to_file(merged_out_fname) # Run if we aren't importing. #",
"file of performance # data, and merges all data points with the same",
"CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL",
"# # \\brief [<i>Performance test script</i>]: Reads in a file of performance #",
"disclaimer in # the documentation and/or other materials provided with the # distribution.",
"PerfDataParser.parse_data_file(infile, default_desc=merged_in_fname, merge_type=merge_val, compute_average=True) input_data.output_to_file(merged_out_fname) # Run if we aren't importing. # Right",
"[merge_type] is \\\"avg\\\" by default (can also be \\\"min\\\")\" # def main(): infile",
"<infile> <outfile> <merge_type>\" print \" <infile> is a required argument.\" print \" <outfile>",
"the same key together. # # \\author <NAME> # \\version 1.02 import os",
"outfile print \"# Merge type: %s\" % merge_type # Compute a merged input/output",
"OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY # WAY OUT OF",
"if (len(sys.argv) > 1): infile = sys.argv[1] else: print \"Usage: <this script> <infile>",
"> 2): outfile = sys.argv[2] if (len(sys.argv) > 3): merge_type = sys.argv[3] if",
"file, and merge all data points with the # same key together. #",
"to endorse or promote products derived # from this software without specific prior",
"GOODS OR SERVICES; LOSS # OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)",
"script> <infile> [outfile] [merge_type] # <infile> is a required argument.\" # <outfile> is",
"= outfile_head + merge_type + \"_\" + outfile_tail print \"Generating output file %s\"",
"\\\"avg\\\" by default (can be \\\"min\\\")\" exit(0) if (len(sys.argv) > 2): outfile =",
"AND CONTRIBUTORS # \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT",
"and use in source and binary forms, with or without # modification, are",
"THE COPYRIGHT HOLDERS AND CONTRIBUTORS # \"AS IS\" AND ANY EXPRESS OR IMPLIED",
"name of Intel Corporation nor the names of its # contributors may be",
"PerfDataPoint import *; from PerfDataSet import *; import PerfDataParser; ## # Script to",
"(INCLUDING, # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS",
"merged input/output file names. (infile_head, infile_tail) = os.path.split(infile) merged_in_fname = infile_head + merge_type",
"IN ANY # WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF",
"EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES",
"OR CONSEQUENTIAL DAMAGES (INCLUDING, # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS",
"copyright # notice, this list of conditions and the following disclaimer. # *",
"PerfDataPoint.MERGE_MAX else: merge_val = PerfDataPoint.MERGE_SUM input_data = PerfDataParser.parse_data_file(infile, default_desc=merged_in_fname, merge_type=merge_val, compute_average=True) input_data.output_to_file(merged_out_fname) #",
"# * Redistributions of source code must retain the above copyright # notice,",
"3): merge_type = sys.argv[3] if (merge_type not in { \"avg\", \"min\" }): merge_type",
"# Usage: <this script> <infile> [outfile] [merge_type] # <infile> is a required argument.\"",
"PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS # OF USE, DATA, OR PROFITS;",
"a file of performance # data, and merges all data points with the",
"# same key together. # # Usage: <this script> <infile> [outfile] [merge_type] #",
"EVENT SHALL THE COPYRIGHT # HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,",
"merge_type = \"avg\" if (len(sys.argv) > 1): infile = sys.argv[1] else: print \"Usage:",
"of its # contributors may be used to endorse or promote products derived",
"None outfile = \"tmp_summary_output.dat\" merge_type = \"avg\" if (len(sys.argv) > 1): infile =",
"# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS #",
"endorse or promote products derived # from this software without specific prior written",
"in a file of performance # data, and merges all data points with",
"\"tmp_summary_output.dat\" merge_type = \"avg\" if (len(sys.argv) > 1): infile = sys.argv[1] else: print",
"ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT",
"if (merge_type not in { \"avg\", \"min\" }): merge_type = \"avg\" print \"#",
"script> <infile> <outfile> <merge_type>\" print \" <infile> is a required argument.\" print \"",
"# distribution. # * Neither the name of Intel Corporation nor the names",
"# Script to read in input file, and merge all data points with",
"\\\"min\\\")\" # def main(): infile = None outfile = \"tmp_summary_output.dat\" merge_type = \"avg\"",
"HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY,",
"# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY # WAY",
"must retain the above copyright # notice, this list of conditions and the",
"(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY # WAY OUT OF THE USE",
"OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE.",
"Redistribution and use in source and binary forms, with or without # modification,",
"> 3): merge_type = sys.argv[3] if (merge_type not in { \"avg\", \"min\" }):",
"import PerfDataParser; ## # Script to read in input file, and merge all",
"source and binary forms, with or without # modification, are permitted provided that",
"if (len(sys.argv) > 2): outfile = sys.argv[2] if (len(sys.argv) > 3): merge_type =",
"OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED # AND ON",
"*; import PerfDataParser; ## # Script to read in input file, and merge",
"above copyright # notice, this list of conditions and the following disclaimer in",
"from PerfDataPoint import *; from PerfDataSet import *; import PerfDataParser; ## # Script",
"conditions and the following disclaimer in # the documentation and/or other materials provided",
"THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # \"AS IS\"",
"binary form must reproduce the above copyright # notice, this list of conditions",
"Redistributions of source code must retain the above copyright # notice, this list",
"form must reproduce the above copyright # notice, this list of conditions and",
"# * Neither the name of Intel Corporation nor the names of its",
"used to endorse or promote products derived # from this software without specific",
"\\\"tmp_summary_output.dat\\\" by default\" print \" <merge_type> is \\\"avg\\\" by default (can be \\\"min\\\")\"",
"1): infile = sys.argv[1] else: print \"Usage: <this script> <infile> <outfile> <merge_type>\" print",
"argument.\" # <outfile> is \\\"tmp_summary_output.dat\\\" by default\" # [merge_type] is \\\"avg\\\" by default",
"2): outfile = sys.argv[2] if (len(sys.argv) > 3): merge_type = sys.argv[3] if (merge_type",
"notice, this list of conditions and the following disclaimer. # * Redistributions in",
"LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,",
"WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN",
"a merged input/output file names. (infile_head, infile_tail) = os.path.split(infile) merged_in_fname = infile_head +",
"INTERRUPTION) HOWEVER CAUSED # AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,",
"*; from PerfDataSet import *; import PerfDataParser; ## # Script to read in",
"with the # same key together. # # Usage: <this script> <infile> [outfile]",
"if (merge_type == \"min\"): merge_val = PerfDataPoint.MERGE_MIN elif (merge_type == \"max\"): merge_val =",
"OTHERWISE) ARISING IN ANY # WAY OUT OF THE USE OF THIS SOFTWARE,",
"%s\" % merged_out_fname if (merge_type == \"min\"): merge_val = PerfDataPoint.MERGE_MIN elif (merge_type ==",
"# # Usage: <this script> <infile> [outfile] [merge_type] # <infile> is a required",
"import sys from PerfDataPoint import *; from PerfDataSet import *; import PerfDataParser; ##",
"provided with the # distribution. # * Neither the name of Intel Corporation",
"AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR",
"the above copyright # notice, this list of conditions and the following disclaimer",
"import *; from PerfDataSet import *; import PerfDataParser; ## # Script to read",
"elif (merge_type == \"max\"): merge_val = PerfDataPoint.MERGE_MAX else: merge_val = PerfDataPoint.MERGE_SUM input_data =",
"= None outfile = \"tmp_summary_output.dat\" merge_type = \"avg\" if (len(sys.argv) > 1): infile",
"(C) 2013 Intel Corporation # All rights reserved. # # Redistribution and use",
"PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # \"AS IS\" AND ANY EXPRESS",
"by default (can also be \\\"min\\\")\" # def main(): infile = None outfile",
"Reads in a file of performance # data, and merges all data points",
"(merge_type == \"min\"): merge_val = PerfDataPoint.MERGE_MIN elif (merge_type == \"max\"): merge_val = PerfDataPoint.MERGE_MAX",
"read in input file, and merge all data points with the # same",
"is \\\"avg\\\" by default (can be \\\"min\\\")\" exit(0) if (len(sys.argv) > 2): outfile",
"that the following conditions # are met: # # * Redistributions of source",
"is a required argument.\" print \" <outfile> is \\\"tmp_summary_output.dat\\\" by default\" print \"",
"be \\\"min\\\")\" exit(0) if (len(sys.argv) > 2): outfile = sys.argv[2] if (len(sys.argv) >",
"OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR",
"\\file perf_summarize_file.py # # \\brief [<i>Performance test script</i>]: Reads in a file of",
"forms, with or without # modification, are permitted provided that the following conditions",
"perf_summarize_file.py # # \\brief [<i>Performance test script</i>]: Reads in a file of performance",
"output file %s\" % merged_out_fname if (merge_type == \"min\"): merge_val = PerfDataPoint.MERGE_MIN elif",
"with the # distribution. # * Neither the name of Intel Corporation nor",
"source code must retain the above copyright # notice, this list of conditions",
"FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT",
"\"avg\", \"min\" }): merge_type = \"avg\" print \"# Input file: %s\" % infile",
"contributors may be used to endorse or promote products derived # from this",
"in source and binary forms, with or without # modification, are permitted provided",
"# Compute a merged input/output file names. (infile_head, infile_tail) = os.path.split(infile) merged_in_fname =",
"SUBSTITUTE GOODS OR SERVICES; LOSS # OF USE, DATA, OR PROFITS; OR BUSINESS",
"SERVICES; LOSS # OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED",
"BUSINESS INTERRUPTION) HOWEVER CAUSED # AND ON ANY THEORY OF LIABILITY, WHETHER IN",
"TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY # WAY OUT OF THE",
"# # Redistribution and use in source and binary forms, with or without",
"to read in input file, and merge all data points with the #",
"\"# Merge type: %s\" % merge_type # Compute a merged input/output file names.",
"DAMAGE. ## # \\file perf_summarize_file.py # # \\brief [<i>Performance test script</i>]: Reads in",
"LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY # WAY OUT",
"INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, # BUT NOT LIMITED TO, PROCUREMENT",
"# # \\author <NAME> # \\version 1.02 import os import sys from PerfDataPoint",
"[<i>Performance test script</i>]: Reads in a file of performance # data, and merges",
"A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # HOLDER",
"we aren't importing. # Right now, we can't really import this file... if",
"<outfile> is \\\"tmp_summary_output.dat\\\" by default\" # [merge_type] is \\\"avg\\\" by default (can also",
"script</i>]: Reads in a file of performance # data, and merges all data",
"SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, # BUT NOT LIMITED TO, PROCUREMENT OF",
"BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # \"AS IS\" AND ANY EXPRESS OR",
"together. # # Usage: <this script> <infile> [outfile] [merge_type] # <infile> is a",
"Run if we aren't importing. # Right now, we can't really import this",
"# \\version 1.02 import os import sys from PerfDataPoint import *; from PerfDataSet",
"may be used to endorse or promote products derived # from this software",
"<infile> is a required argument.\" # <outfile> is \\\"tmp_summary_output.dat\\\" by default\" # [merge_type]",
"prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS",
"print \" <outfile> is \\\"tmp_summary_output.dat\\\" by default\" print \" <merge_type> is \\\"avg\\\" by",
"PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # HOLDER OR",
"exit(0) if (len(sys.argv) > 2): outfile = sys.argv[2] if (len(sys.argv) > 3): merge_type",
"this list of conditions and the following disclaimer in # the documentation and/or",
"key together. # # \\author <NAME> # \\version 1.02 import os import sys",
"%s\" % merge_type # Compute a merged input/output file names. (infile_head, infile_tail) =",
"of conditions and the following disclaimer in # the documentation and/or other materials",
"# contributors may be used to endorse or promote products derived # from",
"AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE",
"\"min\"): merge_val = PerfDataPoint.MERGE_MIN elif (merge_type == \"max\"): merge_val = PerfDataPoint.MERGE_MAX else: merge_val",
"required argument.\" # <outfile> is \\\"tmp_summary_output.dat\\\" by default\" # [merge_type] is \\\"avg\\\" by",
"is \\\"tmp_summary_output.dat\\\" by default\" # [merge_type] is \\\"avg\\\" by default (can also be",
"IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO,",
"use in source and binary forms, with or without # modification, are permitted",
"NO EVENT SHALL THE COPYRIGHT # HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY",
"in binary form must reproduce the above copyright # notice, this list of",
"key together. # # Usage: <this script> <infile> [outfile] [merge_type] # <infile> is",
"# notice, this list of conditions and the following disclaimer in # the",
"(len(sys.argv) > 3): merge_type = sys.argv[3] if (merge_type not in { \"avg\", \"min\"",
"<outfile> <merge_type>\" print \" <infile> is a required argument.\" print \" <outfile> is",
"%s\" % outfile print \"# Merge type: %s\" % merge_type # Compute a",
"# All rights reserved. # # Redistribution and use in source and binary",
"COPYRIGHT # HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL,",
"merged_out_fname if (merge_type == \"min\"): merge_val = PerfDataPoint.MERGE_MIN elif (merge_type == \"max\"): merge_val",
"Compute a merged input/output file names. (infile_head, infile_tail) = os.path.split(infile) merged_in_fname = infile_head",
"by default (can be \\\"min\\\")\" exit(0) if (len(sys.argv) > 2): outfile = sys.argv[2]",
"BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES",
"\\\"min\\\")\" exit(0) if (len(sys.argv) > 2): outfile = sys.argv[2] if (len(sys.argv) > 3):",
"# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # \"AS",
"PerfDataPoint.MERGE_MIN elif (merge_type == \"max\"): merge_val = PerfDataPoint.MERGE_MAX else: merge_val = PerfDataPoint.MERGE_SUM input_data",
"modification, are permitted provided that the following conditions # are met: # #",
"# modification, are permitted provided that the following conditions # are met: #",
"# WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF",
"notice, this list of conditions and the following disclaimer in # the documentation",
"(can also be \\\"min\\\")\" # def main(): infile = None outfile = \"tmp_summary_output.dat\"",
"of performance # data, and merges all data points with the same key",
"\\version 1.02 import os import sys from PerfDataPoint import *; from PerfDataSet import",
"\"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED",
"NEGLIGENCE OR OTHERWISE) ARISING IN ANY # WAY OUT OF THE USE OF",
"WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING",
"file: %s\" % outfile print \"# Merge type: %s\" % merge_type # Compute",
"sys from PerfDataPoint import *; from PerfDataSet import *; import PerfDataParser; ## #",
"distribution. # * Neither the name of Intel Corporation nor the names of",
"os.path.split(infile) merged_in_fname = infile_head + merge_type + \"_\" + infile_tail (outfile_head, outfile_tail) =",
"print \"# Output file: %s\" % outfile print \"# Merge type: %s\" %",
"the following conditions # are met: # # * Redistributions of source code",
"and merge all data points with the # same key together. # #",
"LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)",
"(can be \\\"min\\\")\" exit(0) if (len(sys.argv) > 2): outfile = sys.argv[2] if (len(sys.argv)",
"HOLDERS AND CONTRIBUTORS # \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,",
"data, and merges all data points with the same key together. # #",
"outfile = \"tmp_summary_output.dat\" merge_type = \"avg\" if (len(sys.argv) > 1): infile = sys.argv[1]",
"sys.argv[2] if (len(sys.argv) > 3): merge_type = sys.argv[3] if (merge_type not in {",
"the # same key together. # # Usage: <this script> <infile> [outfile] [merge_type]",
"points with the # same key together. # # Usage: <this script> <infile>",
"and the following disclaimer. # * Redistributions in binary form must reproduce the",
"LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS # OF USE, DATA,",
"merge_val = PerfDataPoint.MERGE_MAX else: merge_val = PerfDataPoint.MERGE_SUM input_data = PerfDataParser.parse_data_file(infile, default_desc=merged_in_fname, merge_type=merge_val, compute_average=True)",
"ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, # BUT",
"infile_tail (outfile_head, outfile_tail) = os.path.split(outfile) merged_out_fname = outfile_head + merge_type + \"_\" +",
"merged_out_fname = outfile_head + merge_type + \"_\" + outfile_tail print \"Generating output file",
"documentation and/or other materials provided with the # distribution. # * Neither the",
"OF THE # POSSIBILITY OF SUCH DAMAGE. ## # \\file perf_summarize_file.py # #",
"THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. ##",
"<outfile> is \\\"tmp_summary_output.dat\\\" by default\" print \" <merge_type> is \\\"avg\\\" by default (can",
"print \"Generating output file %s\" % merged_out_fname if (merge_type == \"min\"): merge_val =",
"default_desc=merged_in_fname, merge_type=merge_val, compute_average=True) input_data.output_to_file(merged_out_fname) # Run if we aren't importing. # Right now,",
"(len(sys.argv) > 2): outfile = sys.argv[2] if (len(sys.argv) > 3): merge_type = sys.argv[3]",
"[merge_type] # <infile> is a required argument.\" # <outfile> is \\\"tmp_summary_output.dat\\\" by default\"",
"# <outfile> is \\\"tmp_summary_output.dat\\\" by default\" # [merge_type] is \\\"avg\\\" by default (can",
"# [merge_type] is \\\"avg\\\" by default (can also be \\\"min\\\")\" # def main():",
"% infile print \"# Output file: %s\" % outfile print \"# Merge type:",
"= sys.argv[1] else: print \"Usage: <this script> <infile> <outfile> <merge_type>\" print \" <infile>",
"Neither the name of Intel Corporation nor the names of its # contributors",
"its # contributors may be used to endorse or promote products derived #",
"THE # POSSIBILITY OF SUCH DAMAGE. ## # \\file perf_summarize_file.py # # \\brief",
"# Run if we aren't importing. # Right now, we can't really import",
"# <infile> is a required argument.\" # <outfile> is \\\"tmp_summary_output.dat\\\" by default\" #",
"OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO",
"reproduce the above copyright # notice, this list of conditions and the following",
"= os.path.split(infile) merged_in_fname = infile_head + merge_type + \"_\" + infile_tail (outfile_head, outfile_tail)",
"= PerfDataPoint.MERGE_SUM input_data = PerfDataParser.parse_data_file(infile, default_desc=merged_in_fname, merge_type=merge_val, compute_average=True) input_data.output_to_file(merged_out_fname) # Run if we",
"data points with the # same key together. # # Usage: <this script>",
"BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR",
"copyright # notice, this list of conditions and the following disclaimer in #",
"be used to endorse or promote products derived # from this software without",
"and binary forms, with or without # modification, are permitted provided that the",
"names of its # contributors may be used to endorse or promote products",
"sys.argv[3] if (merge_type not in { \"avg\", \"min\" }): merge_type = \"avg\" print",
"AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL",
"default\" # [merge_type] is \\\"avg\\\" by default (can also be \\\"min\\\")\" # def",
"import os import sys from PerfDataPoint import *; from PerfDataSet import *; import",
"Merge type: %s\" % merge_type # Compute a merged input/output file names. (infile_head,",
"print \"Usage: <this script> <infile> <outfile> <merge_type>\" print \" <infile> is a required",
"os.path.split(outfile) merged_out_fname = outfile_head + merge_type + \"_\" + outfile_tail print \"Generating output",
"infile_head + merge_type + \"_\" + infile_tail (outfile_head, outfile_tail) = os.path.split(outfile) merged_out_fname =",
"if (len(sys.argv) > 3): merge_type = sys.argv[3] if (merge_type not in { \"avg\",",
"= \"avg\" if (len(sys.argv) > 1): infile = sys.argv[1] else: print \"Usage: <this",
"\"min\" }): merge_type = \"avg\" print \"# Input file: %s\" % infile print",
"in # the documentation and/or other materials provided with the # distribution. #",
"from PerfDataSet import *; import PerfDataParser; ## # Script to read in input",
"% merge_type # Compute a merged input/output file names. (infile_head, infile_tail) = os.path.split(infile)",
"outfile = sys.argv[2] if (len(sys.argv) > 3): merge_type = sys.argv[3] if (merge_type not",
"merge_type # Compute a merged input/output file names. (infile_head, infile_tail) = os.path.split(infile) merged_in_fname",
"and the following disclaimer in # the documentation and/or other materials provided with",
"# AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY,",
"the following disclaimer in # the documentation and/or other materials provided with the",
"IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # \"AS IS\" AND ANY",
"are met: # # * Redistributions of source code must retain the above",
"(merge_type == \"max\"): merge_val = PerfDataPoint.MERGE_MAX else: merge_val = PerfDataPoint.MERGE_SUM input_data = PerfDataParser.parse_data_file(infile,",
"IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN",
"Copyright (C) 2013 Intel Corporation # All rights reserved. # # Redistribution and",
"TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE",
"Intel Corporation # All rights reserved. # # Redistribution and use in source",
"<this script> <infile> [outfile] [merge_type] # <infile> is a required argument.\" # <outfile>",
"+ outfile_tail print \"Generating output file %s\" % merged_out_fname if (merge_type == \"min\"):",
"WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND",
"# \\file perf_summarize_file.py # # \\brief [<i>Performance test script</i>]: Reads in a file",
"# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT #",
"\"# Input file: %s\" % infile print \"# Output file: %s\" % outfile",
"CONSEQUENTIAL DAMAGES (INCLUDING, # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR",
"2013 Intel Corporation # All rights reserved. # # Redistribution and use in",
"derived # from this software without specific prior written permission. # # THIS",
"FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE",
"performance # data, and merges all data points with the same key together.",
"= PerfDataPoint.MERGE_MIN elif (merge_type == \"max\"): merge_val = PerfDataPoint.MERGE_MAX else: merge_val = PerfDataPoint.MERGE_SUM",
"Right now, we can't really import this file... if __name__ == \"__main__\": main()",
"CONTRIBUTORS # \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT",
"}): merge_type = \"avg\" print \"# Input file: %s\" % infile print \"#",
"LOSS # OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED #",
"all data points with the # same key together. # # Usage: <this",
"input_data.output_to_file(merged_out_fname) # Run if we aren't importing. # Right now, we can't really",
"met: # # * Redistributions of source code must retain the above copyright",
"\" <merge_type> is \\\"avg\\\" by default (can be \\\"min\\\")\" exit(0) if (len(sys.argv) >",
"Usage: <this script> <infile> [outfile] [merge_type] # <infile> is a required argument.\" #",
"LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR",
"is \\\"avg\\\" by default (can also be \\\"min\\\")\" # def main(): infile =",
"<this script> <infile> <outfile> <merge_type>\" print \" <infile> is a required argument.\" print",
"merge_val = PerfDataPoint.MERGE_MIN elif (merge_type == \"max\"): merge_val = PerfDataPoint.MERGE_MAX else: merge_val =",
"infile = sys.argv[1] else: print \"Usage: <this script> <infile> <outfile> <merge_type>\" print \"",
"merge_type = \"avg\" print \"# Input file: %s\" % infile print \"# Output",
"> 1): infile = sys.argv[1] else: print \"Usage: <this script> <infile> <outfile> <merge_type>\"",
"OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF",
"infile_tail) = os.path.split(infile) merged_in_fname = infile_head + merge_type + \"_\" + infile_tail (outfile_head,",
"THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE",
"by default\" print \" <merge_type> is \\\"avg\\\" by default (can be \\\"min\\\")\" exit(0)",
"DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # HOLDER OR CONTRIBUTORS BE LIABLE",
"THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF",
"ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # HOLDER OR CONTRIBUTORS BE",
"must reproduce the above copyright # notice, this list of conditions and the",
"* Neither the name of Intel Corporation nor the names of its #",
"Corporation nor the names of its # contributors may be used to endorse",
"<infile> [outfile] [merge_type] # <infile> is a required argument.\" # <outfile> is \\\"tmp_summary_output.dat\\\"",
"the name of Intel Corporation nor the names of its # contributors may",
"Intel Corporation nor the names of its # contributors may be used to",
"<merge_type>\" print \" <infile> is a required argument.\" print \" <outfile> is \\\"tmp_summary_output.dat\\\"",
"FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, #",
"(infile_head, infile_tail) = os.path.split(infile) merged_in_fname = infile_head + merge_type + \"_\" + infile_tail",
"# Right now, we can't really import this file... if __name__ == \"__main__\":",
"the following disclaimer. # * Redistributions in binary form must reproduce the above",
"= sys.argv[2] if (len(sys.argv) > 3): merge_type = sys.argv[3] if (merge_type not in",
"== \"min\"): merge_val = PerfDataPoint.MERGE_MIN elif (merge_type == \"max\"): merge_val = PerfDataPoint.MERGE_MAX else:",
"of Intel Corporation nor the names of its # contributors may be used",
"# def main(): infile = None outfile = \"tmp_summary_output.dat\" merge_type = \"avg\" if",
"MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT",
"PerfDataSet import *; import PerfDataParser; ## # Script to read in input file,",
"<NAME> # \\version 1.02 import os import sys from PerfDataPoint import *; from",
"the names of its # contributors may be used to endorse or promote",
"following disclaimer in # the documentation and/or other materials provided with the #",
"retain the above copyright # notice, this list of conditions and the following",
"import *; import PerfDataParser; ## # Script to read in input file, and",
"# Copyright (C) 2013 Intel Corporation # All rights reserved. # # Redistribution",
"input file, and merge all data points with the # same key together.",
"\\\"tmp_summary_output.dat\\\" by default\" # [merge_type] is \\\"avg\\\" by default (can also be \\\"min\\\")\"",
"# are met: # # * Redistributions of source code must retain the",
"by default\" # [merge_type] is \\\"avg\\\" by default (can also be \\\"min\\\")\" #",
"names. (infile_head, infile_tail) = os.path.split(infile) merged_in_fname = infile_head + merge_type + \"_\" +",
"reserved. # # Redistribution and use in source and binary forms, with or",
"file %s\" % merged_out_fname if (merge_type == \"min\"): merge_val = PerfDataPoint.MERGE_MIN elif (merge_type",
"= sys.argv[3] if (merge_type not in { \"avg\", \"min\" }): merge_type = \"avg\"",
"# Redistribution and use in source and binary forms, with or without #",
"# HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL,",
"WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE",
"SHALL THE COPYRIGHT # HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,",
"merge_type=merge_val, compute_average=True) input_data.output_to_file(merged_out_fname) # Run if we aren't importing. # Right now, we",
"nor the names of its # contributors may be used to endorse or",
"is a required argument.\" # <outfile> is \\\"tmp_summary_output.dat\\\" by default\" # [merge_type] is",
"OF SUBSTITUTE GOODS OR SERVICES; LOSS # OF USE, DATA, OR PROFITS; OR",
"ARISING IN ANY # WAY OUT OF THE USE OF THIS SOFTWARE, EVEN",
"Corporation # All rights reserved. # # Redistribution and use in source and",
"OR BUSINESS INTERRUPTION) HOWEVER CAUSED # AND ON ANY THEORY OF LIABILITY, WHETHER",
"without # modification, are permitted provided that the following conditions # are met:",
"BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS # OF",
"OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED # AND ON ANY THEORY OF",
"is \\\"tmp_summary_output.dat\\\" by default\" print \" <merge_type> is \\\"avg\\\" by default (can be",
"binary forms, with or without # modification, are permitted provided that the following",
"of source code must retain the above copyright # notice, this list of",
"# \\brief [<i>Performance test script</i>]: Reads in a file of performance # data,",
"OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE #",
"<merge_type> is \\\"avg\\\" by default (can be \\\"min\\\")\" exit(0) if (len(sys.argv) > 2):",
"default (can also be \\\"min\\\")\" # def main(): infile = None outfile =",
"\"max\"): merge_val = PerfDataPoint.MERGE_MAX else: merge_val = PerfDataPoint.MERGE_SUM input_data = PerfDataParser.parse_data_file(infile, default_desc=merged_in_fname, merge_type=merge_val,",
"from this software without specific prior written permission. # # THIS SOFTWARE IS",
"same key together. # # Usage: <this script> <infile> [outfile] [merge_type] # <infile>",
"1.02 import os import sys from PerfDataPoint import *; from PerfDataSet import *;",
"OR SERVICES; LOSS # OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER",
"# notice, this list of conditions and the following disclaimer. # * Redistributions",
"%s\" % infile print \"# Output file: %s\" % outfile print \"# Merge",
"def main(): infile = None outfile = \"tmp_summary_output.dat\" merge_type = \"avg\" if (len(sys.argv)",
"OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR",
"# # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS #",
"EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. ## # \\file",
"promote products derived # from this software without specific prior written permission. #",
"USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH",
"= infile_head + merge_type + \"_\" + infile_tail (outfile_head, outfile_tail) = os.path.split(outfile) merged_out_fname",
"in { \"avg\", \"min\" }): merge_type = \"avg\" print \"# Input file: %s\"",
"the above copyright # notice, this list of conditions and the following disclaimer.",
"POSSIBILITY OF SUCH DAMAGE. ## # \\file perf_summarize_file.py # # \\brief [<i>Performance test",
"DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, # BUT NOT",
"TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS # OF USE, DATA, OR",
"<infile> is a required argument.\" print \" <outfile> is \\\"tmp_summary_output.dat\\\" by default\" print",
"+ \"_\" + infile_tail (outfile_head, outfile_tail) = os.path.split(outfile) merged_out_fname = outfile_head + merge_type",
"[outfile] [merge_type] # <infile> is a required argument.\" # <outfile> is \\\"tmp_summary_output.dat\\\" by",
"INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS",
"OF SUCH DAMAGE. ## # \\file perf_summarize_file.py # # \\brief [<i>Performance test script</i>]:",
"# # * Redistributions of source code must retain the above copyright #",
"print \" <infile> is a required argument.\" print \" <outfile> is \\\"tmp_summary_output.dat\\\" by",
"\"_\" + outfile_tail print \"Generating output file %s\" % merged_out_fname if (merge_type ==",
"USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED # AND ON ANY",
"permitted provided that the following conditions # are met: # # * Redistributions",
"\\brief [<i>Performance test script</i>]: Reads in a file of performance # data, and",
"aren't importing. # Right now, we can't really import this file... if __name__",
"merge_val = PerfDataPoint.MERGE_SUM input_data = PerfDataParser.parse_data_file(infile, default_desc=merged_in_fname, merge_type=merge_val, compute_average=True) input_data.output_to_file(merged_out_fname) # Run if",
"PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED # AND ON ANY THEORY OF LIABILITY,",
"written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND",
"disclaimer. # * Redistributions in binary form must reproduce the above copyright #",
"same key together. # # \\author <NAME> # \\version 1.02 import os import",
"# OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED # AND",
"print \"# Input file: %s\" % infile print \"# Output file: %s\" %",
"\"avg\" print \"# Input file: %s\" % infile print \"# Output file: %s\"",
"specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT",
"list of conditions and the following disclaimer in # the documentation and/or other",
"with the same key together. # # \\author <NAME> # \\version 1.02 import"
] |
[
"File to edit: utils.ipynb (unless otherwise specified). __all__ = ['load_config', 'config', 'load_yaml', 'default_yaml',",
"'load_yaml', 'default_yaml', 'dict_to_paras'] # Cell import pkg_resources import configparser import yaml # Cell",
"return load_config(default_config) else: print('loading default_config and '+ new_config) return load_config(pkg_resources.resource_filename('pybiotools4p','default.ini'),new_config) def load_yaml(*yamls): my_dict={}",
"def config(new_config=None): default_config=pkg_resources.resource_filename('pybiotools4p','default.ini') if None is new_config: print('loading default_config['+default_config+']') return load_config(default_config) else: print('loading",
"'default_yaml', 'dict_to_paras'] # Cell import pkg_resources import configparser import yaml # Cell def",
"'+ new_config) return load_config(pkg_resources.resource_filename('pybiotools4p','default.ini'),new_config) def load_yaml(*yamls): my_dict={} for y in yamls: with open(y,'r')",
"y in yamls: with open(y,'r') as yf: my_dict.update(yaml.load(yf)) return my_dict def default_yaml(new_yaml=None): default_config=pkg_resources.resource_filename('pybiotools4p','default.yaml')",
"default_config=pkg_resources.resource_filename('pybiotools4p','default.yaml') if None is new_yaml: print('loading default_config['+default_config+']') return load_yaml(default_config) else: print('loading default_config and",
"# Cell import pkg_resources import configparser import yaml # Cell def load_config(*configs): config",
"configparser import yaml # Cell def load_config(*configs): config = configparser.ConfigParser() config.read(configs) return config",
"default_config=pkg_resources.resource_filename('pybiotools4p','default.ini') if None is new_config: print('loading default_config['+default_config+']') return load_config(default_config) else: print('loading default_config and",
"'+ new_yaml) return load_yaml(pkg_resources.resource_filename('pybiotools4p','default.yaml'),new_yaml) def dict_to_paras(mydict): ''' using dict to store extension parameters",
"if None is new_config: print('loading default_config['+default_config+']') return load_config(default_config) else: print('loading default_config and '+",
"and '+ new_yaml) return load_yaml(pkg_resources.resource_filename('pybiotools4p','default.yaml'),new_yaml) def dict_to_paras(mydict): ''' using dict to store extension",
"config.read(configs) return config def config(new_config=None): default_config=pkg_resources.resource_filename('pybiotools4p','default.ini') if None is new_config: print('loading default_config['+default_config+']') return",
"# AUTOGENERATED! DO NOT EDIT! File to edit: utils.ipynb (unless otherwise specified). __all__",
"my_dict def default_yaml(new_yaml=None): default_config=pkg_resources.resource_filename('pybiotools4p','default.yaml') if None is new_yaml: print('loading default_config['+default_config+']') return load_yaml(default_config) else:",
"default_config['+default_config+']') return load_config(default_config) else: print('loading default_config and '+ new_config) return load_config(pkg_resources.resource_filename('pybiotools4p','default.ini'),new_config) def load_yaml(*yamls):",
"in yamls: with open(y,'r') as yf: my_dict.update(yaml.load(yf)) return my_dict def default_yaml(new_yaml=None): default_config=pkg_resources.resource_filename('pybiotools4p','default.yaml') if",
"is new_config: print('loading default_config['+default_config+']') return load_config(default_config) else: print('loading default_config and '+ new_config) return",
"__all__ = ['load_config', 'config', 'load_yaml', 'default_yaml', 'dict_to_paras'] # Cell import pkg_resources import configparser",
"print('loading default_config and '+ new_yaml) return load_yaml(pkg_resources.resource_filename('pybiotools4p','default.yaml'),new_yaml) def dict_to_paras(mydict): ''' using dict to",
"'config', 'load_yaml', 'default_yaml', 'dict_to_paras'] # Cell import pkg_resources import configparser import yaml #",
"yamls: with open(y,'r') as yf: my_dict.update(yaml.load(yf)) return my_dict def default_yaml(new_yaml=None): default_config=pkg_resources.resource_filename('pybiotools4p','default.yaml') if None",
"# Cell def load_config(*configs): config = configparser.ConfigParser() config.read(configs) return config def config(new_config=None): default_config=pkg_resources.resource_filename('pybiotools4p','default.ini')",
"return load_yaml(default_config) else: print('loading default_config and '+ new_yaml) return load_yaml(pkg_resources.resource_filename('pybiotools4p','default.yaml'),new_yaml) def dict_to_paras(mydict): '''",
"otherwise specified). __all__ = ['load_config', 'config', 'load_yaml', 'default_yaml', 'dict_to_paras'] # Cell import pkg_resources",
"configparser.ConfigParser() config.read(configs) return config def config(new_config=None): default_config=pkg_resources.resource_filename('pybiotools4p','default.ini') if None is new_config: print('loading default_config['+default_config+']')",
"new_config) return load_config(pkg_resources.resource_filename('pybiotools4p','default.ini'),new_config) def load_yaml(*yamls): my_dict={} for y in yamls: with open(y,'r') as",
"load_yaml(*yamls): my_dict={} for y in yamls: with open(y,'r') as yf: my_dict.update(yaml.load(yf)) return my_dict",
"print('loading default_config['+default_config+']') return load_yaml(default_config) else: print('loading default_config and '+ new_yaml) return load_yaml(pkg_resources.resource_filename('pybiotools4p','default.yaml'),new_yaml) def",
"else: print('loading default_config and '+ new_config) return load_config(pkg_resources.resource_filename('pybiotools4p','default.ini'),new_config) def load_yaml(*yamls): my_dict={} for y",
"DO NOT EDIT! File to edit: utils.ipynb (unless otherwise specified). __all__ = ['load_config',",
"import configparser import yaml # Cell def load_config(*configs): config = configparser.ConfigParser() config.read(configs) return",
"load_config(*configs): config = configparser.ConfigParser() config.read(configs) return config def config(new_config=None): default_config=pkg_resources.resource_filename('pybiotools4p','default.ini') if None is",
"default_yaml(new_yaml=None): default_config=pkg_resources.resource_filename('pybiotools4p','default.yaml') if None is new_yaml: print('loading default_config['+default_config+']') return load_yaml(default_config) else: print('loading default_config",
"new_config: print('loading default_config['+default_config+']') return load_config(default_config) else: print('loading default_config and '+ new_config) return load_config(pkg_resources.resource_filename('pybiotools4p','default.ini'),new_config)",
"= ['load_config', 'config', 'load_yaml', 'default_yaml', 'dict_to_paras'] # Cell import pkg_resources import configparser import",
"to store extension parameters ''' return ' '.join([f'{i} {mydict[i]}' for i in mydict.keys()])",
"open(y,'r') as yf: my_dict.update(yaml.load(yf)) return my_dict def default_yaml(new_yaml=None): default_config=pkg_resources.resource_filename('pybiotools4p','default.yaml') if None is new_yaml:",
"new_yaml: print('loading default_config['+default_config+']') return load_yaml(default_config) else: print('loading default_config and '+ new_yaml) return load_yaml(pkg_resources.resource_filename('pybiotools4p','default.yaml'),new_yaml)",
"config = configparser.ConfigParser() config.read(configs) return config def config(new_config=None): default_config=pkg_resources.resource_filename('pybiotools4p','default.ini') if None is new_config:",
"return load_yaml(pkg_resources.resource_filename('pybiotools4p','default.yaml'),new_yaml) def dict_to_paras(mydict): ''' using dict to store extension parameters ''' return",
"else: print('loading default_config and '+ new_yaml) return load_yaml(pkg_resources.resource_filename('pybiotools4p','default.yaml'),new_yaml) def dict_to_paras(mydict): ''' using dict",
"EDIT! File to edit: utils.ipynb (unless otherwise specified). __all__ = ['load_config', 'config', 'load_yaml',",
"config def config(new_config=None): default_config=pkg_resources.resource_filename('pybiotools4p','default.ini') if None is new_config: print('loading default_config['+default_config+']') return load_config(default_config) else:",
"as yf: my_dict.update(yaml.load(yf)) return my_dict def default_yaml(new_yaml=None): default_config=pkg_resources.resource_filename('pybiotools4p','default.yaml') if None is new_yaml: print('loading",
"['load_config', 'config', 'load_yaml', 'default_yaml', 'dict_to_paras'] # Cell import pkg_resources import configparser import yaml",
"my_dict={} for y in yamls: with open(y,'r') as yf: my_dict.update(yaml.load(yf)) return my_dict def",
"to edit: utils.ipynb (unless otherwise specified). __all__ = ['load_config', 'config', 'load_yaml', 'default_yaml', 'dict_to_paras']",
"import pkg_resources import configparser import yaml # Cell def load_config(*configs): config = configparser.ConfigParser()",
"print('loading default_config['+default_config+']') return load_config(default_config) else: print('loading default_config and '+ new_config) return load_config(pkg_resources.resource_filename('pybiotools4p','default.ini'),new_config) def",
"import yaml # Cell def load_config(*configs): config = configparser.ConfigParser() config.read(configs) return config def",
"for y in yamls: with open(y,'r') as yf: my_dict.update(yaml.load(yf)) return my_dict def default_yaml(new_yaml=None):",
"'dict_to_paras'] # Cell import pkg_resources import configparser import yaml # Cell def load_config(*configs):",
"dict_to_paras(mydict): ''' using dict to store extension parameters ''' return ' '.join([f'{i} {mydict[i]}'",
"new_yaml) return load_yaml(pkg_resources.resource_filename('pybiotools4p','default.yaml'),new_yaml) def dict_to_paras(mydict): ''' using dict to store extension parameters '''",
"= configparser.ConfigParser() config.read(configs) return config def config(new_config=None): default_config=pkg_resources.resource_filename('pybiotools4p','default.ini') if None is new_config: print('loading",
"edit: utils.ipynb (unless otherwise specified). __all__ = ['load_config', 'config', 'load_yaml', 'default_yaml', 'dict_to_paras'] #",
"NOT EDIT! File to edit: utils.ipynb (unless otherwise specified). __all__ = ['load_config', 'config',",
"if None is new_yaml: print('loading default_config['+default_config+']') return load_yaml(default_config) else: print('loading default_config and '+",
"default_config and '+ new_yaml) return load_yaml(pkg_resources.resource_filename('pybiotools4p','default.yaml'),new_yaml) def dict_to_paras(mydict): ''' using dict to store",
"default_config['+default_config+']') return load_yaml(default_config) else: print('loading default_config and '+ new_yaml) return load_yaml(pkg_resources.resource_filename('pybiotools4p','default.yaml'),new_yaml) def dict_to_paras(mydict):",
"def default_yaml(new_yaml=None): default_config=pkg_resources.resource_filename('pybiotools4p','default.yaml') if None is new_yaml: print('loading default_config['+default_config+']') return load_yaml(default_config) else: print('loading",
"specified). __all__ = ['load_config', 'config', 'load_yaml', 'default_yaml', 'dict_to_paras'] # Cell import pkg_resources import",
"load_config(pkg_resources.resource_filename('pybiotools4p','default.ini'),new_config) def load_yaml(*yamls): my_dict={} for y in yamls: with open(y,'r') as yf: my_dict.update(yaml.load(yf))",
"Cell import pkg_resources import configparser import yaml # Cell def load_config(*configs): config =",
"return my_dict def default_yaml(new_yaml=None): default_config=pkg_resources.resource_filename('pybiotools4p','default.yaml') if None is new_yaml: print('loading default_config['+default_config+']') return load_yaml(default_config)",
"''' using dict to store extension parameters ''' return ' '.join([f'{i} {mydict[i]}' for",
"def load_yaml(*yamls): my_dict={} for y in yamls: with open(y,'r') as yf: my_dict.update(yaml.load(yf)) return",
"Cell def load_config(*configs): config = configparser.ConfigParser() config.read(configs) return config def config(new_config=None): default_config=pkg_resources.resource_filename('pybiotools4p','default.ini') if",
"load_yaml(default_config) else: print('loading default_config and '+ new_yaml) return load_yaml(pkg_resources.resource_filename('pybiotools4p','default.yaml'),new_yaml) def dict_to_paras(mydict): ''' using",
"using dict to store extension parameters ''' return ' '.join([f'{i} {mydict[i]}' for i",
"my_dict.update(yaml.load(yf)) return my_dict def default_yaml(new_yaml=None): default_config=pkg_resources.resource_filename('pybiotools4p','default.yaml') if None is new_yaml: print('loading default_config['+default_config+']') return",
"return config def config(new_config=None): default_config=pkg_resources.resource_filename('pybiotools4p','default.ini') if None is new_config: print('loading default_config['+default_config+']') return load_config(default_config)",
"return load_config(pkg_resources.resource_filename('pybiotools4p','default.ini'),new_config) def load_yaml(*yamls): my_dict={} for y in yamls: with open(y,'r') as yf:",
"None is new_config: print('loading default_config['+default_config+']') return load_config(default_config) else: print('loading default_config and '+ new_config)",
"yf: my_dict.update(yaml.load(yf)) return my_dict def default_yaml(new_yaml=None): default_config=pkg_resources.resource_filename('pybiotools4p','default.yaml') if None is new_yaml: print('loading default_config['+default_config+']')",
"yaml # Cell def load_config(*configs): config = configparser.ConfigParser() config.read(configs) return config def config(new_config=None):",
"def load_config(*configs): config = configparser.ConfigParser() config.read(configs) return config def config(new_config=None): default_config=pkg_resources.resource_filename('pybiotools4p','default.ini') if None",
"pkg_resources import configparser import yaml # Cell def load_config(*configs): config = configparser.ConfigParser() config.read(configs)",
"with open(y,'r') as yf: my_dict.update(yaml.load(yf)) return my_dict def default_yaml(new_yaml=None): default_config=pkg_resources.resource_filename('pybiotools4p','default.yaml') if None is",
"is new_yaml: print('loading default_config['+default_config+']') return load_yaml(default_config) else: print('loading default_config and '+ new_yaml) return",
"print('loading default_config and '+ new_config) return load_config(pkg_resources.resource_filename('pybiotools4p','default.ini'),new_config) def load_yaml(*yamls): my_dict={} for y in",
"dict to store extension parameters ''' return ' '.join([f'{i} {mydict[i]}' for i in",
"load_yaml(pkg_resources.resource_filename('pybiotools4p','default.yaml'),new_yaml) def dict_to_paras(mydict): ''' using dict to store extension parameters ''' return '",
"AUTOGENERATED! DO NOT EDIT! File to edit: utils.ipynb (unless otherwise specified). __all__ =",
"default_config and '+ new_config) return load_config(pkg_resources.resource_filename('pybiotools4p','default.ini'),new_config) def load_yaml(*yamls): my_dict={} for y in yamls:",
"(unless otherwise specified). __all__ = ['load_config', 'config', 'load_yaml', 'default_yaml', 'dict_to_paras'] # Cell import",
"def dict_to_paras(mydict): ''' using dict to store extension parameters ''' return ' '.join([f'{i}",
"load_config(default_config) else: print('loading default_config and '+ new_config) return load_config(pkg_resources.resource_filename('pybiotools4p','default.ini'),new_config) def load_yaml(*yamls): my_dict={} for",
"config(new_config=None): default_config=pkg_resources.resource_filename('pybiotools4p','default.ini') if None is new_config: print('loading default_config['+default_config+']') return load_config(default_config) else: print('loading default_config",
"and '+ new_config) return load_config(pkg_resources.resource_filename('pybiotools4p','default.ini'),new_config) def load_yaml(*yamls): my_dict={} for y in yamls: with",
"None is new_yaml: print('loading default_config['+default_config+']') return load_yaml(default_config) else: print('loading default_config and '+ new_yaml)",
"utils.ipynb (unless otherwise specified). __all__ = ['load_config', 'config', 'load_yaml', 'default_yaml', 'dict_to_paras'] # Cell"
] |
[
"# in the list or queryset annotated = [(item.pk, item) for item in",
"settings.MEDIA_URL = MEDIA_URL def tearDown(self): settings.MEDIA_ROOT = self.media_root settings.MEDIA_URL = self.media_url def _sort_by_pk(self,",
"= 'http://www.youtube.com/watch?v=nda_OSWeyn8' # django providers (DjangoProvider and DjangoDatebasedProvider) category_url = 'http://example.com/testapp/category/1/' blog_url =",
"providers (StoredProvider) flickr_url = 'http://www.flickr.com/photos/neilkrug/2554073003/' youtube_url = 'http://www.youtube.com/watch?v=nda_OSWeyn8' # django providers (DjangoProvider and",
"flickr_url = 'http://www.flickr.com/photos/neilkrug/2554073003/' youtube_url = 'http://www.youtube.com/watch?v=nda_OSWeyn8' # django providers (DjangoProvider and DjangoDatebasedProvider) category_url",
"blog_url = 'http://example.com/testapp/blog/2010/may/01/entry-1/' rich_url = 'http://example.com/testapp/rich/rich-one/' category_embed = '<img src=\"http://example.com/media/images/breugel_babel2_800x661.jpg\" alt=\"Category 1\" ></img>'",
"'http://example.com/testapp/blog/2010/may/01/entry-1/' rich_url = 'http://example.com/testapp/rich/rich-one/' category_embed = '<img src=\"http://example.com/media/images/breugel_babel2_800x661.jpg\" alt=\"Category 1\" ></img>' def setUp(self):",
"providers and register the test-only provider oembed.autodiscover() # refresh the attribute-cached time the",
"from django.conf import settings from django.core.urlresolvers import reverse, NoReverseMatch from django.test import TestCase",
"self.media_root, self.media_url = settings.MEDIA_ROOT, settings.MEDIA_URL settings.MEDIA_ROOT = MEDIA_ROOT settings.MEDIA_URL = MEDIA_URL def tearDown(self):",
"items # in the list or queryset annotated = [(item.pk, item) for item",
"[(item.pk, item) for item in list_or_qs] annotated.sort() return map(lambda item_tuple: item_tuple[1], annotated) def",
"import OEmbedResource from oembed.tests.settings import MEDIA_ROOT, MEDIA_URL class BaseOEmbedTestCase(TestCase): fixtures = ['oembed_testdata.json'] urls",
"providers (DjangoProvider and DjangoDatebasedProvider) category_url = 'http://example.com/testapp/category/1/' blog_url = 'http://example.com/testapp/blog/2010/may/01/entry-1/' rich_url = 'http://example.com/testapp/rich/rich-one/'",
"oembed.tests.settings import MEDIA_ROOT, MEDIA_URL class BaseOEmbedTestCase(TestCase): fixtures = ['oembed_testdata.json'] urls = 'oembed.tests.urls' #",
"(DjangoProvider and DjangoDatebasedProvider) category_url = 'http://example.com/testapp/category/1/' blog_url = 'http://example.com/testapp/blog/2010/may/01/entry-1/' rich_url = 'http://example.com/testapp/rich/rich-one/' category_embed",
"import oembed from oembed.providers import BaseProvider from oembed.resources import OEmbedResource from oembed.tests.settings import",
"oembed.resources import OEmbedResource from oembed.tests.settings import MEDIA_ROOT, MEDIA_URL class BaseOEmbedTestCase(TestCase): fixtures = ['oembed_testdata.json']",
"fixtures = ['oembed_testdata.json'] urls = 'oembed.tests.urls' # third party providers (StoredProvider) flickr_url =",
"from oembed.resources import OEmbedResource from oembed.tests.settings import MEDIA_ROOT, MEDIA_URL class BaseOEmbedTestCase(TestCase): fixtures =",
"['oembed_testdata.json'] urls = 'oembed.tests.urls' # third party providers (StoredProvider) flickr_url = 'http://www.flickr.com/photos/neilkrug/2554073003/' youtube_url",
"from oembed.tests.settings import MEDIA_ROOT, MEDIA_URL class BaseOEmbedTestCase(TestCase): fixtures = ['oembed_testdata.json'] urls = 'oembed.tests.urls'",
"\"Set up test environment\" # load up all the providers and register the",
"up all the providers and register the test-only provider oembed.autodiscover() # refresh the",
"oembed.providers import BaseProvider from oembed.resources import OEmbedResource from oembed.tests.settings import MEDIA_ROOT, MEDIA_URL class",
"undecorate using the pk of the items # in the list or queryset",
"<reponame>ericholscher/djangoembed<filename>oembed/tests/tests/base.py import simplejson from django.conf import settings from django.core.urlresolvers import reverse, NoReverseMatch from",
"= '<img src=\"http://example.com/media/images/breugel_babel2_800x661.jpg\" alt=\"Category 1\" ></img>' def setUp(self): \"Set up test environment\" #",
"test-only provider oembed.autodiscover() # refresh the attribute-cached time the db providers were last",
"self.media_url = settings.MEDIA_ROOT, settings.MEDIA_URL settings.MEDIA_ROOT = MEDIA_ROOT settings.MEDIA_URL = MEDIA_URL def tearDown(self): settings.MEDIA_ROOT",
"settings.MEDIA_ROOT = self.media_root settings.MEDIA_URL = self.media_url def _sort_by_pk(self, list_or_qs): # decorate, sort, undecorate",
"or queryset a is the same as list or queryset b return self.assertEqual(self._sort_by_pk(a),",
"settings.MEDIA_URL = self.media_url def _sort_by_pk(self, list_or_qs): # decorate, sort, undecorate using the pk",
"# django providers (DjangoProvider and DjangoDatebasedProvider) category_url = 'http://example.com/testapp/category/1/' blog_url = 'http://example.com/testapp/blog/2010/may/01/entry-1/' rich_url",
"decorate, sort, undecorate using the pk of the items # in the list",
"item_tuple[1], annotated) def assertQuerysetEqual(self, a, b): # assert list or queryset a is",
"self.media_url def _sort_by_pk(self, list_or_qs): # decorate, sort, undecorate using the pk of the",
"class BaseOEmbedTestCase(TestCase): fixtures = ['oembed_testdata.json'] urls = 'oembed.tests.urls' # third party providers (StoredProvider)",
"list_or_qs): # decorate, sort, undecorate using the pk of the items # in",
"pk of the items # in the list or queryset annotated = [(item.pk,",
"# assert list or queryset a is the same as list or queryset",
"# refresh the attribute-cached time the db providers were last updated oembed.site._db_updated =",
"or queryset annotated = [(item.pk, item) for item in list_or_qs] annotated.sort() return map(lambda",
"return map(lambda item_tuple: item_tuple[1], annotated) def assertQuerysetEqual(self, a, b): # assert list or",
"annotated) def assertQuerysetEqual(self, a, b): # assert list or queryset a is the",
"of the items # in the list or queryset annotated = [(item.pk, item)",
"db providers were last updated oembed.site._db_updated = None self.media_root, self.media_url = settings.MEDIA_ROOT, settings.MEDIA_URL",
"item in list_or_qs] annotated.sort() return map(lambda item_tuple: item_tuple[1], annotated) def assertQuerysetEqual(self, a, b):",
"import reverse, NoReverseMatch from django.test import TestCase import oembed from oembed.providers import BaseProvider",
"def tearDown(self): settings.MEDIA_ROOT = self.media_root settings.MEDIA_URL = self.media_url def _sort_by_pk(self, list_or_qs): # decorate,",
"the providers and register the test-only provider oembed.autodiscover() # refresh the attribute-cached time",
"urls = 'oembed.tests.urls' # third party providers (StoredProvider) flickr_url = 'http://www.flickr.com/photos/neilkrug/2554073003/' youtube_url =",
"settings.MEDIA_ROOT = MEDIA_ROOT settings.MEDIA_URL = MEDIA_URL def tearDown(self): settings.MEDIA_ROOT = self.media_root settings.MEDIA_URL =",
"'<img src=\"http://example.com/media/images/breugel_babel2_800x661.jpg\" alt=\"Category 1\" ></img>' def setUp(self): \"Set up test environment\" # load",
"django providers (DjangoProvider and DjangoDatebasedProvider) category_url = 'http://example.com/testapp/category/1/' blog_url = 'http://example.com/testapp/blog/2010/may/01/entry-1/' rich_url =",
"in the list or queryset annotated = [(item.pk, item) for item in list_or_qs]",
"></img>' def setUp(self): \"Set up test environment\" # load up all the providers",
"'http://www.flickr.com/photos/neilkrug/2554073003/' youtube_url = 'http://www.youtube.com/watch?v=nda_OSWeyn8' # django providers (DjangoProvider and DjangoDatebasedProvider) category_url = 'http://example.com/testapp/category/1/'",
"list or queryset annotated = [(item.pk, item) for item in list_or_qs] annotated.sort() return",
"'http://example.com/testapp/rich/rich-one/' category_embed = '<img src=\"http://example.com/media/images/breugel_babel2_800x661.jpg\" alt=\"Category 1\" ></img>' def setUp(self): \"Set up test",
"DjangoDatebasedProvider) category_url = 'http://example.com/testapp/category/1/' blog_url = 'http://example.com/testapp/blog/2010/may/01/entry-1/' rich_url = 'http://example.com/testapp/rich/rich-one/' category_embed = '<img",
"updated oembed.site._db_updated = None self.media_root, self.media_url = settings.MEDIA_ROOT, settings.MEDIA_URL settings.MEDIA_ROOT = MEDIA_ROOT settings.MEDIA_URL",
"= self.media_url def _sort_by_pk(self, list_or_qs): # decorate, sort, undecorate using the pk of",
"time the db providers were last updated oembed.site._db_updated = None self.media_root, self.media_url =",
"django.core.urlresolvers import reverse, NoReverseMatch from django.test import TestCase import oembed from oembed.providers import",
"= MEDIA_URL def tearDown(self): settings.MEDIA_ROOT = self.media_root settings.MEDIA_URL = self.media_url def _sort_by_pk(self, list_or_qs):",
"b): # assert list or queryset a is the same as list or",
"MEDIA_ROOT, MEDIA_URL class BaseOEmbedTestCase(TestCase): fixtures = ['oembed_testdata.json'] urls = 'oembed.tests.urls' # third party",
"settings.MEDIA_ROOT, settings.MEDIA_URL settings.MEDIA_ROOT = MEDIA_ROOT settings.MEDIA_URL = MEDIA_URL def tearDown(self): settings.MEDIA_ROOT = self.media_root",
"all the providers and register the test-only provider oembed.autodiscover() # refresh the attribute-cached",
"OEmbedResource from oembed.tests.settings import MEDIA_ROOT, MEDIA_URL class BaseOEmbedTestCase(TestCase): fixtures = ['oembed_testdata.json'] urls =",
"BaseProvider from oembed.resources import OEmbedResource from oembed.tests.settings import MEDIA_ROOT, MEDIA_URL class BaseOEmbedTestCase(TestCase): fixtures",
"setUp(self): \"Set up test environment\" # load up all the providers and register",
"refresh the attribute-cached time the db providers were last updated oembed.site._db_updated = None",
"# load up all the providers and register the test-only provider oembed.autodiscover() #",
"the attribute-cached time the db providers were last updated oembed.site._db_updated = None self.media_root,",
"simplejson from django.conf import settings from django.core.urlresolvers import reverse, NoReverseMatch from django.test import",
"settings from django.core.urlresolvers import reverse, NoReverseMatch from django.test import TestCase import oembed from",
"# decorate, sort, undecorate using the pk of the items # in the",
"third party providers (StoredProvider) flickr_url = 'http://www.flickr.com/photos/neilkrug/2554073003/' youtube_url = 'http://www.youtube.com/watch?v=nda_OSWeyn8' # django providers",
"assertQuerysetEqual(self, a, b): # assert list or queryset a is the same as",
"alt=\"Category 1\" ></img>' def setUp(self): \"Set up test environment\" # load up all",
"reverse, NoReverseMatch from django.test import TestCase import oembed from oembed.providers import BaseProvider from",
"import settings from django.core.urlresolvers import reverse, NoReverseMatch from django.test import TestCase import oembed",
"map(lambda item_tuple: item_tuple[1], annotated) def assertQuerysetEqual(self, a, b): # assert list or queryset",
"up test environment\" # load up all the providers and register the test-only",
"oembed.site._db_updated = None self.media_root, self.media_url = settings.MEDIA_ROOT, settings.MEDIA_URL settings.MEDIA_ROOT = MEDIA_ROOT settings.MEDIA_URL =",
"_sort_by_pk(self, list_or_qs): # decorate, sort, undecorate using the pk of the items #",
"MEDIA_ROOT settings.MEDIA_URL = MEDIA_URL def tearDown(self): settings.MEDIA_ROOT = self.media_root settings.MEDIA_URL = self.media_url def",
"for item in list_or_qs] annotated.sort() return map(lambda item_tuple: item_tuple[1], annotated) def assertQuerysetEqual(self, a,",
"MEDIA_URL class BaseOEmbedTestCase(TestCase): fixtures = ['oembed_testdata.json'] urls = 'oembed.tests.urls' # third party providers",
"MEDIA_URL def tearDown(self): settings.MEDIA_ROOT = self.media_root settings.MEDIA_URL = self.media_url def _sort_by_pk(self, list_or_qs): #",
"annotated = [(item.pk, item) for item in list_or_qs] annotated.sort() return map(lambda item_tuple: item_tuple[1],",
"= self.media_root settings.MEDIA_URL = self.media_url def _sort_by_pk(self, list_or_qs): # decorate, sort, undecorate using",
"in list_or_qs] annotated.sort() return map(lambda item_tuple: item_tuple[1], annotated) def assertQuerysetEqual(self, a, b): #",
"the test-only provider oembed.autodiscover() # refresh the attribute-cached time the db providers were",
"= [(item.pk, item) for item in list_or_qs] annotated.sort() return map(lambda item_tuple: item_tuple[1], annotated)",
"= 'oembed.tests.urls' # third party providers (StoredProvider) flickr_url = 'http://www.flickr.com/photos/neilkrug/2554073003/' youtube_url = 'http://www.youtube.com/watch?v=nda_OSWeyn8'",
"a, b): # assert list or queryset a is the same as list",
"= 'http://www.flickr.com/photos/neilkrug/2554073003/' youtube_url = 'http://www.youtube.com/watch?v=nda_OSWeyn8' # django providers (DjangoProvider and DjangoDatebasedProvider) category_url =",
"oembed from oembed.providers import BaseProvider from oembed.resources import OEmbedResource from oembed.tests.settings import MEDIA_ROOT,",
"were last updated oembed.site._db_updated = None self.media_root, self.media_url = settings.MEDIA_ROOT, settings.MEDIA_URL settings.MEDIA_ROOT =",
"1\" ></img>' def setUp(self): \"Set up test environment\" # load up all the",
"providers were last updated oembed.site._db_updated = None self.media_root, self.media_url = settings.MEDIA_ROOT, settings.MEDIA_URL settings.MEDIA_ROOT",
"the list or queryset annotated = [(item.pk, item) for item in list_or_qs] annotated.sort()",
"import BaseProvider from oembed.resources import OEmbedResource from oembed.tests.settings import MEDIA_ROOT, MEDIA_URL class BaseOEmbedTestCase(TestCase):",
"queryset a is the same as list or queryset b return self.assertEqual(self._sort_by_pk(a), self._sort_by_pk(b))",
"from django.core.urlresolvers import reverse, NoReverseMatch from django.test import TestCase import oembed from oembed.providers",
"BaseOEmbedTestCase(TestCase): fixtures = ['oembed_testdata.json'] urls = 'oembed.tests.urls' # third party providers (StoredProvider) flickr_url",
"rich_url = 'http://example.com/testapp/rich/rich-one/' category_embed = '<img src=\"http://example.com/media/images/breugel_babel2_800x661.jpg\" alt=\"Category 1\" ></img>' def setUp(self): \"Set",
"= 'http://example.com/testapp/category/1/' blog_url = 'http://example.com/testapp/blog/2010/may/01/entry-1/' rich_url = 'http://example.com/testapp/rich/rich-one/' category_embed = '<img src=\"http://example.com/media/images/breugel_babel2_800x661.jpg\" alt=\"Category",
"last updated oembed.site._db_updated = None self.media_root, self.media_url = settings.MEDIA_ROOT, settings.MEDIA_URL settings.MEDIA_ROOT = MEDIA_ROOT",
"party providers (StoredProvider) flickr_url = 'http://www.flickr.com/photos/neilkrug/2554073003/' youtube_url = 'http://www.youtube.com/watch?v=nda_OSWeyn8' # django providers (DjangoProvider",
"django.conf import settings from django.core.urlresolvers import reverse, NoReverseMatch from django.test import TestCase import",
"list_or_qs] annotated.sort() return map(lambda item_tuple: item_tuple[1], annotated) def assertQuerysetEqual(self, a, b): # assert",
"def _sort_by_pk(self, list_or_qs): # decorate, sort, undecorate using the pk of the items",
"annotated.sort() return map(lambda item_tuple: item_tuple[1], annotated) def assertQuerysetEqual(self, a, b): # assert list",
"item) for item in list_or_qs] annotated.sort() return map(lambda item_tuple: item_tuple[1], annotated) def assertQuerysetEqual(self,",
"from oembed.providers import BaseProvider from oembed.resources import OEmbedResource from oembed.tests.settings import MEDIA_ROOT, MEDIA_URL",
"def assertQuerysetEqual(self, a, b): # assert list or queryset a is the same",
"= settings.MEDIA_ROOT, settings.MEDIA_URL settings.MEDIA_ROOT = MEDIA_ROOT settings.MEDIA_URL = MEDIA_URL def tearDown(self): settings.MEDIA_ROOT =",
"(StoredProvider) flickr_url = 'http://www.flickr.com/photos/neilkrug/2554073003/' youtube_url = 'http://www.youtube.com/watch?v=nda_OSWeyn8' # django providers (DjangoProvider and DjangoDatebasedProvider)",
"'oembed.tests.urls' # third party providers (StoredProvider) flickr_url = 'http://www.flickr.com/photos/neilkrug/2554073003/' youtube_url = 'http://www.youtube.com/watch?v=nda_OSWeyn8' #",
"TestCase import oembed from oembed.providers import BaseProvider from oembed.resources import OEmbedResource from oembed.tests.settings",
"youtube_url = 'http://www.youtube.com/watch?v=nda_OSWeyn8' # django providers (DjangoProvider and DjangoDatebasedProvider) category_url = 'http://example.com/testapp/category/1/' blog_url",
"None self.media_root, self.media_url = settings.MEDIA_ROOT, settings.MEDIA_URL settings.MEDIA_ROOT = MEDIA_ROOT settings.MEDIA_URL = MEDIA_URL def",
"import simplejson from django.conf import settings from django.core.urlresolvers import reverse, NoReverseMatch from django.test",
"the pk of the items # in the list or queryset annotated =",
"category_embed = '<img src=\"http://example.com/media/images/breugel_babel2_800x661.jpg\" alt=\"Category 1\" ></img>' def setUp(self): \"Set up test environment\"",
"= None self.media_root, self.media_url = settings.MEDIA_ROOT, settings.MEDIA_URL settings.MEDIA_ROOT = MEDIA_ROOT settings.MEDIA_URL = MEDIA_URL",
"= MEDIA_ROOT settings.MEDIA_URL = MEDIA_URL def tearDown(self): settings.MEDIA_ROOT = self.media_root settings.MEDIA_URL = self.media_url",
"NoReverseMatch from django.test import TestCase import oembed from oembed.providers import BaseProvider from oembed.resources",
"the items # in the list or queryset annotated = [(item.pk, item) for",
"category_url = 'http://example.com/testapp/category/1/' blog_url = 'http://example.com/testapp/blog/2010/may/01/entry-1/' rich_url = 'http://example.com/testapp/rich/rich-one/' category_embed = '<img src=\"http://example.com/media/images/breugel_babel2_800x661.jpg\"",
"assert list or queryset a is the same as list or queryset b",
"and register the test-only provider oembed.autodiscover() # refresh the attribute-cached time the db",
"src=\"http://example.com/media/images/breugel_babel2_800x661.jpg\" alt=\"Category 1\" ></img>' def setUp(self): \"Set up test environment\" # load up",
"environment\" # load up all the providers and register the test-only provider oembed.autodiscover()",
"attribute-cached time the db providers were last updated oembed.site._db_updated = None self.media_root, self.media_url",
"tearDown(self): settings.MEDIA_ROOT = self.media_root settings.MEDIA_URL = self.media_url def _sort_by_pk(self, list_or_qs): # decorate, sort,",
"load up all the providers and register the test-only provider oembed.autodiscover() # refresh",
"= 'http://example.com/testapp/blog/2010/may/01/entry-1/' rich_url = 'http://example.com/testapp/rich/rich-one/' category_embed = '<img src=\"http://example.com/media/images/breugel_babel2_800x661.jpg\" alt=\"Category 1\" ></img>' def",
"item_tuple: item_tuple[1], annotated) def assertQuerysetEqual(self, a, b): # assert list or queryset a",
"def setUp(self): \"Set up test environment\" # load up all the providers and",
"sort, undecorate using the pk of the items # in the list or",
"'http://example.com/testapp/category/1/' blog_url = 'http://example.com/testapp/blog/2010/may/01/entry-1/' rich_url = 'http://example.com/testapp/rich/rich-one/' category_embed = '<img src=\"http://example.com/media/images/breugel_babel2_800x661.jpg\" alt=\"Category 1\"",
"django.test import TestCase import oembed from oembed.providers import BaseProvider from oembed.resources import OEmbedResource",
"and DjangoDatebasedProvider) category_url = 'http://example.com/testapp/category/1/' blog_url = 'http://example.com/testapp/blog/2010/may/01/entry-1/' rich_url = 'http://example.com/testapp/rich/rich-one/' category_embed =",
"= 'http://example.com/testapp/rich/rich-one/' category_embed = '<img src=\"http://example.com/media/images/breugel_babel2_800x661.jpg\" alt=\"Category 1\" ></img>' def setUp(self): \"Set up",
"import MEDIA_ROOT, MEDIA_URL class BaseOEmbedTestCase(TestCase): fixtures = ['oembed_testdata.json'] urls = 'oembed.tests.urls' # third",
"test environment\" # load up all the providers and register the test-only provider",
"from django.test import TestCase import oembed from oembed.providers import BaseProvider from oembed.resources import",
"= ['oembed_testdata.json'] urls = 'oembed.tests.urls' # third party providers (StoredProvider) flickr_url = 'http://www.flickr.com/photos/neilkrug/2554073003/'",
"import TestCase import oembed from oembed.providers import BaseProvider from oembed.resources import OEmbedResource from",
"list or queryset a is the same as list or queryset b return",
"provider oembed.autodiscover() # refresh the attribute-cached time the db providers were last updated",
"oembed.autodiscover() # refresh the attribute-cached time the db providers were last updated oembed.site._db_updated",
"using the pk of the items # in the list or queryset annotated",
"# third party providers (StoredProvider) flickr_url = 'http://www.flickr.com/photos/neilkrug/2554073003/' youtube_url = 'http://www.youtube.com/watch?v=nda_OSWeyn8' # django",
"the db providers were last updated oembed.site._db_updated = None self.media_root, self.media_url = settings.MEDIA_ROOT,",
"queryset annotated = [(item.pk, item) for item in list_or_qs] annotated.sort() return map(lambda item_tuple:",
"'http://www.youtube.com/watch?v=nda_OSWeyn8' # django providers (DjangoProvider and DjangoDatebasedProvider) category_url = 'http://example.com/testapp/category/1/' blog_url = 'http://example.com/testapp/blog/2010/may/01/entry-1/'",
"register the test-only provider oembed.autodiscover() # refresh the attribute-cached time the db providers",
"self.media_root settings.MEDIA_URL = self.media_url def _sort_by_pk(self, list_or_qs): # decorate, sort, undecorate using the",
"settings.MEDIA_URL settings.MEDIA_ROOT = MEDIA_ROOT settings.MEDIA_URL = MEDIA_URL def tearDown(self): settings.MEDIA_ROOT = self.media_root settings.MEDIA_URL"
] |
[
"] # MODEL_SECTIONS required_headers = [ \"component_list\", \"node_conn_df\", \"sysinp_setup\", \"sysout_setup\" ] # -----------------------------------------------------------------------------",
"# ----------------------------------------------------------------------------- # Worksheet names / primary JSON keys # XL_WORKSHEET_NAMES required_model_worksheets =",
"'component_id', 'component_type', 'component_class', 'cost_fraction', 'node_type', 'node_cluster', 'operating_capacity', 'pos_x', 'pos_y' ] # MODEL_COMPONENT_HEADERS required_component_headers",
"\"damages_states_constructor\" ] # MODEL_CONNECTION_HEADERS required_col_names_conn = [ 'origin', 'destination', 'link_capacity', 'weight' ] #",
"Params lists and functions for validation testing of models and config files Validates",
"'output_setup', 'comp_type_dmg_algo', 'damage_state_def' ] # XL_COMPONENT_LIST_HEADERS required_col_names_clist = [ 'component_id', 'component_type', 'component_class', 'cost_fraction',",
"import Path # ----------------------------------------------------------------------------- # Paths SIRA_ROOT_DIR = Path(__file__).resolve().parent path_to_test_models = Path(SIRA_ROOT_DIR, \"tests\",",
"= [ 'origin', 'destination', 'link_capacity', 'weight' ] # ALGORITHM_DEFINITION_PARAMS required_col_names = [ 'is_piecewise',",
"keys # XL_WORKSHEET_NAMES required_model_worksheets = [ 'system_meta', 'component_list', 'component_connections', 'supply_setup', 'output_setup', 'comp_type_dmg_algo', 'damage_state_def'",
"[ 'component_id', 'component_type', 'component_class', 'cost_fraction', 'node_type', 'node_cluster', 'operating_capacity', 'pos_x', 'pos_y' ] # MODEL_COMPONENT_HEADERS",
"files based on rules \"\"\" from pathlib import Path # ----------------------------------------------------------------------------- # Paths",
"Path # ----------------------------------------------------------------------------- # Paths SIRA_ROOT_DIR = Path(__file__).resolve().parent path_to_test_models = Path(SIRA_ROOT_DIR, \"tests\", \"models\")",
"for validation testing of models and config files Validates model and config files",
"required_model_worksheets = [ 'system_meta', 'component_list', 'component_connections', 'supply_setup', 'output_setup', 'comp_type_dmg_algo', 'damage_state_def' ] # XL_COMPONENT_LIST_HEADERS",
"files Validates model and config files based on rules \"\"\" from pathlib import",
"Paths SIRA_ROOT_DIR = Path(__file__).resolve().parent path_to_test_models = Path(SIRA_ROOT_DIR, \"tests\", \"models\") # ----------------------------------------------------------------------------- # Worksheet",
"'supply_setup', 'output_setup', 'comp_type_dmg_algo', 'damage_state_def' ] # XL_COMPONENT_LIST_HEADERS required_col_names_clist = [ 'component_id', 'component_type', 'component_class',",
"required_component_headers = [ \"component_type\", \"component_class\", \"cost_fraction\", \"node_type\", \"node_cluster\", \"operating_capacity\", \"pos_x\", \"pos_y\", \"damages_states_constructor\" ]",
"from pathlib import Path # ----------------------------------------------------------------------------- # Paths SIRA_ROOT_DIR = Path(__file__).resolve().parent path_to_test_models =",
"names / primary JSON keys # XL_WORKSHEET_NAMES required_model_worksheets = [ 'system_meta', 'component_list', 'component_connections',",
"\"cost_fraction\", \"node_type\", \"node_cluster\", \"operating_capacity\", \"pos_x\", \"pos_y\", \"damages_states_constructor\" ] # MODEL_CONNECTION_HEADERS required_col_names_conn = [",
"# XL_COMPONENT_LIST_HEADERS required_col_names_clist = [ 'component_id', 'component_type', 'component_class', 'cost_fraction', 'node_type', 'node_cluster', 'operating_capacity', 'pos_x',",
"on rules \"\"\" from pathlib import Path # ----------------------------------------------------------------------------- # Paths SIRA_ROOT_DIR =",
"'component_class', 'cost_fraction', 'node_type', 'node_cluster', 'operating_capacity', 'pos_x', 'pos_y' ] # MODEL_COMPONENT_HEADERS required_component_headers = [",
"'node_cluster', 'operating_capacity', 'pos_x', 'pos_y' ] # MODEL_COMPONENT_HEADERS required_component_headers = [ \"component_type\", \"component_class\", \"cost_fraction\",",
"and config files Validates model and config files based on rules \"\"\" from",
"----------------------------------------------------------------------------- # Paths SIRA_ROOT_DIR = Path(__file__).resolve().parent path_to_test_models = Path(SIRA_ROOT_DIR, \"tests\", \"models\") # -----------------------------------------------------------------------------",
"XL_WORKSHEET_NAMES required_model_worksheets = [ 'system_meta', 'component_list', 'component_connections', 'supply_setup', 'output_setup', 'comp_type_dmg_algo', 'damage_state_def' ] #",
"[ 'system_meta', 'component_list', 'component_connections', 'supply_setup', 'output_setup', 'comp_type_dmg_algo', 'damage_state_def' ] # XL_COMPONENT_LIST_HEADERS required_col_names_clist =",
"models and config files Validates model and config files based on rules \"\"\"",
"# XL_WORKSHEET_NAMES required_model_worksheets = [ 'system_meta', 'component_list', 'component_connections', 'supply_setup', 'output_setup', 'comp_type_dmg_algo', 'damage_state_def' ]",
"rules \"\"\" from pathlib import Path # ----------------------------------------------------------------------------- # Paths SIRA_ROOT_DIR = Path(__file__).resolve().parent",
"functions for validation testing of models and config files Validates model and config",
"'component_connections', 'supply_setup', 'output_setup', 'comp_type_dmg_algo', 'damage_state_def' ] # XL_COMPONENT_LIST_HEADERS required_col_names_clist = [ 'component_id', 'component_type',",
"'node_type', 'node_cluster', 'operating_capacity', 'pos_x', 'pos_y' ] # MODEL_COMPONENT_HEADERS required_component_headers = [ \"component_type\", \"component_class\",",
"# Paths SIRA_ROOT_DIR = Path(__file__).resolve().parent path_to_test_models = Path(SIRA_ROOT_DIR, \"tests\", \"models\") # ----------------------------------------------------------------------------- #",
"'system_meta', 'component_list', 'component_connections', 'supply_setup', 'output_setup', 'comp_type_dmg_algo', 'damage_state_def' ] # XL_COMPONENT_LIST_HEADERS required_col_names_clist = [",
"= [ 'system_meta', 'component_list', 'component_connections', 'supply_setup', 'output_setup', 'comp_type_dmg_algo', 'damage_state_def' ] # XL_COMPONENT_LIST_HEADERS required_col_names_clist",
"[ 'is_piecewise', 'damage_function', 'damage_ratio', 'functionality', 'recovery_function', 'recovery_param1', 'recovery_param2' ] # MODEL_SECTIONS required_headers =",
"SIRA_ROOT_DIR = Path(__file__).resolve().parent path_to_test_models = Path(SIRA_ROOT_DIR, \"tests\", \"models\") # ----------------------------------------------------------------------------- # Worksheet names",
"] # MODEL_CONNECTION_HEADERS required_col_names_conn = [ 'origin', 'destination', 'link_capacity', 'weight' ] # ALGORITHM_DEFINITION_PARAMS",
"'operating_capacity', 'pos_x', 'pos_y' ] # MODEL_COMPONENT_HEADERS required_component_headers = [ \"component_type\", \"component_class\", \"cost_fraction\", \"node_type\",",
"# MODEL_COMPONENT_HEADERS required_component_headers = [ \"component_type\", \"component_class\", \"cost_fraction\", \"node_type\", \"node_cluster\", \"operating_capacity\", \"pos_x\", \"pos_y\",",
"MODEL_COMPONENT_HEADERS required_component_headers = [ \"component_type\", \"component_class\", \"cost_fraction\", \"node_type\", \"node_cluster\", \"operating_capacity\", \"pos_x\", \"pos_y\", \"damages_states_constructor\"",
"primary JSON keys # XL_WORKSHEET_NAMES required_model_worksheets = [ 'system_meta', 'component_list', 'component_connections', 'supply_setup', 'output_setup',",
"Validates model and config files based on rules \"\"\" from pathlib import Path",
"----------------------------------------------------------------------------- # Worksheet names / primary JSON keys # XL_WORKSHEET_NAMES required_model_worksheets = [",
"validation testing of models and config files Validates model and config files based",
"] # MODEL_COMPONENT_HEADERS required_component_headers = [ \"component_type\", \"component_class\", \"cost_fraction\", \"node_type\", \"node_cluster\", \"operating_capacity\", \"pos_x\",",
"] # XL_COMPONENT_LIST_HEADERS required_col_names_clist = [ 'component_id', 'component_type', 'component_class', 'cost_fraction', 'node_type', 'node_cluster', 'operating_capacity',",
"# MODEL_CONNECTION_HEADERS required_col_names_conn = [ 'origin', 'destination', 'link_capacity', 'weight' ] # ALGORITHM_DEFINITION_PARAMS required_col_names",
"and config files based on rules \"\"\" from pathlib import Path # -----------------------------------------------------------------------------",
"= [ 'component_id', 'component_type', 'component_class', 'cost_fraction', 'node_type', 'node_cluster', 'operating_capacity', 'pos_x', 'pos_y' ] #",
"'comp_type_dmg_algo', 'damage_state_def' ] # XL_COMPONENT_LIST_HEADERS required_col_names_clist = [ 'component_id', 'component_type', 'component_class', 'cost_fraction', 'node_type',",
"Path(__file__).resolve().parent path_to_test_models = Path(SIRA_ROOT_DIR, \"tests\", \"models\") # ----------------------------------------------------------------------------- # Worksheet names / primary",
"= [ 'is_piecewise', 'damage_function', 'damage_ratio', 'functionality', 'recovery_function', 'recovery_param1', 'recovery_param2' ] # MODEL_SECTIONS required_headers",
"XL_COMPONENT_LIST_HEADERS required_col_names_clist = [ 'component_id', 'component_type', 'component_class', 'cost_fraction', 'node_type', 'node_cluster', 'operating_capacity', 'pos_x', 'pos_y'",
"based on rules \"\"\" from pathlib import Path # ----------------------------------------------------------------------------- # Paths SIRA_ROOT_DIR",
"Worksheet names / primary JSON keys # XL_WORKSHEET_NAMES required_model_worksheets = [ 'system_meta', 'component_list',",
"] # ALGORITHM_DEFINITION_PARAMS required_col_names = [ 'is_piecewise', 'damage_function', 'damage_ratio', 'functionality', 'recovery_function', 'recovery_param1', 'recovery_param2'",
"config files Validates model and config files based on rules \"\"\" from pathlib",
"lists and functions for validation testing of models and config files Validates model",
"\"\"\" Params lists and functions for validation testing of models and config files",
"\"pos_y\", \"damages_states_constructor\" ] # MODEL_CONNECTION_HEADERS required_col_names_conn = [ 'origin', 'destination', 'link_capacity', 'weight' ]",
"pathlib import Path # ----------------------------------------------------------------------------- # Paths SIRA_ROOT_DIR = Path(__file__).resolve().parent path_to_test_models = Path(SIRA_ROOT_DIR,",
"model and config files based on rules \"\"\" from pathlib import Path #",
"JSON keys # XL_WORKSHEET_NAMES required_model_worksheets = [ 'system_meta', 'component_list', 'component_connections', 'supply_setup', 'output_setup', 'comp_type_dmg_algo',",
"\"node_cluster\", \"operating_capacity\", \"pos_x\", \"pos_y\", \"damages_states_constructor\" ] # MODEL_CONNECTION_HEADERS required_col_names_conn = [ 'origin', 'destination',",
"'weight' ] # ALGORITHM_DEFINITION_PARAMS required_col_names = [ 'is_piecewise', 'damage_function', 'damage_ratio', 'functionality', 'recovery_function', 'recovery_param1',",
"'pos_x', 'pos_y' ] # MODEL_COMPONENT_HEADERS required_component_headers = [ \"component_type\", \"component_class\", \"cost_fraction\", \"node_type\", \"node_cluster\",",
"'component_list', 'component_connections', 'supply_setup', 'output_setup', 'comp_type_dmg_algo', 'damage_state_def' ] # XL_COMPONENT_LIST_HEADERS required_col_names_clist = [ 'component_id',",
"[ \"component_type\", \"component_class\", \"cost_fraction\", \"node_type\", \"node_cluster\", \"operating_capacity\", \"pos_x\", \"pos_y\", \"damages_states_constructor\" ] # MODEL_CONNECTION_HEADERS",
"<filename>tests/validation.py \"\"\" Params lists and functions for validation testing of models and config",
"\"models\") # ----------------------------------------------------------------------------- # Worksheet names / primary JSON keys # XL_WORKSHEET_NAMES required_model_worksheets",
"= Path(__file__).resolve().parent path_to_test_models = Path(SIRA_ROOT_DIR, \"tests\", \"models\") # ----------------------------------------------------------------------------- # Worksheet names /",
"\"tests\", \"models\") # ----------------------------------------------------------------------------- # Worksheet names / primary JSON keys # XL_WORKSHEET_NAMES",
"of models and config files Validates model and config files based on rules",
"\"\"\" from pathlib import Path # ----------------------------------------------------------------------------- # Paths SIRA_ROOT_DIR = Path(__file__).resolve().parent path_to_test_models",
"'pos_y' ] # MODEL_COMPONENT_HEADERS required_component_headers = [ \"component_type\", \"component_class\", \"cost_fraction\", \"node_type\", \"node_cluster\", \"operating_capacity\",",
"# Worksheet names / primary JSON keys # XL_WORKSHEET_NAMES required_model_worksheets = [ 'system_meta',",
"# ----------------------------------------------------------------------------- # Paths SIRA_ROOT_DIR = Path(__file__).resolve().parent path_to_test_models = Path(SIRA_ROOT_DIR, \"tests\", \"models\") #",
"\"component_class\", \"cost_fraction\", \"node_type\", \"node_cluster\", \"operating_capacity\", \"pos_x\", \"pos_y\", \"damages_states_constructor\" ] # MODEL_CONNECTION_HEADERS required_col_names_conn =",
"/ primary JSON keys # XL_WORKSHEET_NAMES required_model_worksheets = [ 'system_meta', 'component_list', 'component_connections', 'supply_setup',",
"testing of models and config files Validates model and config files based on",
"path_to_test_models = Path(SIRA_ROOT_DIR, \"tests\", \"models\") # ----------------------------------------------------------------------------- # Worksheet names / primary JSON",
"\"component_type\", \"component_class\", \"cost_fraction\", \"node_type\", \"node_cluster\", \"operating_capacity\", \"pos_x\", \"pos_y\", \"damages_states_constructor\" ] # MODEL_CONNECTION_HEADERS required_col_names_conn",
"\"node_type\", \"node_cluster\", \"operating_capacity\", \"pos_x\", \"pos_y\", \"damages_states_constructor\" ] # MODEL_CONNECTION_HEADERS required_col_names_conn = [ 'origin',",
"config files based on rules \"\"\" from pathlib import Path # ----------------------------------------------------------------------------- #",
"'recovery_function', 'recovery_param1', 'recovery_param2' ] # MODEL_SECTIONS required_headers = [ \"component_list\", \"node_conn_df\", \"sysinp_setup\", \"sysout_setup\"",
"'destination', 'link_capacity', 'weight' ] # ALGORITHM_DEFINITION_PARAMS required_col_names = [ 'is_piecewise', 'damage_function', 'damage_ratio', 'functionality',",
"'damage_state_def' ] # XL_COMPONENT_LIST_HEADERS required_col_names_clist = [ 'component_id', 'component_type', 'component_class', 'cost_fraction', 'node_type', 'node_cluster',",
"= [ \"component_type\", \"component_class\", \"cost_fraction\", \"node_type\", \"node_cluster\", \"operating_capacity\", \"pos_x\", \"pos_y\", \"damages_states_constructor\" ] #",
"'functionality', 'recovery_function', 'recovery_param1', 'recovery_param2' ] # MODEL_SECTIONS required_headers = [ \"component_list\", \"node_conn_df\", \"sysinp_setup\",",
"Path(SIRA_ROOT_DIR, \"tests\", \"models\") # ----------------------------------------------------------------------------- # Worksheet names / primary JSON keys #",
"'recovery_param1', 'recovery_param2' ] # MODEL_SECTIONS required_headers = [ \"component_list\", \"node_conn_df\", \"sysinp_setup\", \"sysout_setup\" ]",
"'recovery_param2' ] # MODEL_SECTIONS required_headers = [ \"component_list\", \"node_conn_df\", \"sysinp_setup\", \"sysout_setup\" ] #",
"'cost_fraction', 'node_type', 'node_cluster', 'operating_capacity', 'pos_x', 'pos_y' ] # MODEL_COMPONENT_HEADERS required_component_headers = [ \"component_type\",",
"'component_type', 'component_class', 'cost_fraction', 'node_type', 'node_cluster', 'operating_capacity', 'pos_x', 'pos_y' ] # MODEL_COMPONENT_HEADERS required_component_headers =",
"\"pos_x\", \"pos_y\", \"damages_states_constructor\" ] # MODEL_CONNECTION_HEADERS required_col_names_conn = [ 'origin', 'destination', 'link_capacity', 'weight'",
"'origin', 'destination', 'link_capacity', 'weight' ] # ALGORITHM_DEFINITION_PARAMS required_col_names = [ 'is_piecewise', 'damage_function', 'damage_ratio',",
"and functions for validation testing of models and config files Validates model and",
"MODEL_CONNECTION_HEADERS required_col_names_conn = [ 'origin', 'destination', 'link_capacity', 'weight' ] # ALGORITHM_DEFINITION_PARAMS required_col_names =",
"required_col_names = [ 'is_piecewise', 'damage_function', 'damage_ratio', 'functionality', 'recovery_function', 'recovery_param1', 'recovery_param2' ] # MODEL_SECTIONS",
"= Path(SIRA_ROOT_DIR, \"tests\", \"models\") # ----------------------------------------------------------------------------- # Worksheet names / primary JSON keys",
"required_col_names_conn = [ 'origin', 'destination', 'link_capacity', 'weight' ] # ALGORITHM_DEFINITION_PARAMS required_col_names = [",
"[ 'origin', 'destination', 'link_capacity', 'weight' ] # ALGORITHM_DEFINITION_PARAMS required_col_names = [ 'is_piecewise', 'damage_function',",
"\"operating_capacity\", \"pos_x\", \"pos_y\", \"damages_states_constructor\" ] # MODEL_CONNECTION_HEADERS required_col_names_conn = [ 'origin', 'destination', 'link_capacity',",
"'link_capacity', 'weight' ] # ALGORITHM_DEFINITION_PARAMS required_col_names = [ 'is_piecewise', 'damage_function', 'damage_ratio', 'functionality', 'recovery_function',",
"'is_piecewise', 'damage_function', 'damage_ratio', 'functionality', 'recovery_function', 'recovery_param1', 'recovery_param2' ] # MODEL_SECTIONS required_headers = [",
"# ALGORITHM_DEFINITION_PARAMS required_col_names = [ 'is_piecewise', 'damage_function', 'damage_ratio', 'functionality', 'recovery_function', 'recovery_param1', 'recovery_param2' ]",
"required_col_names_clist = [ 'component_id', 'component_type', 'component_class', 'cost_fraction', 'node_type', 'node_cluster', 'operating_capacity', 'pos_x', 'pos_y' ]",
"'damage_function', 'damage_ratio', 'functionality', 'recovery_function', 'recovery_param1', 'recovery_param2' ] # MODEL_SECTIONS required_headers = [ \"component_list\",",
"'damage_ratio', 'functionality', 'recovery_function', 'recovery_param1', 'recovery_param2' ] # MODEL_SECTIONS required_headers = [ \"component_list\", \"node_conn_df\",",
"ALGORITHM_DEFINITION_PARAMS required_col_names = [ 'is_piecewise', 'damage_function', 'damage_ratio', 'functionality', 'recovery_function', 'recovery_param1', 'recovery_param2' ] #"
] |
[
"key, but this time put in the password to check new_key = hashlib.pbkdf2_hmac(",
"salt, key): # Use the exact same setup you used to generate the",
"= os.urandom(32) key = hashlib.pbkdf2_hmac('sha256', password.encode('utf-8'), salt, 100000) return (salt, key) def check_password_hash(password,",
"salt, 100000 ) success = False if new_key == key: success = True",
"new_key = hashlib.pbkdf2_hmac( 'sha256', password.encode('utf-8'), # Convert the password to bytes salt, 100000",
"False if new_key == key: success = True print('Password is correct') else: print('Password",
"# Use the exact same setup you used to generate the key, but",
"= hashlib.pbkdf2_hmac('sha256', password.encode('utf-8'), salt, 100000) return (salt, key) def check_password_hash(password, salt, key): #",
"key): # Use the exact same setup you used to generate the key,",
"def generate_password_hash(password): salt = os.urandom(32) key = hashlib.pbkdf2_hmac('sha256', password.encode('utf-8'), salt, 100000) return (salt,",
"os import hashlib def generate_password_hash(password): salt = os.urandom(32) key = hashlib.pbkdf2_hmac('sha256', password.encode('utf-8'), salt,",
"to check new_key = hashlib.pbkdf2_hmac( 'sha256', password.encode('utf-8'), # Convert the password to bytes",
"this time put in the password to check new_key = hashlib.pbkdf2_hmac( 'sha256', password.encode('utf-8'),",
"def check_password_hash(password, salt, key): # Use the exact same setup you used to",
"bytes salt, 100000 ) success = False if new_key == key: success =",
"salt, 100000) return (salt, key) def check_password_hash(password, salt, key): # Use the exact",
"= hashlib.pbkdf2_hmac( 'sha256', password.encode('utf-8'), # Convert the password to bytes salt, 100000 )",
"check_password_hash(password, salt, key): # Use the exact same setup you used to generate",
"hashlib.pbkdf2_hmac( 'sha256', password.encode('utf-8'), # Convert the password to bytes salt, 100000 ) success",
"to bytes salt, 100000 ) success = False if new_key == key: success",
"used to generate the key, but this time put in the password to",
"same setup you used to generate the key, but this time put in",
"but this time put in the password to check new_key = hashlib.pbkdf2_hmac( 'sha256',",
"the password to check new_key = hashlib.pbkdf2_hmac( 'sha256', password.encode('utf-8'), # Convert the password",
"the password to bytes salt, 100000 ) success = False if new_key ==",
"== key: success = True print('Password is correct') else: print('Password is incorrect') return",
"100000) return (salt, key) def check_password_hash(password, salt, key): # Use the exact same",
"setup you used to generate the key, but this time put in the",
"Use the exact same setup you used to generate the key, but this",
"password to bytes salt, 100000 ) success = False if new_key == key:",
"new_key == key: success = True print('Password is correct') else: print('Password is incorrect')",
"the key, but this time put in the password to check new_key =",
"put in the password to check new_key = hashlib.pbkdf2_hmac( 'sha256', password.encode('utf-8'), # Convert",
"generate the key, but this time put in the password to check new_key",
"generate_password_hash(password): salt = os.urandom(32) key = hashlib.pbkdf2_hmac('sha256', password.encode('utf-8'), salt, 100000) return (salt, key)",
"'sha256', password.encode('utf-8'), # Convert the password to bytes salt, 100000 ) success =",
"key) def check_password_hash(password, salt, key): # Use the exact same setup you used",
"100000 ) success = False if new_key == key: success = True print('Password",
"os.urandom(32) key = hashlib.pbkdf2_hmac('sha256', password.encode('utf-8'), salt, 100000) return (salt, key) def check_password_hash(password, salt,",
"exact same setup you used to generate the key, but this time put",
"salt = os.urandom(32) key = hashlib.pbkdf2_hmac('sha256', password.encode('utf-8'), salt, 100000) return (salt, key) def",
"success = False if new_key == key: success = True print('Password is correct')",
"the exact same setup you used to generate the key, but this time",
"password to check new_key = hashlib.pbkdf2_hmac( 'sha256', password.encode('utf-8'), # Convert the password to",
"password.encode('utf-8'), salt, 100000) return (salt, key) def check_password_hash(password, salt, key): # Use the",
"key = hashlib.pbkdf2_hmac('sha256', password.encode('utf-8'), salt, 100000) return (salt, key) def check_password_hash(password, salt, key):",
"# Convert the password to bytes salt, 100000 ) success = False if",
"= False if new_key == key: success = True print('Password is correct') else:",
"you used to generate the key, but this time put in the password",
"key: success = True print('Password is correct') else: print('Password is incorrect') return success",
"in the password to check new_key = hashlib.pbkdf2_hmac( 'sha256', password.encode('utf-8'), # Convert the",
"time put in the password to check new_key = hashlib.pbkdf2_hmac( 'sha256', password.encode('utf-8'), #",
"hashlib.pbkdf2_hmac('sha256', password.encode('utf-8'), salt, 100000) return (salt, key) def check_password_hash(password, salt, key): # Use",
"check new_key = hashlib.pbkdf2_hmac( 'sha256', password.encode('utf-8'), # Convert the password to bytes salt,",
"password.encode('utf-8'), # Convert the password to bytes salt, 100000 ) success = False",
"Convert the password to bytes salt, 100000 ) success = False if new_key",
"(salt, key) def check_password_hash(password, salt, key): # Use the exact same setup you",
"hashlib def generate_password_hash(password): salt = os.urandom(32) key = hashlib.pbkdf2_hmac('sha256', password.encode('utf-8'), salt, 100000) return",
"import os import hashlib def generate_password_hash(password): salt = os.urandom(32) key = hashlib.pbkdf2_hmac('sha256', password.encode('utf-8'),",
"to generate the key, but this time put in the password to check",
"import hashlib def generate_password_hash(password): salt = os.urandom(32) key = hashlib.pbkdf2_hmac('sha256', password.encode('utf-8'), salt, 100000)",
") success = False if new_key == key: success = True print('Password is",
"if new_key == key: success = True print('Password is correct') else: print('Password is",
"return (salt, key) def check_password_hash(password, salt, key): # Use the exact same setup"
] |
[
"import path try: fl = f\"{path[0]}/\" + input(\"Escribe el nobre del archvo: \")",
"el nobre del archvo: \") with open(fl, \"w\") as f: f.write(\"aBca\") except Exception",
"deben presentar recuentos distintos de cero). Questión: Crea un archivo de prueba para",
"orden alfabético (solo se deben presentar recuentos distintos de cero). Questión: Crea un",
"tratan como iguales). Imprima un histograma simple en orden alfabético (solo se deben",
"except Exception as e: print(e) dic = {} try: f = open(fl, \"r\")",
"simple en orden alfabético (solo se deben presentar recuentos distintos de cero). Questión:",
"distintos de cero). Questión: Crea un archivo de prueba para tu código y",
"un histograma simple en orden alfabético (solo se deben presentar recuentos distintos de",
"Lea el archivo (si es posible) y cuente todas las letras latinas (las",
"y verifica si tu histograma contiene resultados válidos. ''' from sys import path",
"f.close() for k in data: if k not in dic.keys(): dic[k] = 1",
"input(\"Escribe el nobre del archvo: \") with open(fl, \"w\") as f: f.write(\"aBca\") except",
"todas las letras latinas (las letras mayúsculas y minúsculas se tratan como iguales).",
"entrada. Lea el archivo (si es posible) y cuente todas las letras latinas",
"Pasos: Pida al usuario el nombre del archivo de entrada. Lea el archivo",
"tu histograma contiene resultados válidos. ''' from sys import path try: fl =",
"1 else: dic[k] += 1 for k, v in dic.items(): print(f\"{k} -> {v}\")",
"else: dic[k] += 1 for k, v in dic.items(): print(f\"{k} -> {v}\") except",
"del archivo de entrada. Lea el archivo (si es posible) y cuente todas",
"with open(fl, \"w\") as f: f.write(\"aBca\") except Exception as e: print(e) dic =",
"f.write(\"aBca\") except Exception as e: print(e) dic = {} try: f = open(fl,",
"k in data: if k not in dic.keys(): dic[k] = 1 else: dic[k]",
"Crea un archivo de prueba para tu código y verifica si tu histograma",
"try: fl = f\"{path[0]}/\" + input(\"Escribe el nobre del archvo: \") with open(fl,",
"in dic.keys(): dic[k] = 1 else: dic[k] += 1 for k, v in",
"Pida al usuario el nombre del archivo de entrada. Lea el archivo (si",
"en orden alfabético (solo se deben presentar recuentos distintos de cero). Questión: Crea",
"dic = {} try: f = open(fl, \"r\") data = f.read() f.close() for",
"from sys import path try: fl = f\"{path[0]}/\" + input(\"Escribe el nobre del",
"un archivo de prueba para tu código y verifica si tu histograma contiene",
"Questión: Crea un archivo de prueba para tu código y verifica si tu",
"se tratan como iguales). Imprima un histograma simple en orden alfabético (solo se",
"open(fl, \"r\") data = f.read() f.close() for k in data: if k not",
"usuario el nombre del archivo de entrada. Lea el archivo (si es posible)",
"for k, v in dic.items(): print(f\"{k} -> {v}\") except Exception as e: print(e)",
"válidos. ''' from sys import path try: fl = f\"{path[0]}/\" + input(\"Escribe el",
"nobre del archvo: \") with open(fl, \"w\") as f: f.write(\"aBca\") except Exception as",
"f.read() f.close() for k in data: if k not in dic.keys(): dic[k] =",
"try: f = open(fl, \"r\") data = f.read() f.close() for k in data:",
"= 1 else: dic[k] += 1 for k, v in dic.items(): print(f\"{k} ->",
"letras mayúsculas y minúsculas se tratan como iguales). Imprima un histograma simple en",
"if k not in dic.keys(): dic[k] = 1 else: dic[k] += 1 for",
"e: print(e) dic = {} try: f = open(fl, \"r\") data = f.read()",
"dic[k] += 1 for k, v in dic.items(): print(f\"{k} -> {v}\") except Exception",
"1 for k, v in dic.items(): print(f\"{k} -> {v}\") except Exception as e:",
"f = open(fl, \"r\") data = f.read() f.close() for k in data: if",
"fl = f\"{path[0]}/\" + input(\"Escribe el nobre del archvo: \") with open(fl, \"w\")",
"\") with open(fl, \"w\") as f: f.write(\"aBca\") except Exception as e: print(e) dic",
"latinas (las letras mayúsculas y minúsculas se tratan como iguales). Imprima un histograma",
"data = f.read() f.close() for k in data: if k not in dic.keys():",
"as e: print(e) dic = {} try: f = open(fl, \"r\") data =",
"es posible) y cuente todas las letras latinas (las letras mayúsculas y minúsculas",
"el archivo (si es posible) y cuente todas las letras latinas (las letras",
"data: if k not in dic.keys(): dic[k] = 1 else: dic[k] += 1",
"prueba para tu código y verifica si tu histograma contiene resultados válidos. '''",
"código y verifica si tu histograma contiene resultados válidos. ''' from sys import",
"for k in data: if k not in dic.keys(): dic[k] = 1 else:",
"cero). Questión: Crea un archivo de prueba para tu código y verifica si",
"dic.keys(): dic[k] = 1 else: dic[k] += 1 for k, v in dic.items():",
"minúsculas se tratan como iguales). Imprima un histograma simple en orden alfabético (solo",
"= open(fl, \"r\") data = f.read() f.close() for k in data: if k",
"f: f.write(\"aBca\") except Exception as e: print(e) dic = {} try: f =",
"las letras latinas (las letras mayúsculas y minúsculas se tratan como iguales). Imprima",
"\"r\") data = f.read() f.close() for k in data: if k not in",
"archivo de entrada. Lea el archivo (si es posible) y cuente todas las",
"cuente todas las letras latinas (las letras mayúsculas y minúsculas se tratan como",
"tu código y verifica si tu histograma contiene resultados válidos. ''' from sys",
"archivo de prueba para tu código y verifica si tu histograma contiene resultados",
"path try: fl = f\"{path[0]}/\" + input(\"Escribe el nobre del archvo: \") with",
"sys import path try: fl = f\"{path[0]}/\" + input(\"Escribe el nobre del archvo:",
"letras latinas (las letras mayúsculas y minúsculas se tratan como iguales). Imprima un",
"(las letras mayúsculas y minúsculas se tratan como iguales). Imprima un histograma simple",
"\"w\") as f: f.write(\"aBca\") except Exception as e: print(e) dic = {} try:",
"= f.read() f.close() for k in data: if k not in dic.keys(): dic[k]",
"para tu código y verifica si tu histograma contiene resultados válidos. ''' from",
"posible) y cuente todas las letras latinas (las letras mayúsculas y minúsculas se",
"de prueba para tu código y verifica si tu histograma contiene resultados válidos.",
"si tu histograma contiene resultados válidos. ''' from sys import path try: fl",
"f\"{path[0]}/\" + input(\"Escribe el nobre del archvo: \") with open(fl, \"w\") as f:",
"''' from sys import path try: fl = f\"{path[0]}/\" + input(\"Escribe el nobre",
"''' Pasos: Pida al usuario el nombre del archivo de entrada. Lea el",
"in data: if k not in dic.keys(): dic[k] = 1 else: dic[k] +=",
"alfabético (solo se deben presentar recuentos distintos de cero). Questión: Crea un archivo",
"k not in dic.keys(): dic[k] = 1 else: dic[k] += 1 for k,",
"iguales). Imprima un histograma simple en orden alfabético (solo se deben presentar recuentos",
"presentar recuentos distintos de cero). Questión: Crea un archivo de prueba para tu",
"histograma simple en orden alfabético (solo se deben presentar recuentos distintos de cero).",
"print(e) dic = {} try: f = open(fl, \"r\") data = f.read() f.close()",
"not in dic.keys(): dic[k] = 1 else: dic[k] += 1 for k, v",
"as f: f.write(\"aBca\") except Exception as e: print(e) dic = {} try: f",
"y cuente todas las letras latinas (las letras mayúsculas y minúsculas se tratan",
"resultados válidos. ''' from sys import path try: fl = f\"{path[0]}/\" + input(\"Escribe",
"= {} try: f = open(fl, \"r\") data = f.read() f.close() for k",
"Exception as e: print(e) dic = {} try: f = open(fl, \"r\") data",
"= f\"{path[0]}/\" + input(\"Escribe el nobre del archvo: \") with open(fl, \"w\") as",
"al usuario el nombre del archivo de entrada. Lea el archivo (si es",
"Imprima un histograma simple en orden alfabético (solo se deben presentar recuentos distintos",
"histograma contiene resultados válidos. ''' from sys import path try: fl = f\"{path[0]}/\"",
"se deben presentar recuentos distintos de cero). Questión: Crea un archivo de prueba",
"+ input(\"Escribe el nobre del archvo: \") with open(fl, \"w\") as f: f.write(\"aBca\")",
"como iguales). Imprima un histograma simple en orden alfabético (solo se deben presentar",
"de entrada. Lea el archivo (si es posible) y cuente todas las letras",
"+= 1 for k, v in dic.items(): print(f\"{k} -> {v}\") except Exception as",
"el nombre del archivo de entrada. Lea el archivo (si es posible) y",
"dic[k] = 1 else: dic[k] += 1 for k, v in dic.items(): print(f\"{k}",
"(si es posible) y cuente todas las letras latinas (las letras mayúsculas y",
"mayúsculas y minúsculas se tratan como iguales). Imprima un histograma simple en orden",
"verifica si tu histograma contiene resultados válidos. ''' from sys import path try:",
"(solo se deben presentar recuentos distintos de cero). Questión: Crea un archivo de",
"recuentos distintos de cero). Questión: Crea un archivo de prueba para tu código",
"{} try: f = open(fl, \"r\") data = f.read() f.close() for k in",
"nombre del archivo de entrada. Lea el archivo (si es posible) y cuente",
"del archvo: \") with open(fl, \"w\") as f: f.write(\"aBca\") except Exception as e:",
"y minúsculas se tratan como iguales). Imprima un histograma simple en orden alfabético",
"open(fl, \"w\") as f: f.write(\"aBca\") except Exception as e: print(e) dic = {}",
"de cero). Questión: Crea un archivo de prueba para tu código y verifica",
"contiene resultados válidos. ''' from sys import path try: fl = f\"{path[0]}/\" +",
"archvo: \") with open(fl, \"w\") as f: f.write(\"aBca\") except Exception as e: print(e)",
"archivo (si es posible) y cuente todas las letras latinas (las letras mayúsculas"
] |
[
"Signature, SigningKey from ..base import BaseModel from ..signed_change_request_message import SignedChangeRequestMessage T = TypeVar('T',",
"import BaseModel from ..signed_change_request_message import SignedChangeRequestMessage T = TypeVar('T', bound='SignedChangeRequest') class SignedChangeRequest(ValidatableMixin, BaseModel,",
"blockchain_facade): if blockchain_facade.get_account_lock(self.signer) != self.message.account_lock: raise ValidationError('Invalid account lock') @lock(BLOCK_LOCK, expect_locked=True) def validate_blockchain_state_dependent(self,",
"from ..base import BaseModel from ..signed_change_request_message import SignedChangeRequestMessage T = TypeVar('T', bound='SignedChangeRequest') class",
"node.blockchain.mixins.crypto import HashableMixin, validate_signature_helper from node.blockchain.mixins.validatable import ValidatableMixin from node.blockchain.utils.lock import lock from",
"== SignedChangeRequest: # only child classes signature validation makes sense return values return",
"values return validate_signature_helper(values) def validate_business_logic(self): self.message.validate_business_logic() def validate_account_lock(self, blockchain_facade): if blockchain_facade.get_account_lock(self.signer) != self.message.account_lock:",
"blockchain_facade.get_account_lock(self.signer) != self.message.account_lock: raise ValidationError('Invalid account lock') @lock(BLOCK_LOCK, expect_locked=True) def validate_blockchain_state_dependent(self, blockchain_facade): self.message.validate_blockchain_state_dependent(blockchain_facade,",
"ValidatableMixin from node.blockchain.utils.lock import lock from node.core.exceptions import ValidationError from node.core.utils.cryptography import derive_public_key",
"= TypeVar('T', bound='SignedChangeRequest') class SignedChangeRequest(ValidatableMixin, BaseModel, HashableMixin): signer: AccountNumber signature: Signature message: SignedChangeRequestMessage",
"obj return class_.parse_obj(*args, **kwargs) @root_validator def validate_signature(cls, values): if cls == SignedChangeRequest: #",
"validate_business_logic(self): self.message.validate_business_logic() def validate_account_lock(self, blockchain_facade): if blockchain_facade.get_account_lock(self.signer) != self.message.account_lock: raise ValidationError('Invalid account lock')",
"message.type should be validated by now if cls == class_: # avoid recursion",
"classes signature validation makes sense return values return validate_signature_helper(values) def validate_business_logic(self): self.message.validate_business_logic() def",
"be validated by now class_ = cast(TypingType[T], class_) return class_( signer=derive_public_key(signing_key), signature=message.make_signature(signing_key), message=message,",
"account lock') @lock(BLOCK_LOCK, expect_locked=True) def validate_blockchain_state_dependent(self, blockchain_facade): self.message.validate_blockchain_state_dependent(blockchain_facade, bypass_lock_validation=True) self.validate_account_lock(blockchain_facade) def get_type(self): return",
"self.message.account_lock: raise ValidationError('Invalid account lock') @lock(BLOCK_LOCK, expect_locked=True) def validate_blockchain_state_dependent(self, blockchain_facade): self.message.validate_blockchain_state_dependent(blockchain_facade, bypass_lock_validation=True) self.validate_account_lock(blockchain_facade)",
"node.core.exceptions import ValidationError from node.core.utils.cryptography import derive_public_key from ...types import AccountNumber, Signature, SigningKey",
"HashableMixin): signer: AccountNumber signature: Signature message: SignedChangeRequestMessage @classmethod def create_from_signed_change_request_message( cls: TypingType[T], message:",
"ValidationError('Invalid account lock') @lock(BLOCK_LOCK, expect_locked=True) def validate_blockchain_state_dependent(self, blockchain_facade): self.message.validate_blockchain_state_dependent(blockchain_facade, bypass_lock_validation=True) self.validate_account_lock(blockchain_facade) def get_type(self):",
"node.blockchain.mixins.validatable import ValidatableMixin from node.blockchain.utils.lock import lock from node.core.exceptions import ValidationError from node.core.utils.cryptography",
"# because message.type should be validated by now class_ = cast(TypingType[T], class_) return",
"import BLOCK_LOCK from node.blockchain.mixins.crypto import HashableMixin, validate_signature_helper from node.blockchain.mixins.validatable import ValidatableMixin from node.blockchain.utils.lock",
"signature: Signature message: SignedChangeRequestMessage @classmethod def create_from_signed_change_request_message( cls: TypingType[T], message: SignedChangeRequestMessage, signing_key: SigningKey",
"message: SignedChangeRequestMessage, signing_key: SigningKey ) -> T: from node.blockchain.inner_models.type_map import get_signed_change_request_subclass class_ =",
"now if cls == class_: # avoid recursion return obj return class_.parse_obj(*args, **kwargs)",
"import get_signed_change_request_subclass class_ = get_signed_change_request_subclass(type_) assert class_ # because message.type should be validated",
"root_validator from node.blockchain.constants import BLOCK_LOCK from node.blockchain.mixins.crypto import HashableMixin, validate_signature_helper from node.blockchain.mixins.validatable import",
"def validate_signature(cls, values): if cls == SignedChangeRequest: # only child classes signature validation",
"from node.blockchain.mixins.validatable import ValidatableMixin from node.blockchain.utils.lock import lock from node.core.exceptions import ValidationError from",
"T = TypeVar('T', bound='SignedChangeRequest') class SignedChangeRequest(ValidatableMixin, BaseModel, HashableMixin): signer: AccountNumber signature: Signature message:",
"class_ = cast(TypingType[T], class_) return class_( signer=derive_public_key(signing_key), signature=message.make_signature(signing_key), message=message, ) @classmethod def parse_obj(cls,",
"if cls == class_: # avoid recursion return obj return class_.parse_obj(*args, **kwargs) @root_validator",
"from node.blockchain.mixins.crypto import HashableMixin, validate_signature_helper from node.blockchain.mixins.validatable import ValidatableMixin from node.blockchain.utils.lock import lock",
"class_: # avoid recursion return obj return class_.parse_obj(*args, **kwargs) @root_validator def validate_signature(cls, values):",
"sense return values return validate_signature_helper(values) def validate_business_logic(self): self.message.validate_business_logic() def validate_account_lock(self, blockchain_facade): if blockchain_facade.get_account_lock(self.signer)",
"HashableMixin, validate_signature_helper from node.blockchain.mixins.validatable import ValidatableMixin from node.blockchain.utils.lock import lock from node.core.exceptions import",
"super().parse_obj(*args, **kwargs) type_ = obj.message.type from node.blockchain.inner_models.type_map import get_signed_change_request_subclass class_ = get_signed_change_request_subclass(type_) assert",
"get_signed_change_request_subclass class_ = get_signed_change_request_subclass(type_) assert class_ # because message.type should be validated by",
"validate_signature(cls, values): if cls == SignedChangeRequest: # only child classes signature validation makes",
"from ...types import AccountNumber, Signature, SigningKey from ..base import BaseModel from ..signed_change_request_message import",
"get_signed_change_request_subclass class_ = get_signed_change_request_subclass(message.type) assert class_ # because message.type should be validated by",
"signer=derive_public_key(signing_key), signature=message.make_signature(signing_key), message=message, ) @classmethod def parse_obj(cls, *args, **kwargs): obj = super().parse_obj(*args, **kwargs)",
"only child classes signature validation makes sense return values return validate_signature_helper(values) def validate_business_logic(self):",
"class_( signer=derive_public_key(signing_key), signature=message.make_signature(signing_key), message=message, ) @classmethod def parse_obj(cls, *args, **kwargs): obj = super().parse_obj(*args,",
"import ValidatableMixin from node.blockchain.utils.lock import lock from node.core.exceptions import ValidationError from node.core.utils.cryptography import",
"BaseModel, HashableMixin): signer: AccountNumber signature: Signature message: SignedChangeRequestMessage @classmethod def create_from_signed_change_request_message( cls: TypingType[T],",
"now class_ = cast(TypingType[T], class_) return class_( signer=derive_public_key(signing_key), signature=message.make_signature(signing_key), message=message, ) @classmethod def",
"**kwargs) type_ = obj.message.type from node.blockchain.inner_models.type_map import get_signed_change_request_subclass class_ = get_signed_change_request_subclass(type_) assert class_",
"get_signed_change_request_subclass(type_) assert class_ # because message.type should be validated by now if cls",
"by now if cls == class_: # avoid recursion return obj return class_.parse_obj(*args,",
"cls == class_: # avoid recursion return obj return class_.parse_obj(*args, **kwargs) @root_validator def",
"import Type as TypingType from typing import TypeVar, cast from pydantic import root_validator",
"as TypingType from typing import TypeVar, cast from pydantic import root_validator from node.blockchain.constants",
"import AccountNumber, Signature, SigningKey from ..base import BaseModel from ..signed_change_request_message import SignedChangeRequestMessage T",
"class_.parse_obj(*args, **kwargs) @root_validator def validate_signature(cls, values): if cls == SignedChangeRequest: # only child",
"signature=message.make_signature(signing_key), message=message, ) @classmethod def parse_obj(cls, *args, **kwargs): obj = super().parse_obj(*args, **kwargs) type_",
"lock from node.core.exceptions import ValidationError from node.core.utils.cryptography import derive_public_key from ...types import AccountNumber,",
"because message.type should be validated by now class_ = cast(TypingType[T], class_) return class_(",
"*args, **kwargs): obj = super().parse_obj(*args, **kwargs) type_ = obj.message.type from node.blockchain.inner_models.type_map import get_signed_change_request_subclass",
"create_from_signed_change_request_message( cls: TypingType[T], message: SignedChangeRequestMessage, signing_key: SigningKey ) -> T: from node.blockchain.inner_models.type_map import",
"ValidationError from node.core.utils.cryptography import derive_public_key from ...types import AccountNumber, Signature, SigningKey from ..base",
"node.blockchain.utils.lock import lock from node.core.exceptions import ValidationError from node.core.utils.cryptography import derive_public_key from ...types",
"obj.message.type from node.blockchain.inner_models.type_map import get_signed_change_request_subclass class_ = get_signed_change_request_subclass(type_) assert class_ # because message.type",
"!= self.message.account_lock: raise ValidationError('Invalid account lock') @lock(BLOCK_LOCK, expect_locked=True) def validate_blockchain_state_dependent(self, blockchain_facade): self.message.validate_blockchain_state_dependent(blockchain_facade, bypass_lock_validation=True)",
"assert class_ # because message.type should be validated by now class_ = cast(TypingType[T],",
"child classes signature validation makes sense return values return validate_signature_helper(values) def validate_business_logic(self): self.message.validate_business_logic()",
"BaseModel from ..signed_change_request_message import SignedChangeRequestMessage T = TypeVar('T', bound='SignedChangeRequest') class SignedChangeRequest(ValidatableMixin, BaseModel, HashableMixin):",
"def validate_business_logic(self): self.message.validate_business_logic() def validate_account_lock(self, blockchain_facade): if blockchain_facade.get_account_lock(self.signer) != self.message.account_lock: raise ValidationError('Invalid account",
"from node.core.utils.cryptography import derive_public_key from ...types import AccountNumber, Signature, SigningKey from ..base import",
"return class_( signer=derive_public_key(signing_key), signature=message.make_signature(signing_key), message=message, ) @classmethod def parse_obj(cls, *args, **kwargs): obj =",
"# avoid recursion return obj return class_.parse_obj(*args, **kwargs) @root_validator def validate_signature(cls, values): if",
"...types import AccountNumber, Signature, SigningKey from ..base import BaseModel from ..signed_change_request_message import SignedChangeRequestMessage",
"signing_key: SigningKey ) -> T: from node.blockchain.inner_models.type_map import get_signed_change_request_subclass class_ = get_signed_change_request_subclass(message.type) assert",
"<filename>node/blockchain/inner_models/signed_change_request/base.py from typing import Type as TypingType from typing import TypeVar, cast from",
"derive_public_key from ...types import AccountNumber, Signature, SigningKey from ..base import BaseModel from ..signed_change_request_message",
"makes sense return values return validate_signature_helper(values) def validate_business_logic(self): self.message.validate_business_logic() def validate_account_lock(self, blockchain_facade): if",
"class_ = get_signed_change_request_subclass(message.type) assert class_ # because message.type should be validated by now",
"lock') @lock(BLOCK_LOCK, expect_locked=True) def validate_blockchain_state_dependent(self, blockchain_facade): self.message.validate_blockchain_state_dependent(blockchain_facade, bypass_lock_validation=True) self.validate_account_lock(blockchain_facade) def get_type(self): return self.message.type",
"node.blockchain.inner_models.type_map import get_signed_change_request_subclass class_ = get_signed_change_request_subclass(message.type) assert class_ # because message.type should be",
"import derive_public_key from ...types import AccountNumber, Signature, SigningKey from ..base import BaseModel from",
"import HashableMixin, validate_signature_helper from node.blockchain.mixins.validatable import ValidatableMixin from node.blockchain.utils.lock import lock from node.core.exceptions",
"import TypeVar, cast from pydantic import root_validator from node.blockchain.constants import BLOCK_LOCK from node.blockchain.mixins.crypto",
"because message.type should be validated by now if cls == class_: # avoid",
"T: from node.blockchain.inner_models.type_map import get_signed_change_request_subclass class_ = get_signed_change_request_subclass(message.type) assert class_ # because message.type",
"obj = super().parse_obj(*args, **kwargs) type_ = obj.message.type from node.blockchain.inner_models.type_map import get_signed_change_request_subclass class_ =",
"if blockchain_facade.get_account_lock(self.signer) != self.message.account_lock: raise ValidationError('Invalid account lock') @lock(BLOCK_LOCK, expect_locked=True) def validate_blockchain_state_dependent(self, blockchain_facade):",
"TypingType from typing import TypeVar, cast from pydantic import root_validator from node.blockchain.constants import",
"get_signed_change_request_subclass(message.type) assert class_ # because message.type should be validated by now class_ =",
"import lock from node.core.exceptions import ValidationError from node.core.utils.cryptography import derive_public_key from ...types import",
"from node.blockchain.constants import BLOCK_LOCK from node.blockchain.mixins.crypto import HashableMixin, validate_signature_helper from node.blockchain.mixins.validatable import ValidatableMixin",
") @classmethod def parse_obj(cls, *args, **kwargs): obj = super().parse_obj(*args, **kwargs) type_ = obj.message.type",
"from node.blockchain.utils.lock import lock from node.core.exceptions import ValidationError from node.core.utils.cryptography import derive_public_key from",
"bound='SignedChangeRequest') class SignedChangeRequest(ValidatableMixin, BaseModel, HashableMixin): signer: AccountNumber signature: Signature message: SignedChangeRequestMessage @classmethod def",
"@classmethod def create_from_signed_change_request_message( cls: TypingType[T], message: SignedChangeRequestMessage, signing_key: SigningKey ) -> T: from",
"# because message.type should be validated by now if cls == class_: #",
"from node.blockchain.inner_models.type_map import get_signed_change_request_subclass class_ = get_signed_change_request_subclass(message.type) assert class_ # because message.type should",
"# only child classes signature validation makes sense return values return validate_signature_helper(values) def",
"signature validation makes sense return values return validate_signature_helper(values) def validate_business_logic(self): self.message.validate_business_logic() def validate_account_lock(self,",
"validate_signature_helper from node.blockchain.mixins.validatable import ValidatableMixin from node.blockchain.utils.lock import lock from node.core.exceptions import ValidationError",
") -> T: from node.blockchain.inner_models.type_map import get_signed_change_request_subclass class_ = get_signed_change_request_subclass(message.type) assert class_ #",
"message.type should be validated by now class_ = cast(TypingType[T], class_) return class_( signer=derive_public_key(signing_key),",
"= get_signed_change_request_subclass(message.type) assert class_ # because message.type should be validated by now class_",
"SignedChangeRequestMessage @classmethod def create_from_signed_change_request_message( cls: TypingType[T], message: SignedChangeRequestMessage, signing_key: SigningKey ) -> T:",
"TypingType[T], message: SignedChangeRequestMessage, signing_key: SigningKey ) -> T: from node.blockchain.inner_models.type_map import get_signed_change_request_subclass class_",
"raise ValidationError('Invalid account lock') @lock(BLOCK_LOCK, expect_locked=True) def validate_blockchain_state_dependent(self, blockchain_facade): self.message.validate_blockchain_state_dependent(blockchain_facade, bypass_lock_validation=True) self.validate_account_lock(blockchain_facade) def",
"..signed_change_request_message import SignedChangeRequestMessage T = TypeVar('T', bound='SignedChangeRequest') class SignedChangeRequest(ValidatableMixin, BaseModel, HashableMixin): signer: AccountNumber",
"class SignedChangeRequest(ValidatableMixin, BaseModel, HashableMixin): signer: AccountNumber signature: Signature message: SignedChangeRequestMessage @classmethod def create_from_signed_change_request_message(",
"..base import BaseModel from ..signed_change_request_message import SignedChangeRequestMessage T = TypeVar('T', bound='SignedChangeRequest') class SignedChangeRequest(ValidatableMixin,",
"parse_obj(cls, *args, **kwargs): obj = super().parse_obj(*args, **kwargs) type_ = obj.message.type from node.blockchain.inner_models.type_map import",
"import SignedChangeRequestMessage T = TypeVar('T', bound='SignedChangeRequest') class SignedChangeRequest(ValidatableMixin, BaseModel, HashableMixin): signer: AccountNumber signature:",
"= super().parse_obj(*args, **kwargs) type_ = obj.message.type from node.blockchain.inner_models.type_map import get_signed_change_request_subclass class_ = get_signed_change_request_subclass(type_)",
"**kwargs) @root_validator def validate_signature(cls, values): if cls == SignedChangeRequest: # only child classes",
"return values return validate_signature_helper(values) def validate_business_logic(self): self.message.validate_business_logic() def validate_account_lock(self, blockchain_facade): if blockchain_facade.get_account_lock(self.signer) !=",
"self.message.validate_business_logic() def validate_account_lock(self, blockchain_facade): if blockchain_facade.get_account_lock(self.signer) != self.message.account_lock: raise ValidationError('Invalid account lock') @lock(BLOCK_LOCK,",
"node.core.utils.cryptography import derive_public_key from ...types import AccountNumber, Signature, SigningKey from ..base import BaseModel",
"SignedChangeRequest(ValidatableMixin, BaseModel, HashableMixin): signer: AccountNumber signature: Signature message: SignedChangeRequestMessage @classmethod def create_from_signed_change_request_message( cls:",
"from node.blockchain.inner_models.type_map import get_signed_change_request_subclass class_ = get_signed_change_request_subclass(type_) assert class_ # because message.type should",
"node.blockchain.inner_models.type_map import get_signed_change_request_subclass class_ = get_signed_change_request_subclass(type_) assert class_ # because message.type should be",
"if cls == SignedChangeRequest: # only child classes signature validation makes sense return",
"message=message, ) @classmethod def parse_obj(cls, *args, **kwargs): obj = super().parse_obj(*args, **kwargs) type_ =",
"avoid recursion return obj return class_.parse_obj(*args, **kwargs) @root_validator def validate_signature(cls, values): if cls",
"AccountNumber signature: Signature message: SignedChangeRequestMessage @classmethod def create_from_signed_change_request_message( cls: TypingType[T], message: SignedChangeRequestMessage, signing_key:",
"validated by now if cls == class_: # avoid recursion return obj return",
"def validate_account_lock(self, blockchain_facade): if blockchain_facade.get_account_lock(self.signer) != self.message.account_lock: raise ValidationError('Invalid account lock') @lock(BLOCK_LOCK, expect_locked=True)",
"import root_validator from node.blockchain.constants import BLOCK_LOCK from node.blockchain.mixins.crypto import HashableMixin, validate_signature_helper from node.blockchain.mixins.validatable",
"typing import TypeVar, cast from pydantic import root_validator from node.blockchain.constants import BLOCK_LOCK from",
"node.blockchain.constants import BLOCK_LOCK from node.blockchain.mixins.crypto import HashableMixin, validate_signature_helper from node.blockchain.mixins.validatable import ValidatableMixin from",
"typing import Type as TypingType from typing import TypeVar, cast from pydantic import",
"class_) return class_( signer=derive_public_key(signing_key), signature=message.make_signature(signing_key), message=message, ) @classmethod def parse_obj(cls, *args, **kwargs): obj",
"import get_signed_change_request_subclass class_ = get_signed_change_request_subclass(message.type) assert class_ # because message.type should be validated",
"SignedChangeRequest: # only child classes signature validation makes sense return values return validate_signature_helper(values)",
"from typing import Type as TypingType from typing import TypeVar, cast from pydantic",
"SignedChangeRequestMessage T = TypeVar('T', bound='SignedChangeRequest') class SignedChangeRequest(ValidatableMixin, BaseModel, HashableMixin): signer: AccountNumber signature: Signature",
"TypeVar, cast from pydantic import root_validator from node.blockchain.constants import BLOCK_LOCK from node.blockchain.mixins.crypto import",
"import ValidationError from node.core.utils.cryptography import derive_public_key from ...types import AccountNumber, Signature, SigningKey from",
"BLOCK_LOCK from node.blockchain.mixins.crypto import HashableMixin, validate_signature_helper from node.blockchain.mixins.validatable import ValidatableMixin from node.blockchain.utils.lock import",
"cls: TypingType[T], message: SignedChangeRequestMessage, signing_key: SigningKey ) -> T: from node.blockchain.inner_models.type_map import get_signed_change_request_subclass",
"from typing import TypeVar, cast from pydantic import root_validator from node.blockchain.constants import BLOCK_LOCK",
"@classmethod def parse_obj(cls, *args, **kwargs): obj = super().parse_obj(*args, **kwargs) type_ = obj.message.type from",
"TypeVar('T', bound='SignedChangeRequest') class SignedChangeRequest(ValidatableMixin, BaseModel, HashableMixin): signer: AccountNumber signature: Signature message: SignedChangeRequestMessage @classmethod",
"pydantic import root_validator from node.blockchain.constants import BLOCK_LOCK from node.blockchain.mixins.crypto import HashableMixin, validate_signature_helper from",
"= cast(TypingType[T], class_) return class_( signer=derive_public_key(signing_key), signature=message.make_signature(signing_key), message=message, ) @classmethod def parse_obj(cls, *args,",
"SignedChangeRequestMessage, signing_key: SigningKey ) -> T: from node.blockchain.inner_models.type_map import get_signed_change_request_subclass class_ = get_signed_change_request_subclass(message.type)",
"class_ # because message.type should be validated by now class_ = cast(TypingType[T], class_)",
"== class_: # avoid recursion return obj return class_.parse_obj(*args, **kwargs) @root_validator def validate_signature(cls,",
"recursion return obj return class_.parse_obj(*args, **kwargs) @root_validator def validate_signature(cls, values): if cls ==",
"validated by now class_ = cast(TypingType[T], class_) return class_( signer=derive_public_key(signing_key), signature=message.make_signature(signing_key), message=message, )",
"**kwargs): obj = super().parse_obj(*args, **kwargs) type_ = obj.message.type from node.blockchain.inner_models.type_map import get_signed_change_request_subclass class_",
"Signature message: SignedChangeRequestMessage @classmethod def create_from_signed_change_request_message( cls: TypingType[T], message: SignedChangeRequestMessage, signing_key: SigningKey )",
"= get_signed_change_request_subclass(type_) assert class_ # because message.type should be validated by now if",
"cast from pydantic import root_validator from node.blockchain.constants import BLOCK_LOCK from node.blockchain.mixins.crypto import HashableMixin,",
"should be validated by now if cls == class_: # avoid recursion return",
"class_ # because message.type should be validated by now if cls == class_:",
"values): if cls == SignedChangeRequest: # only child classes signature validation makes sense",
"assert class_ # because message.type should be validated by now if cls ==",
"signer: AccountNumber signature: Signature message: SignedChangeRequestMessage @classmethod def create_from_signed_change_request_message( cls: TypingType[T], message: SignedChangeRequestMessage,",
"from node.core.exceptions import ValidationError from node.core.utils.cryptography import derive_public_key from ...types import AccountNumber, Signature,",
"validation makes sense return values return validate_signature_helper(values) def validate_business_logic(self): self.message.validate_business_logic() def validate_account_lock(self, blockchain_facade):",
"from ..signed_change_request_message import SignedChangeRequestMessage T = TypeVar('T', bound='SignedChangeRequest') class SignedChangeRequest(ValidatableMixin, BaseModel, HashableMixin): signer:",
"SigningKey ) -> T: from node.blockchain.inner_models.type_map import get_signed_change_request_subclass class_ = get_signed_change_request_subclass(message.type) assert class_",
"def parse_obj(cls, *args, **kwargs): obj = super().parse_obj(*args, **kwargs) type_ = obj.message.type from node.blockchain.inner_models.type_map",
"should be validated by now class_ = cast(TypingType[T], class_) return class_( signer=derive_public_key(signing_key), signature=message.make_signature(signing_key),",
"be validated by now if cls == class_: # avoid recursion return obj",
"@root_validator def validate_signature(cls, values): if cls == SignedChangeRequest: # only child classes signature",
"SigningKey from ..base import BaseModel from ..signed_change_request_message import SignedChangeRequestMessage T = TypeVar('T', bound='SignedChangeRequest')",
"type_ = obj.message.type from node.blockchain.inner_models.type_map import get_signed_change_request_subclass class_ = get_signed_change_request_subclass(type_) assert class_ #",
"validate_signature_helper(values) def validate_business_logic(self): self.message.validate_business_logic() def validate_account_lock(self, blockchain_facade): if blockchain_facade.get_account_lock(self.signer) != self.message.account_lock: raise ValidationError('Invalid",
"class_ = get_signed_change_request_subclass(type_) assert class_ # because message.type should be validated by now",
"return validate_signature_helper(values) def validate_business_logic(self): self.message.validate_business_logic() def validate_account_lock(self, blockchain_facade): if blockchain_facade.get_account_lock(self.signer) != self.message.account_lock: raise",
"message: SignedChangeRequestMessage @classmethod def create_from_signed_change_request_message( cls: TypingType[T], message: SignedChangeRequestMessage, signing_key: SigningKey ) ->",
"def create_from_signed_change_request_message( cls: TypingType[T], message: SignedChangeRequestMessage, signing_key: SigningKey ) -> T: from node.blockchain.inner_models.type_map",
"cast(TypingType[T], class_) return class_( signer=derive_public_key(signing_key), signature=message.make_signature(signing_key), message=message, ) @classmethod def parse_obj(cls, *args, **kwargs):",
"return class_.parse_obj(*args, **kwargs) @root_validator def validate_signature(cls, values): if cls == SignedChangeRequest: # only",
"-> T: from node.blockchain.inner_models.type_map import get_signed_change_request_subclass class_ = get_signed_change_request_subclass(message.type) assert class_ # because",
"Type as TypingType from typing import TypeVar, cast from pydantic import root_validator from",
"AccountNumber, Signature, SigningKey from ..base import BaseModel from ..signed_change_request_message import SignedChangeRequestMessage T =",
"= obj.message.type from node.blockchain.inner_models.type_map import get_signed_change_request_subclass class_ = get_signed_change_request_subclass(type_) assert class_ # because",
"validate_account_lock(self, blockchain_facade): if blockchain_facade.get_account_lock(self.signer) != self.message.account_lock: raise ValidationError('Invalid account lock') @lock(BLOCK_LOCK, expect_locked=True) def",
"cls == SignedChangeRequest: # only child classes signature validation makes sense return values",
"from pydantic import root_validator from node.blockchain.constants import BLOCK_LOCK from node.blockchain.mixins.crypto import HashableMixin, validate_signature_helper",
"return obj return class_.parse_obj(*args, **kwargs) @root_validator def validate_signature(cls, values): if cls == SignedChangeRequest:",
"by now class_ = cast(TypingType[T], class_) return class_( signer=derive_public_key(signing_key), signature=message.make_signature(signing_key), message=message, ) @classmethod"
] |
[
"# # Copyright (c) 2018 <NAME> (<EMAIL>) - MIT License # SPDX-License-Identifier: MIT",
"except ImportError: pass import sys from . import sjfmt if __name__ == '__main__':",
"# To enable pretty tracebacks: # echo \"export ENABLE_BACKTRACE=1;\" >> ~/.bashrc backtrace.hook(align=True, strip_path=True,",
"SPDX-License-Identifier: MIT try: import backtrace # To enable pretty tracebacks: # echo \"export",
"enable_on_envvar_only=True) except ImportError: pass import sys from . import sjfmt if __name__ ==",
"of the straitjacket project # https://gitlab.com/mbarkhau/straitjacket # # Copyright (c) 2018 <NAME> (<EMAIL>)",
"2018 <NAME> (<EMAIL>) - MIT License # SPDX-License-Identifier: MIT try: import backtrace #",
"https://gitlab.com/mbarkhau/straitjacket # # Copyright (c) 2018 <NAME> (<EMAIL>) - MIT License # SPDX-License-Identifier:",
"try: import backtrace # To enable pretty tracebacks: # echo \"export ENABLE_BACKTRACE=1;\" >>",
"ImportError: pass import sys from . import sjfmt if __name__ == '__main__': sjfmt.main()",
"(c) 2018 <NAME> (<EMAIL>) - MIT License # SPDX-License-Identifier: MIT try: import backtrace",
"# https://gitlab.com/mbarkhau/straitjacket # # Copyright (c) 2018 <NAME> (<EMAIL>) - MIT License #",
"straitjacket project # https://gitlab.com/mbarkhau/straitjacket # # Copyright (c) 2018 <NAME> (<EMAIL>) - MIT",
"<NAME> (<EMAIL>) - MIT License # SPDX-License-Identifier: MIT try: import backtrace # To",
"This file is part of the straitjacket project # https://gitlab.com/mbarkhau/straitjacket # # Copyright",
"project # https://gitlab.com/mbarkhau/straitjacket # # Copyright (c) 2018 <NAME> (<EMAIL>) - MIT License",
"\"export ENABLE_BACKTRACE=1;\" >> ~/.bashrc backtrace.hook(align=True, strip_path=True, enable_on_envvar_only=True) except ImportError: pass import sys from",
"backtrace.hook(align=True, strip_path=True, enable_on_envvar_only=True) except ImportError: pass import sys from . import sjfmt if",
"is part of the straitjacket project # https://gitlab.com/mbarkhau/straitjacket # # Copyright (c) 2018",
"Copyright (c) 2018 <NAME> (<EMAIL>) - MIT License # SPDX-License-Identifier: MIT try: import",
"pass import sys from . import sjfmt if __name__ == '__main__': sjfmt.main() sys.exit(0)",
"#!/usr/bin/env python # This file is part of the straitjacket project # https://gitlab.com/mbarkhau/straitjacket",
"echo \"export ENABLE_BACKTRACE=1;\" >> ~/.bashrc backtrace.hook(align=True, strip_path=True, enable_on_envvar_only=True) except ImportError: pass import sys",
"# This file is part of the straitjacket project # https://gitlab.com/mbarkhau/straitjacket # #",
"backtrace # To enable pretty tracebacks: # echo \"export ENABLE_BACKTRACE=1;\" >> ~/.bashrc backtrace.hook(align=True,",
"enable pretty tracebacks: # echo \"export ENABLE_BACKTRACE=1;\" >> ~/.bashrc backtrace.hook(align=True, strip_path=True, enable_on_envvar_only=True) except",
"MIT License # SPDX-License-Identifier: MIT try: import backtrace # To enable pretty tracebacks:",
"# echo \"export ENABLE_BACKTRACE=1;\" >> ~/.bashrc backtrace.hook(align=True, strip_path=True, enable_on_envvar_only=True) except ImportError: pass import",
"part of the straitjacket project # https://gitlab.com/mbarkhau/straitjacket # # Copyright (c) 2018 <NAME>",
">> ~/.bashrc backtrace.hook(align=True, strip_path=True, enable_on_envvar_only=True) except ImportError: pass import sys from . import",
"strip_path=True, enable_on_envvar_only=True) except ImportError: pass import sys from . import sjfmt if __name__",
"python # This file is part of the straitjacket project # https://gitlab.com/mbarkhau/straitjacket #",
"- MIT License # SPDX-License-Identifier: MIT try: import backtrace # To enable pretty",
"pretty tracebacks: # echo \"export ENABLE_BACKTRACE=1;\" >> ~/.bashrc backtrace.hook(align=True, strip_path=True, enable_on_envvar_only=True) except ImportError:",
"import backtrace # To enable pretty tracebacks: # echo \"export ENABLE_BACKTRACE=1;\" >> ~/.bashrc",
"file is part of the straitjacket project # https://gitlab.com/mbarkhau/straitjacket # # Copyright (c)",
"License # SPDX-License-Identifier: MIT try: import backtrace # To enable pretty tracebacks: #",
"(<EMAIL>) - MIT License # SPDX-License-Identifier: MIT try: import backtrace # To enable",
"the straitjacket project # https://gitlab.com/mbarkhau/straitjacket # # Copyright (c) 2018 <NAME> (<EMAIL>) -",
"# SPDX-License-Identifier: MIT try: import backtrace # To enable pretty tracebacks: # echo",
"tracebacks: # echo \"export ENABLE_BACKTRACE=1;\" >> ~/.bashrc backtrace.hook(align=True, strip_path=True, enable_on_envvar_only=True) except ImportError: pass",
"To enable pretty tracebacks: # echo \"export ENABLE_BACKTRACE=1;\" >> ~/.bashrc backtrace.hook(align=True, strip_path=True, enable_on_envvar_only=True)",
"ENABLE_BACKTRACE=1;\" >> ~/.bashrc backtrace.hook(align=True, strip_path=True, enable_on_envvar_only=True) except ImportError: pass import sys from .",
"~/.bashrc backtrace.hook(align=True, strip_path=True, enable_on_envvar_only=True) except ImportError: pass import sys from . import sjfmt",
"MIT try: import backtrace # To enable pretty tracebacks: # echo \"export ENABLE_BACKTRACE=1;\"",
"# Copyright (c) 2018 <NAME> (<EMAIL>) - MIT License # SPDX-License-Identifier: MIT try:"
] |
[
"used at # this time. self.logger.info(\"terraform_version: %s\", terraform_version) # Capture resources to parse",
"file directly if self.tfstate is not None: # Log tfstate file path self.logger.info(\"Loading",
"to the original current working directory os.chdir(current_dir) # Log and exit if file/directory",
"file.\"\"\" # Load resources up resources = self.load() # Check if resources are",
"= {} # Define Terraform tfstate file to load self.tfstate = args.tfstate #",
"newer Terraform versions if isinstance(resources, list): for resource in resources: self.resource_types(resource) instances =",
"tfstate file with open(self.tfstate, \"r\") as stream: # Load JSON data try: data",
"sys class Parser: \"\"\"Main Terraform tfstate parser.\"\"\" def __init__(self, args): \"\"\"Init a thing.\"\"\"",
"dict): for resource, resource_config in resources.items(): self.resource_types(resource_config) self.all_resources[resource_config[\"type\"]].append( resource_config[\"primary\"][\"attributes\"] ) return self.all_resources def",
"found except FileNotFoundError as error: self.logger.error(error) sys.exit(1) # Capture Terraform version from tfstate",
"resource): \"\"\"Populate resource types.\"\"\" # Check to see if all_resources is already populated",
"back. current_dir = os.getcwd() # Change to the tfstate directory os.chdir(self.tfstatedir) try: #",
"from directory using terraform state pull else: # Log tfstate directory self.logger.info(\"Loading --tfstatedir",
"self.all_resources.get(resource[\"type\"]) # Add resource type to all resources if not found in lookup",
"and exit if file not found except FileNotFoundError as error: self.logger.error(error) sys.exit(1) #",
"# Add resource type to all resources if not found in lookup if",
"to all resources if not found in lookup if resource_type_lookup is None: self.all_resources[resource[\"type\"]]",
"current working directory prior to changing to the # tfstate directory. So, we",
"self.all_resources def resource_types(self, resource): \"\"\"Populate resource types.\"\"\" # Check to see if all_resources",
"# Open tfstate file with open(self.tfstate, \"r\") as stream: # Load JSON data",
"FileNotFoundError as error: self.logger.error(error) sys.exit(1) # Capture Terraform version from tfstate terraform_version =",
"resource.get(\"instances\") if instances is not None: for instance in instances: self.all_resources[resource[\"type\"]].append( instance[\"attributes\"] )",
"populated with resource type resource_type_lookup = self.all_resources.get(resource[\"type\"]) # Add resource type to all",
"state pull\") ) # Log and exit if JSON data not found except",
"versions elif isinstance(resources, dict): for resource, resource_config in resources.items(): self.resource_types(resource_config) self.all_resources[resource_config[\"type\"]].append( resource_config[\"primary\"][\"attributes\"] )",
"logging import os import subprocess import sys class Parser: \"\"\"Main Terraform tfstate parser.\"\"\"",
"self.tfstate = args.tfstate # Define Terraform tfstate directory to load self.tfstatedir = args.tfstatedir",
"sys.exit(1) # Change back to the original current working directory os.chdir(current_dir) # Log",
"{} # Define Terraform tfstate file to load self.tfstate = args.tfstate # Define",
"tfstate from directory using terraform state pull else: # Log tfstate directory self.logger.info(\"Loading",
"JSON data not found except json.decoder.JSONDecodeError as error: self.logger.error(error) sys.exit(1) # Change back",
"= json.loads( subprocess.getoutput(\"terraform state pull\") ) # Log and exit if JSON data",
"resource_types(self, resource): \"\"\"Populate resource types.\"\"\" # Check to see if all_resources is already",
"if JSON data not found except json.JSONDecodeError as error: self.logger.error(error) sys.exit(1) # Log",
"\"\"\"Populate resource types.\"\"\" # Check to see if all_resources is already populated with",
"to the tfstate directory os.chdir(self.tfstatedir) try: # Try to load JSON output from",
"# Capture current working directory prior to changing to the # tfstate directory.",
"already populated with resource type resource_type_lookup = self.all_resources.get(resource[\"type\"]) # Add resource type to",
"time. self.logger.info(\"terraform_version: %s\", terraform_version) # Capture resources to parse resources = data.get(\"resources\") if",
"self.tfstate) try: # Open tfstate file with open(self.tfstate, \"r\") as stream: # Load",
"os.chdir(self.tfstatedir) try: # Try to load JSON output from terraform state pull command",
"= [] modules = data.get(\"modules\") if modules is not None: resources = modules[0].get(\"resources\")",
"older Terraform versions elif isinstance(resources, dict): for resource, resource_config in resources.items(): self.resource_types(resource_config) self.all_resources[resource_config[\"type\"]].append(",
"Attempt to load tfstate from directory using terraform state pull else: # Log",
"try: # Try to load JSON output from terraform state pull command data",
"terraform_version = data.get(\"terraform_version\") # Log Terraform version for additional logic if needed. Not",
"path self.logger.info(\"Loading --tfstate %s\", self.tfstate) try: # Open tfstate file with open(self.tfstate, \"r\")",
"working directory os.chdir(current_dir) # Log and exit if file/directory not found except FileNotFoundError",
"= modules[0].get(\"resources\") return resources def parse(self): \"\"\"Parse Terraform tfstate file.\"\"\" # Load resources",
"for instance in instances: self.all_resources[resource[\"type\"]].append( instance[\"attributes\"] ) # Check if resources are a",
"= args.tfstate # Define Terraform tfstate directory to load self.tfstatedir = args.tfstatedir #",
"Change back to the original current working directory os.chdir(current_dir) # Log and exit",
"Check if resources are a list - newer Terraform versions if isinstance(resources, list):",
"directory using terraform state pull else: # Log tfstate directory self.logger.info(\"Loading --tfstatedir %s\",",
"if resources are a list - newer Terraform versions if isinstance(resources, list): for",
"in resources: self.resource_types(resource) instances = resource.get(\"instances\") if instances is not None: for instance",
"to load tfstate file directly if self.tfstate is not None: # Log tfstate",
"self.resource_types(resource) instances = resource.get(\"instances\") if instances is not None: for instance in instances:",
"load self.tfstatedir = args.tfstatedir # Setup logging self.logger = logging.getLogger(__name__) def load(self): \"\"\"Load",
"and exit if file/directory not found except FileNotFoundError as error: self.logger.error(error) sys.exit(1) #",
"to load JSON output from terraform state pull command data = json.loads( subprocess.getoutput(\"terraform",
"tfstate file path self.logger.info(\"Loading --tfstate %s\", self.tfstate) try: # Open tfstate file with",
"JSON data try: data = json.load(stream) # Log and exit if JSON data",
"Define Terraform tfstate directory to load self.tfstatedir = args.tfstatedir # Setup logging self.logger",
"resource type to all resources if not found in lookup if resource_type_lookup is",
"if instances is not None: for instance in instances: self.all_resources[resource[\"type\"]].append( instance[\"attributes\"] ) #",
"resources is None: resources = [] modules = data.get(\"modules\") if modules is not",
"%s\", self.tfstatedir) try: # Capture current working directory prior to changing to the",
"tfstate file directly if self.tfstate is not None: # Log tfstate file path",
"to see if all_resources is already populated with resource type resource_type_lookup = self.all_resources.get(resource[\"type\"])",
"modules is not None: resources = modules[0].get(\"resources\") return resources def parse(self): \"\"\"Parse Terraform",
"to parse resources = data.get(\"resources\") if resources is None: resources = [] modules",
"sys.exit(1) # Log and exit if file not found except FileNotFoundError as error:",
"to hold all parsed resources self.all_resources = {} # Define Terraform tfstate file",
"from tfstate terraform_version = data.get(\"terraform_version\") # Log Terraform version for additional logic if",
"back to the original current working directory os.chdir(current_dir) # Log and exit if",
"from terraform state pull command data = json.loads( subprocess.getoutput(\"terraform state pull\") ) #",
"%s\", terraform_version) # Capture resources to parse resources = data.get(\"resources\") if resources is",
"self.resource_types(resource_config) self.all_resources[resource_config[\"type\"]].append( resource_config[\"primary\"][\"attributes\"] ) return self.all_resources def resource_types(self, resource): \"\"\"Populate resource types.\"\"\" #",
"found except FileNotFoundError as error: self.logger.error(error) sys.exit(1) # Attempt to load tfstate from",
"as error: self.logger.error(error) sys.exit(1) # Attempt to load tfstate from directory using terraform",
"current_dir = os.getcwd() # Change to the tfstate directory os.chdir(self.tfstatedir) try: # Try",
"self.all_resources[resource_config[\"type\"]].append( resource_config[\"primary\"][\"attributes\"] ) return self.all_resources def resource_types(self, resource): \"\"\"Populate resource types.\"\"\" # Check",
"# Capture Terraform version from tfstate terraform_version = data.get(\"terraform_version\") # Log Terraform version",
"prior to changing to the # tfstate directory. So, we can changing back.",
"self.tfstate is not None: # Log tfstate file path self.logger.info(\"Loading --tfstate %s\", self.tfstate)",
"resources = [] modules = data.get(\"modules\") if modules is not None: resources =",
"for resource, resource_config in resources.items(): self.resource_types(resource_config) self.all_resources[resource_config[\"type\"]].append( resource_config[\"primary\"][\"attributes\"] ) return self.all_resources def resource_types(self,",
"json.JSONDecodeError as error: self.logger.error(error) sys.exit(1) # Log and exit if file not found",
"version for additional logic if needed. Not used at # this time. self.logger.info(\"terraform_version:",
"if self.tfstate is not None: # Log tfstate file path self.logger.info(\"Loading --tfstate %s\",",
"isinstance(resources, list): for resource in resources: self.resource_types(resource) instances = resource.get(\"instances\") if instances is",
"versions if isinstance(resources, list): for resource in resources: self.resource_types(resource) instances = resource.get(\"instances\") if",
"is None: resources = [] modules = data.get(\"modules\") if modules is not None:",
"the original current working directory os.chdir(current_dir) # Log and exit if file/directory not",
"the tfstate directory os.chdir(self.tfstatedir) try: # Try to load JSON output from terraform",
"is not None: resources = modules[0].get(\"resources\") return resources def parse(self): \"\"\"Parse Terraform tfstate",
"# Try to load JSON output from terraform state pull command data =",
"if resources is None: resources = [] modules = data.get(\"modules\") if modules is",
"args): \"\"\"Init a thing.\"\"\" # Define dictionary to hold all parsed resources self.all_resources",
"resources: self.resource_types(resource) instances = resource.get(\"instances\") if instances is not None: for instance in",
"try: # Capture current working directory prior to changing to the # tfstate",
"# Define dictionary to hold all parsed resources self.all_resources = {} # Define",
"up resources = self.load() # Check if resources are a list - newer",
"# Log and exit if file not found except FileNotFoundError as error: self.logger.error(error)",
"error: self.logger.error(error) sys.exit(1) # Attempt to load tfstate from directory using terraform state",
"tfstate directory self.logger.info(\"Loading --tfstatedir %s\", self.tfstatedir) try: # Capture current working directory prior",
"as stream: # Load JSON data try: data = json.load(stream) # Log and",
"import logging import os import subprocess import sys class Parser: \"\"\"Main Terraform tfstate",
"Terraform tfstate directory to load self.tfstatedir = args.tfstatedir # Setup logging self.logger =",
"self.all_resources[resource[\"type\"]].append( instance[\"attributes\"] ) # Check if resources are a dict - older Terraform",
"modules = data.get(\"modules\") if modules is not None: resources = modules[0].get(\"resources\") return resources",
"thing.\"\"\" # Define dictionary to hold all parsed resources self.all_resources = {} #",
"to the # tfstate directory. So, we can changing back. current_dir = os.getcwd()",
"original current working directory os.chdir(current_dir) # Log and exit if file/directory not found",
"= args.tfstatedir # Setup logging self.logger = logging.getLogger(__name__) def load(self): \"\"\"Load Terraform tfstate",
"load JSON output from terraform state pull command data = json.loads( subprocess.getoutput(\"terraform state",
"self.tfstatedir = args.tfstatedir # Setup logging self.logger = logging.getLogger(__name__) def load(self): \"\"\"Load Terraform",
"parse resources = data.get(\"resources\") if resources is None: resources = [] modules =",
"# Check if resources are a list - newer Terraform versions if isinstance(resources,",
"a thing.\"\"\" # Define dictionary to hold all parsed resources self.all_resources = {}",
"terraform_version) # Capture resources to parse resources = data.get(\"resources\") if resources is None:",
"not None: for instance in instances: self.all_resources[resource[\"type\"]].append( instance[\"attributes\"] ) # Check if resources",
"self.logger.error(error) sys.exit(1) # Change back to the original current working directory os.chdir(current_dir) #",
"self.load() # Check if resources are a list - newer Terraform versions if",
"found except json.JSONDecodeError as error: self.logger.error(error) sys.exit(1) # Log and exit if file",
"exit if JSON data not found except json.decoder.JSONDecodeError as error: self.logger.error(error) sys.exit(1) #",
"parser.\"\"\" def __init__(self, args): \"\"\"Init a thing.\"\"\" # Define dictionary to hold all",
"except json.decoder.JSONDecodeError as error: self.logger.error(error) sys.exit(1) # Change back to the original current",
"file not found except FileNotFoundError as error: self.logger.error(error) sys.exit(1) # Attempt to load",
"data = json.load(stream) # Log and exit if JSON data not found except",
"resources = modules[0].get(\"resources\") return resources def parse(self): \"\"\"Parse Terraform tfstate file.\"\"\" # Load",
"are a list - newer Terraform versions if isinstance(resources, list): for resource in",
"except FileNotFoundError as error: self.logger.error(error) sys.exit(1) # Attempt to load tfstate from directory",
"for resource in resources: self.resource_types(resource) instances = resource.get(\"instances\") if instances is not None:",
"sys.exit(1) # Capture Terraform version from tfstate terraform_version = data.get(\"terraform_version\") # Log Terraform",
"dict - older Terraform versions elif isinstance(resources, dict): for resource, resource_config in resources.items():",
"error: self.logger.error(error) sys.exit(1) # Change back to the original current working directory os.chdir(current_dir)",
"--tfstatedir %s\", self.tfstatedir) try: # Capture current working directory prior to changing to",
"hold all parsed resources self.all_resources = {} # Define Terraform tfstate file to",
"directory prior to changing to the # tfstate directory. So, we can changing",
"tfstate directory to load self.tfstatedir = args.tfstatedir # Setup logging self.logger = logging.getLogger(__name__)",
"file path self.logger.info(\"Loading --tfstate %s\", self.tfstate) try: # Open tfstate file with open(self.tfstate,",
"Log tfstate file path self.logger.info(\"Loading --tfstate %s\", self.tfstate) try: # Open tfstate file",
"list - newer Terraform versions if isinstance(resources, list): for resource in resources: self.resource_types(resource)",
"if JSON data not found except json.decoder.JSONDecodeError as error: self.logger.error(error) sys.exit(1) # Change",
"data not found except json.decoder.JSONDecodeError as error: self.logger.error(error) sys.exit(1) # Change back to",
"resources if not found in lookup if resource_type_lookup is None: self.all_resources[resource[\"type\"]] = []",
"resource type resource_type_lookup = self.all_resources.get(resource[\"type\"]) # Add resource type to all resources if",
"# Log tfstate directory self.logger.info(\"Loading --tfstatedir %s\", self.tfstatedir) try: # Capture current working",
"not None: # Log tfstate file path self.logger.info(\"Loading --tfstate %s\", self.tfstate) try: #",
"isinstance(resources, dict): for resource, resource_config in resources.items(): self.resource_types(resource_config) self.all_resources[resource_config[\"type\"]].append( resource_config[\"primary\"][\"attributes\"] ) return self.all_resources",
"None: resources = modules[0].get(\"resources\") return resources def parse(self): \"\"\"Parse Terraform tfstate file.\"\"\" #",
"--tfstate %s\", self.tfstate) try: # Open tfstate file with open(self.tfstate, \"r\") as stream:",
"not found except FileNotFoundError as error: self.logger.error(error) sys.exit(1) # Attempt to load tfstate",
"if isinstance(resources, list): for resource in resources: self.resource_types(resource) instances = resource.get(\"instances\") if instances",
"directly if self.tfstate is not None: # Log tfstate file path self.logger.info(\"Loading --tfstate",
"# Capture resources to parse resources = data.get(\"resources\") if resources is None: resources",
"error: self.logger.error(error) sys.exit(1) # Log and exit if file not found except FileNotFoundError",
"Terraform versions if isinstance(resources, list): for resource in resources: self.resource_types(resource) instances = resource.get(\"instances\")",
"Setup logging self.logger = logging.getLogger(__name__) def load(self): \"\"\"Load Terraform tfstate file.\"\"\" # Attempt",
"os.getcwd() # Change to the tfstate directory os.chdir(self.tfstatedir) try: # Try to load",
"see if all_resources is already populated with resource type resource_type_lookup = self.all_resources.get(resource[\"type\"]) #",
"if all_resources is already populated with resource type resource_type_lookup = self.all_resources.get(resource[\"type\"]) # Add",
"data = json.loads( subprocess.getoutput(\"terraform state pull\") ) # Log and exit if JSON",
"# Change back to the original current working directory os.chdir(current_dir) # Log and",
"Not used at # this time. self.logger.info(\"terraform_version: %s\", terraform_version) # Capture resources to",
"resources def parse(self): \"\"\"Parse Terraform tfstate file.\"\"\" # Load resources up resources =",
"file with open(self.tfstate, \"r\") as stream: # Load JSON data try: data =",
"resource types.\"\"\" # Check to see if all_resources is already populated with resource",
"resources self.all_resources = {} # Define Terraform tfstate file to load self.tfstate =",
"for additional logic if needed. Not used at # this time. self.logger.info(\"terraform_version: %s\",",
"Try to load JSON output from terraform state pull command data = json.loads(",
"logging self.logger = logging.getLogger(__name__) def load(self): \"\"\"Load Terraform tfstate file.\"\"\" # Attempt to",
"Define Terraform tfstate file to load self.tfstate = args.tfstate # Define Terraform tfstate",
"stream: # Load JSON data try: data = json.load(stream) # Log and exit",
"output from terraform state pull command data = json.loads( subprocess.getoutput(\"terraform state pull\") )",
"resource_type_lookup = self.all_resources.get(resource[\"type\"]) # Add resource type to all resources if not found",
"\"\"\"Main Terraform tfstate parser.\"\"\" def __init__(self, args): \"\"\"Init a thing.\"\"\" # Define dictionary",
"resource in resources: self.resource_types(resource) instances = resource.get(\"instances\") if instances is not None: for",
"json import logging import os import subprocess import sys class Parser: \"\"\"Main Terraform",
"exit if file/directory not found except FileNotFoundError as error: self.logger.error(error) sys.exit(1) # Capture",
"data.get(\"resources\") if resources is None: resources = [] modules = data.get(\"modules\") if modules",
"Define dictionary to hold all parsed resources self.all_resources = {} # Define Terraform",
"return resources def parse(self): \"\"\"Parse Terraform tfstate file.\"\"\" # Load resources up resources",
"json.loads( subprocess.getoutput(\"terraform state pull\") ) # Log and exit if JSON data not",
"terraform state pull command data = json.loads( subprocess.getoutput(\"terraform state pull\") ) # Log",
"None: for instance in instances: self.all_resources[resource[\"type\"]].append( instance[\"attributes\"] ) # Check if resources are",
"Terraform tfstate file.\"\"\" # Attempt to load tfstate file directly if self.tfstate is",
"- older Terraform versions elif isinstance(resources, dict): for resource, resource_config in resources.items(): self.resource_types(resource_config)",
"to changing to the # tfstate directory. So, we can changing back. current_dir",
"except FileNotFoundError as error: self.logger.error(error) sys.exit(1) # Capture Terraform version from tfstate terraform_version",
"resources = data.get(\"resources\") if resources is None: resources = [] modules = data.get(\"modules\")",
"import sys class Parser: \"\"\"Main Terraform tfstate parser.\"\"\" def __init__(self, args): \"\"\"Init a",
"can changing back. current_dir = os.getcwd() # Change to the tfstate directory os.chdir(self.tfstatedir)",
"# Define Terraform tfstate directory to load self.tfstatedir = args.tfstatedir # Setup logging",
"pull\") ) # Log and exit if JSON data not found except json.decoder.JSONDecodeError",
"= json.load(stream) # Log and exit if JSON data not found except json.JSONDecodeError",
"import os import subprocess import sys class Parser: \"\"\"Main Terraform tfstate parser.\"\"\" def",
"if file not found except FileNotFoundError as error: self.logger.error(error) sys.exit(1) # Attempt to",
"needed. Not used at # this time. self.logger.info(\"terraform_version: %s\", terraform_version) # Capture resources",
"load(self): \"\"\"Load Terraform tfstate file.\"\"\" # Attempt to load tfstate file directly if",
"with resource type resource_type_lookup = self.all_resources.get(resource[\"type\"]) # Add resource type to all resources",
"def __init__(self, args): \"\"\"Init a thing.\"\"\" # Define dictionary to hold all parsed",
"type to all resources if not found in lookup if resource_type_lookup is None:",
"tfstate file.\"\"\" # Attempt to load tfstate file directly if self.tfstate is not",
"instances: self.all_resources[resource[\"type\"]].append( instance[\"attributes\"] ) # Check if resources are a dict - older",
"to load self.tfstatedir = args.tfstatedir # Setup logging self.logger = logging.getLogger(__name__) def load(self):",
"types.\"\"\" # Check to see if all_resources is already populated with resource type",
"# Log and exit if file/directory not found except FileNotFoundError as error: self.logger.error(error)",
"type resource_type_lookup = self.all_resources.get(resource[\"type\"]) # Add resource type to all resources if not",
"if file/directory not found except FileNotFoundError as error: self.logger.error(error) sys.exit(1) # Capture Terraform",
"return self.all_resources def resource_types(self, resource): \"\"\"Populate resource types.\"\"\" # Check to see if",
"logic if needed. Not used at # this time. self.logger.info(\"terraform_version: %s\", terraform_version) #",
"and exit if JSON data not found except json.decoder.JSONDecodeError as error: self.logger.error(error) sys.exit(1)",
"def load(self): \"\"\"Load Terraform tfstate file.\"\"\" # Attempt to load tfstate file directly",
"parse(self): \"\"\"Parse Terraform tfstate file.\"\"\" # Load resources up resources = self.load() #",
"if resources are a dict - older Terraform versions elif isinstance(resources, dict): for",
"resources are a dict - older Terraform versions elif isinstance(resources, dict): for resource,",
"JSON data not found except json.JSONDecodeError as error: self.logger.error(error) sys.exit(1) # Log and",
"None: resources = [] modules = data.get(\"modules\") if modules is not None: resources",
"self.logger.error(error) sys.exit(1) # Capture Terraform version from tfstate terraform_version = data.get(\"terraform_version\") # Log",
"# Log and exit if JSON data not found except json.decoder.JSONDecodeError as error:",
"= logging.getLogger(__name__) def load(self): \"\"\"Load Terraform tfstate file.\"\"\" # Attempt to load tfstate",
"logging.getLogger(__name__) def load(self): \"\"\"Load Terraform tfstate file.\"\"\" # Attempt to load tfstate file",
"tfstate file to load self.tfstate = args.tfstate # Define Terraform tfstate directory to",
"# Define Terraform tfstate file to load self.tfstate = args.tfstate # Define Terraform",
"to load self.tfstate = args.tfstate # Define Terraform tfstate directory to load self.tfstatedir",
"args.tfstate # Define Terraform tfstate directory to load self.tfstatedir = args.tfstatedir # Setup",
"tfstate directory os.chdir(self.tfstatedir) try: # Try to load JSON output from terraform state",
"= resource.get(\"instances\") if instances is not None: for instance in instances: self.all_resources[resource[\"type\"]].append( instance[\"attributes\"]",
"are a dict - older Terraform versions elif isinstance(resources, dict): for resource, resource_config",
"file.\"\"\" # Attempt to load tfstate file directly if self.tfstate is not None:",
"Log and exit if JSON data not found except json.JSONDecodeError as error: self.logger.error(error)",
"command data = json.loads( subprocess.getoutput(\"terraform state pull\") ) # Log and exit if",
"version from tfstate terraform_version = data.get(\"terraform_version\") # Log Terraform version for additional logic",
"found except json.decoder.JSONDecodeError as error: self.logger.error(error) sys.exit(1) # Change back to the original",
"- newer Terraform versions if isinstance(resources, list): for resource in resources: self.resource_types(resource) instances",
"a list - newer Terraform versions if isinstance(resources, list): for resource in resources:",
"# Attempt to load tfstate file directly if self.tfstate is not None: #",
"Change to the tfstate directory os.chdir(self.tfstatedir) try: # Try to load JSON output",
"# Log Terraform version for additional logic if needed. Not used at #",
"directory. So, we can changing back. current_dir = os.getcwd() # Change to the",
"a dict - older Terraform versions elif isinstance(resources, dict): for resource, resource_config in",
"def resource_types(self, resource): \"\"\"Populate resource types.\"\"\" # Check to see if all_resources is",
"# Log tfstate file path self.logger.info(\"Loading --tfstate %s\", self.tfstate) try: # Open tfstate",
"json.load(stream) # Log and exit if JSON data not found except json.JSONDecodeError as",
"Check if resources are a dict - older Terraform versions elif isinstance(resources, dict):",
"with open(self.tfstate, \"r\") as stream: # Load JSON data try: data = json.load(stream)",
"exit if JSON data not found except json.JSONDecodeError as error: self.logger.error(error) sys.exit(1) #",
"file/directory not found except FileNotFoundError as error: self.logger.error(error) sys.exit(1) # Capture Terraform version",
"all resources if not found in lookup if resource_type_lookup is None: self.all_resources[resource[\"type\"]] =",
"directory self.logger.info(\"Loading --tfstatedir %s\", self.tfstatedir) try: # Capture current working directory prior to",
"resources to parse resources = data.get(\"resources\") if resources is None: resources = []",
"json.decoder.JSONDecodeError as error: self.logger.error(error) sys.exit(1) # Change back to the original current working",
"if needed. Not used at # this time. self.logger.info(\"terraform_version: %s\", terraform_version) # Capture",
") return self.all_resources def resource_types(self, resource): \"\"\"Populate resource types.\"\"\" # Check to see",
"parsed resources self.all_resources = {} # Define Terraform tfstate file to load self.tfstate",
"all_resources is already populated with resource type resource_type_lookup = self.all_resources.get(resource[\"type\"]) # Add resource",
"\"\"\"Init a thing.\"\"\" # Define dictionary to hold all parsed resources self.all_resources =",
"subprocess.getoutput(\"terraform state pull\") ) # Log and exit if JSON data not found",
"pull command data = json.loads( subprocess.getoutput(\"terraform state pull\") ) # Log and exit",
"Terraform tfstate file.\"\"\" # Load resources up resources = self.load() # Check if",
"\"r\") as stream: # Load JSON data try: data = json.load(stream) # Log",
"Log and exit if JSON data not found except json.decoder.JSONDecodeError as error: self.logger.error(error)",
"resources.items(): self.resource_types(resource_config) self.all_resources[resource_config[\"type\"]].append( resource_config[\"primary\"][\"attributes\"] ) return self.all_resources def resource_types(self, resource): \"\"\"Populate resource types.\"\"\"",
"open(self.tfstate, \"r\") as stream: # Load JSON data try: data = json.load(stream) #",
"import subprocess import sys class Parser: \"\"\"Main Terraform tfstate parser.\"\"\" def __init__(self, args):",
"we can changing back. current_dir = os.getcwd() # Change to the tfstate directory",
"[] modules = data.get(\"modules\") if modules is not None: resources = modules[0].get(\"resources\") return",
"data.get(\"modules\") if modules is not None: resources = modules[0].get(\"resources\") return resources def parse(self):",
"resources up resources = self.load() # Check if resources are a list -",
"self.logger.info(\"Loading --tfstate %s\", self.tfstate) try: # Open tfstate file with open(self.tfstate, \"r\") as",
"is not None: # Log tfstate file path self.logger.info(\"Loading --tfstate %s\", self.tfstate) try:",
"Capture Terraform version from tfstate terraform_version = data.get(\"terraform_version\") # Log Terraform version for",
"and exit if JSON data not found except json.JSONDecodeError as error: self.logger.error(error) sys.exit(1)",
"# this time. self.logger.info(\"terraform_version: %s\", terraform_version) # Capture resources to parse resources =",
"args.tfstatedir # Setup logging self.logger = logging.getLogger(__name__) def load(self): \"\"\"Load Terraform tfstate file.\"\"\"",
"tfstate terraform_version = data.get(\"terraform_version\") # Log Terraform version for additional logic if needed.",
"exit if file not found except FileNotFoundError as error: self.logger.error(error) sys.exit(1) # Attempt",
"terraform state pull else: # Log tfstate directory self.logger.info(\"Loading --tfstatedir %s\", self.tfstatedir) try:",
"else: # Log tfstate directory self.logger.info(\"Loading --tfstatedir %s\", self.tfstatedir) try: # Capture current",
"load self.tfstate = args.tfstate # Define Terraform tfstate directory to load self.tfstatedir =",
"self.tfstatedir) try: # Capture current working directory prior to changing to the #",
"modules[0].get(\"resources\") return resources def parse(self): \"\"\"Parse Terraform tfstate file.\"\"\" # Load resources up",
"tfstate file.\"\"\" # Load resources up resources = self.load() # Check if resources",
"= data.get(\"terraform_version\") # Log Terraform version for additional logic if needed. Not used",
"Load JSON data try: data = json.load(stream) # Log and exit if JSON",
"not found except json.decoder.JSONDecodeError as error: self.logger.error(error) sys.exit(1) # Change back to the",
"using terraform state pull else: # Log tfstate directory self.logger.info(\"Loading --tfstatedir %s\", self.tfstatedir)",
"# Load JSON data try: data = json.load(stream) # Log and exit if",
"None: # Log tfstate file path self.logger.info(\"Loading --tfstate %s\", self.tfstate) try: # Open",
"# Setup logging self.logger = logging.getLogger(__name__) def load(self): \"\"\"Load Terraform tfstate file.\"\"\" #",
"in resources.items(): self.resource_types(resource_config) self.all_resources[resource_config[\"type\"]].append( resource_config[\"primary\"][\"attributes\"] ) return self.all_resources def resource_types(self, resource): \"\"\"Populate resource",
"tfstate parser.\"\"\" def __init__(self, args): \"\"\"Init a thing.\"\"\" # Define dictionary to hold",
"# Check to see if all_resources is already populated with resource type resource_type_lookup",
"resource, resource_config in resources.items(): self.resource_types(resource_config) self.all_resources[resource_config[\"type\"]].append( resource_config[\"primary\"][\"attributes\"] ) return self.all_resources def resource_types(self, resource):",
"pull else: # Log tfstate directory self.logger.info(\"Loading --tfstatedir %s\", self.tfstatedir) try: # Capture",
"# Attempt to load tfstate from directory using terraform state pull else: #",
"data try: data = json.load(stream) # Log and exit if JSON data not",
"class Parser: \"\"\"Main Terraform tfstate parser.\"\"\" def __init__(self, args): \"\"\"Init a thing.\"\"\" #",
"all parsed resources self.all_resources = {} # Define Terraform tfstate file to load",
"self.logger.info(\"Loading --tfstatedir %s\", self.tfstatedir) try: # Capture current working directory prior to changing",
"is already populated with resource type resource_type_lookup = self.all_resources.get(resource[\"type\"]) # Add resource type",
"instance[\"attributes\"] ) # Check if resources are a dict - older Terraform versions",
"# Check if resources are a dict - older Terraform versions elif isinstance(resources,",
"state pull else: # Log tfstate directory self.logger.info(\"Loading --tfstatedir %s\", self.tfstatedir) try: #",
"self.logger.info(\"terraform_version: %s\", terraform_version) # Capture resources to parse resources = data.get(\"resources\") if resources",
"the # tfstate directory. So, we can changing back. current_dir = os.getcwd() #",
"# Load resources up resources = self.load() # Check if resources are a",
"error: self.logger.error(error) sys.exit(1) # Capture Terraform version from tfstate terraform_version = data.get(\"terraform_version\") #",
"Parser: \"\"\"Main Terraform tfstate parser.\"\"\" def __init__(self, args): \"\"\"Init a thing.\"\"\" # Define",
"instances is not None: for instance in instances: self.all_resources[resource[\"type\"]].append( instance[\"attributes\"] ) # Check",
"Add resource type to all resources if not found in lookup if resource_type_lookup",
"# Log and exit if JSON data not found except json.JSONDecodeError as error:",
"sys.exit(1) # Attempt to load tfstate from directory using terraform state pull else:",
") # Check if resources are a dict - older Terraform versions elif",
"try: # Open tfstate file with open(self.tfstate, \"r\") as stream: # Load JSON",
") # Log and exit if JSON data not found except json.decoder.JSONDecodeError as",
"Open tfstate file with open(self.tfstate, \"r\") as stream: # Load JSON data try:",
"except json.JSONDecodeError as error: self.logger.error(error) sys.exit(1) # Log and exit if file not",
"self.logger.error(error) sys.exit(1) # Log and exit if file not found except FileNotFoundError as",
"elif isinstance(resources, dict): for resource, resource_config in resources.items(): self.resource_types(resource_config) self.all_resources[resource_config[\"type\"]].append( resource_config[\"primary\"][\"attributes\"] ) return",
"Log and exit if file not found except FileNotFoundError as error: self.logger.error(error) sys.exit(1)",
"working directory prior to changing to the # tfstate directory. So, we can",
"\"\"\"Load Terraform tfstate file.\"\"\" # Attempt to load tfstate file directly if self.tfstate",
"So, we can changing back. current_dir = os.getcwd() # Change to the tfstate",
"= os.getcwd() # Change to the tfstate directory os.chdir(self.tfstatedir) try: # Try to",
"is not None: for instance in instances: self.all_resources[resource[\"type\"]].append( instance[\"attributes\"] ) # Check if",
"not found except FileNotFoundError as error: self.logger.error(error) sys.exit(1) # Capture Terraform version from",
"FileNotFoundError as error: self.logger.error(error) sys.exit(1) # Attempt to load tfstate from directory using",
"load tfstate from directory using terraform state pull else: # Log tfstate directory",
"instances = resource.get(\"instances\") if instances is not None: for instance in instances: self.all_resources[resource[\"type\"]].append(",
"current working directory os.chdir(current_dir) # Log and exit if file/directory not found except",
"to load tfstate from directory using terraform state pull else: # Log tfstate",
"= self.all_resources.get(resource[\"type\"]) # Add resource type to all resources if not found in",
"as error: self.logger.error(error) sys.exit(1) # Change back to the original current working directory",
"if modules is not None: resources = modules[0].get(\"resources\") return resources def parse(self): \"\"\"Parse",
"directory os.chdir(current_dir) # Log and exit if file/directory not found except FileNotFoundError as",
"at # this time. self.logger.info(\"terraform_version: %s\", terraform_version) # Capture resources to parse resources",
"%s\", self.tfstate) try: # Open tfstate file with open(self.tfstate, \"r\") as stream: #",
"# Change to the tfstate directory os.chdir(self.tfstatedir) try: # Try to load JSON",
"Load resources up resources = self.load() # Check if resources are a list",
"self.logger.error(error) sys.exit(1) # Attempt to load tfstate from directory using terraform state pull",
"changing to the # tfstate directory. So, we can changing back. current_dir =",
"as error: self.logger.error(error) sys.exit(1) # Log and exit if file not found except",
"load tfstate file directly if self.tfstate is not None: # Log tfstate file",
"list): for resource in resources: self.resource_types(resource) instances = resource.get(\"instances\") if instances is not",
"= data.get(\"modules\") if modules is not None: resources = modules[0].get(\"resources\") return resources def",
"# tfstate directory. So, we can changing back. current_dir = os.getcwd() # Change",
"instance in instances: self.all_resources[resource[\"type\"]].append( instance[\"attributes\"] ) # Check if resources are a dict",
"= self.load() # Check if resources are a list - newer Terraform versions",
"try: data = json.load(stream) # Log and exit if JSON data not found",
"in instances: self.all_resources[resource[\"type\"]].append( instance[\"attributes\"] ) # Check if resources are a dict -",
"Terraform tfstate parser.\"\"\" def __init__(self, args): \"\"\"Init a thing.\"\"\" # Define dictionary to",
"dictionary to hold all parsed resources self.all_resources = {} # Define Terraform tfstate",
"Terraform version from tfstate terraform_version = data.get(\"terraform_version\") # Log Terraform version for additional",
"directory os.chdir(self.tfstatedir) try: # Try to load JSON output from terraform state pull",
"os.chdir(current_dir) # Log and exit if file/directory not found except FileNotFoundError as error:",
"Capture resources to parse resources = data.get(\"resources\") if resources is None: resources =",
"Terraform version for additional logic if needed. Not used at # this time.",
"Log Terraform version for additional logic if needed. Not used at # this",
"self.logger = logging.getLogger(__name__) def load(self): \"\"\"Load Terraform tfstate file.\"\"\" # Attempt to load",
"directory to load self.tfstatedir = args.tfstatedir # Setup logging self.logger = logging.getLogger(__name__) def",
"data not found except json.JSONDecodeError as error: self.logger.error(error) sys.exit(1) # Log and exit",
"changing back. current_dir = os.getcwd() # Change to the tfstate directory os.chdir(self.tfstatedir) try:",
"__init__(self, args): \"\"\"Init a thing.\"\"\" # Define dictionary to hold all parsed resources",
"\"\"\"terraform_to_ansible/parser.py\"\"\" import json import logging import os import subprocess import sys class Parser:",
"Log and exit if file/directory not found except FileNotFoundError as error: self.logger.error(error) sys.exit(1)",
"file to load self.tfstate = args.tfstate # Define Terraform tfstate directory to load",
"\"\"\"Parse Terraform tfstate file.\"\"\" # Load resources up resources = self.load() # Check",
"os import subprocess import sys class Parser: \"\"\"Main Terraform tfstate parser.\"\"\" def __init__(self,",
"self.all_resources = {} # Define Terraform tfstate file to load self.tfstate = args.tfstate",
"JSON output from terraform state pull command data = json.loads( subprocess.getoutput(\"terraform state pull\")",
"as error: self.logger.error(error) sys.exit(1) # Capture Terraform version from tfstate terraform_version = data.get(\"terraform_version\")",
"resources = self.load() # Check if resources are a list - newer Terraform",
"not found except json.JSONDecodeError as error: self.logger.error(error) sys.exit(1) # Log and exit if",
"additional logic if needed. Not used at # this time. self.logger.info(\"terraform_version: %s\", terraform_version)",
"= data.get(\"resources\") if resources is None: resources = [] modules = data.get(\"modules\") if",
"def parse(self): \"\"\"Parse Terraform tfstate file.\"\"\" # Load resources up resources = self.load()",
"resource_config[\"primary\"][\"attributes\"] ) return self.all_resources def resource_types(self, resource): \"\"\"Populate resource types.\"\"\" # Check to",
"Capture current working directory prior to changing to the # tfstate directory. So,",
"state pull command data = json.loads( subprocess.getoutput(\"terraform state pull\") ) # Log and",
"tfstate directory. So, we can changing back. current_dir = os.getcwd() # Change to",
"Log tfstate directory self.logger.info(\"Loading --tfstatedir %s\", self.tfstatedir) try: # Capture current working directory",
"Terraform versions elif isinstance(resources, dict): for resource, resource_config in resources.items(): self.resource_types(resource_config) self.all_resources[resource_config[\"type\"]].append( resource_config[\"primary\"][\"attributes\"]",
"resource_config in resources.items(): self.resource_types(resource_config) self.all_resources[resource_config[\"type\"]].append( resource_config[\"primary\"][\"attributes\"] ) return self.all_resources def resource_types(self, resource): \"\"\"Populate",
"this time. self.logger.info(\"terraform_version: %s\", terraform_version) # Capture resources to parse resources = data.get(\"resources\")",
"Attempt to load tfstate file directly if self.tfstate is not None: # Log",
"subprocess import sys class Parser: \"\"\"Main Terraform tfstate parser.\"\"\" def __init__(self, args): \"\"\"Init",
"data.get(\"terraform_version\") # Log Terraform version for additional logic if needed. Not used at",
"Check to see if all_resources is already populated with resource type resource_type_lookup =",
"import json import logging import os import subprocess import sys class Parser: \"\"\"Main",
"Terraform tfstate file to load self.tfstate = args.tfstate # Define Terraform tfstate directory",
"not None: resources = modules[0].get(\"resources\") return resources def parse(self): \"\"\"Parse Terraform tfstate file.\"\"\"",
"resources are a list - newer Terraform versions if isinstance(resources, list): for resource"
] |
[
"grouped timeseries\", author=\"<NAME>\", author_email=\"<EMAIL>\", url=\"http://github.com/sam-bailey/tyme\", packages=find_packages(where=\"src\"), package_dir={\"\": \"src\"}, cmdclass=cmdclass, ext_modules=ext_modules, include_dirs=[numpy.get_include()], long_description=open(\"README.md\").read(), install_requires=requirements,",
"-> str: return self.path + \".pyx\" @property def c(self) -> str: return self.path",
"= name self.path = path @property def name(self) -> str: return self._name @name.setter",
"== \"auto\": USE_CYTHON = False else: raise class CythonModule(object): def __init__(self, name: str,",
"] cmdclass = dict(build_ext=build_ext, sdist=sdist) else: ext_modules = [ Extension(module.name, [module.c]) for module",
"requirements_dev = [\"pytest\", \"pytest-cov\", \"Cython\", \"pre-commit\", \"tox\"] setup( name=\"tyme\", # version=\"0.1.0\", description=\"A timeseries",
"cmdclass = {} requirements = [ \"Bottleneck\", \"cycler\", \"kiwisolver\", \"numpy\", \"pandas\", \"Pillow\", \"pyparsing\",",
"cythonize([module.pyx for module in cython_modules]) _sdist.run(self) ext_modules = [ Extension(module.name, [module.pyx]) for module",
"3\", \"Programming Language :: Python :: 3.1\", \"Programming Language :: Python :: 3.2\",",
"numpy USE_CYTHON = \"auto\" if USE_CYTHON: try: from Cython.Distutils import build_ext from Cython.Build",
"\"Programming Language :: Python :: 3.2\", \"Programming Language :: Python :: 3.3\", \"Programming",
"\"pyparsing\", \"python-dateutil\", \"pytz\", \"six\", \"scipy\", \"Cython\", ] requirements_dev = [\"pytest\", \"pytest-cov\", \"Cython\", \"pre-commit\",",
"if USE_CYTHON == \"auto\": USE_CYTHON = False else: raise class CythonModule(object): def __init__(self,",
"@property def path(self) -> str: return self._path @path.setter def path(self, path: str) ->",
"description=\"A timeseries forecasting package, specialised in forecasting grouped timeseries\", author=\"<NAME>\", author_email=\"<EMAIL>\", url=\"http://github.com/sam-bailey/tyme\", packages=find_packages(where=\"src\"),",
":: 3.6\", \"Programming Language :: Python :: 3.7\", \"Programming Language :: Python ::",
"path @property def pyx(self) -> str: return self.path + \".pyx\" @property def c(self)",
"Cython files in the distribution are up-to-date cythonize([module.pyx for module in cython_modules]) _sdist.run(self)",
"\"Programming Language :: Python :: 3.3\", \"Programming Language :: Python :: 3.4\", \"Programming",
"include_dirs=[numpy.get_include()], long_description=open(\"README.md\").read(), install_requires=requirements, extras_require={\"dev\": requirements_dev}, license=\"MIT\", classifiers=[ \"Development Status :: 4 - Beta\",",
"= name @property def path(self) -> str: return self._path @path.setter def path(self, path:",
"compiled Cython files in the distribution are up-to-date cythonize([module.pyx for module in cython_modules])",
"setup, find_packages, Extension from distutils.command.sdist import sdist as _sdist import numpy USE_CYTHON =",
"\"numpy\", \"pandas\", \"Pillow\", \"pyparsing\", \"python-dateutil\", \"pytz\", \"six\", \"scipy\", \"Cython\", ] requirements_dev = [\"pytest\",",
"Set this to True to enable building extensions using Cython. # Set it",
"\"six\", \"scipy\", \"Cython\", ] requirements_dev = [\"pytest\", \"pytest-cov\", \"Cython\", \"pre-commit\", \"tox\"] setup( name=\"tyme\",",
":: Cython\", \"Topic :: Scientific/Engineering :: Mathematics\", ], keywords=\"timeseries forecast forecasting time\", )",
"raise Exception(\"Python 2.x is no longer supported\") if USE_CYTHON: class sdist(_sdist): def run(self):",
"ext_modules = [ Extension(module.name, [module.c]) for module in cython_modules ] cmdclass = {}",
"USE_CYTHON == \"auto\": USE_CYTHON = False else: raise class CythonModule(object): def __init__(self, name:",
"return self._name @name.setter def name(self, name: str) -> None: self._name = name @property",
"- Beta\", \"Intended Audience :: Developers\", \"License :: OSI Approved :: MIT License\",",
":: 3.1\", \"Programming Language :: Python :: 3.2\", \"Programming Language :: Python ::",
":: Python\", \"Programming Language :: Python :: 3\", \"Programming Language :: Python ::",
"= [ CythonModule( name=\"tyme.base_forecasters.exponential_smoothing_cy\", path=\"src/cython/exponential_smoothing_cy\", ), CythonModule( name=\"tyme.base_forecasters.robust_exponential_smoothing_cy\", path=\"src/cython/robust_exponential_smoothing_cy\", ), ] if sys.version_info[0]",
"\"Programming Language :: Python :: 3.4\", \"Programming Language :: Python :: 3.5\", \"Programming",
"= [ \"Bottleneck\", \"cycler\", \"kiwisolver\", \"numpy\", \"pandas\", \"Pillow\", \"pyparsing\", \"python-dateutil\", \"pytz\", \"six\", \"scipy\",",
"USE_CYTHON: try: from Cython.Distutils import build_ext from Cython.Build import cythonize except ImportError: if",
"Python :: 3.4\", \"Programming Language :: Python :: 3.5\", \"Programming Language :: Python",
"url=\"http://github.com/sam-bailey/tyme\", packages=find_packages(where=\"src\"), package_dir={\"\": \"src\"}, cmdclass=cmdclass, ext_modules=ext_modules, include_dirs=[numpy.get_include()], long_description=open(\"README.md\").read(), install_requires=requirements, extras_require={\"dev\": requirements_dev}, license=\"MIT\", classifiers=[",
"_sdist import numpy USE_CYTHON = \"auto\" if USE_CYTHON: try: from Cython.Distutils import build_ext",
"python3 # Set this to True to enable building extensions using Cython. #",
"\"Cython\", ] requirements_dev = [\"pytest\", \"pytest-cov\", \"Cython\", \"pre-commit\", \"tox\"] setup( name=\"tyme\", # version=\"0.1.0\",",
"path @property def name(self) -> str: return self._name @name.setter def name(self, name: str)",
"Extension(module.name, [module.c]) for module in cython_modules ] cmdclass = {} requirements = [",
"enable building extensions using Cython. # Set it to False to build extensions",
"\"Cython\", \"pre-commit\", \"tox\"] setup( name=\"tyme\", # version=\"0.1.0\", description=\"A timeseries forecasting package, specialised in",
"== 2: raise Exception(\"Python 2.x is no longer supported\") if USE_CYTHON: class sdist(_sdist):",
"files in the distribution are up-to-date cythonize([module.pyx for module in cython_modules]) _sdist.run(self) ext_modules",
":: 3.2\", \"Programming Language :: Python :: 3.3\", \"Programming Language :: Python ::",
"import setup, find_packages, Extension from distutils.command.sdist import sdist as _sdist import numpy USE_CYTHON",
"run(self): # Make sure the compiled Cython files in the distribution are up-to-date",
"timeseries\", author=\"<NAME>\", author_email=\"<EMAIL>\", url=\"http://github.com/sam-bailey/tyme\", packages=find_packages(where=\"src\"), package_dir={\"\": \"src\"}, cmdclass=cmdclass, ext_modules=ext_modules, include_dirs=[numpy.get_include()], long_description=open(\"README.md\").read(), install_requires=requirements, extras_require={\"dev\":",
"Python :: 3.6\", \"Programming Language :: Python :: 3.7\", \"Programming Language :: Python",
"file (that # was previously created using Cython). # Set it to 'auto'",
"Cython if available, otherwise # from the C file. import sys from setuptools",
"3.7\", \"Programming Language :: Python :: 3.8\", \"Programming Language :: Cython\", \"Topic ::",
"is no longer supported\") if USE_CYTHON: class sdist(_sdist): def run(self): # Make sure",
"Set it to False to build extensions from the C file (that #",
"path: str) -> None: self._path = path @property def pyx(self) -> str: return",
"ext_modules=ext_modules, include_dirs=[numpy.get_include()], long_description=open(\"README.md\").read(), install_requires=requirements, extras_require={\"dev\": requirements_dev}, license=\"MIT\", classifiers=[ \"Development Status :: 4 -",
"Language :: Cython\", \"Topic :: Scientific/Engineering :: Mathematics\", ], keywords=\"timeseries forecast forecasting time\",",
"cython_modules ] cmdclass = dict(build_ext=build_ext, sdist=sdist) else: ext_modules = [ Extension(module.name, [module.c]) for",
"str: return self.path + \".pyx\" @property def c(self) -> str: return self.path +",
"True to enable building extensions using Cython. # Set it to False to",
"forecasting grouped timeseries\", author=\"<NAME>\", author_email=\"<EMAIL>\", url=\"http://github.com/sam-bailey/tyme\", packages=find_packages(where=\"src\"), package_dir={\"\": \"src\"}, cmdclass=cmdclass, ext_modules=ext_modules, include_dirs=[numpy.get_include()], long_description=open(\"README.md\").read(),",
"Language :: Python :: 3.2\", \"Programming Language :: Python :: 3.3\", \"Programming Language",
"\"Programming Language :: Python :: 3.7\", \"Programming Language :: Python :: 3.8\", \"Programming",
"{} requirements = [ \"Bottleneck\", \"cycler\", \"kiwisolver\", \"numpy\", \"pandas\", \"Pillow\", \"pyparsing\", \"python-dateutil\", \"pytz\",",
"setuptools import setup, find_packages, Extension from distutils.command.sdist import sdist as _sdist import numpy",
"path(self, path: str) -> None: self._path = path @property def pyx(self) -> str:",
"Cython. # Set it to False to build extensions from the C file",
"CythonModule( name=\"tyme.base_forecasters.exponential_smoothing_cy\", path=\"src/cython/exponential_smoothing_cy\", ), CythonModule( name=\"tyme.base_forecasters.robust_exponential_smoothing_cy\", path=\"src/cython/robust_exponential_smoothing_cy\", ), ] if sys.version_info[0] == 2:",
"\"Programming Language :: Cython\", \"Topic :: Scientific/Engineering :: Mathematics\", ], keywords=\"timeseries forecast forecasting",
"requirements_dev}, license=\"MIT\", classifiers=[ \"Development Status :: 4 - Beta\", \"Intended Audience :: Developers\",",
"Python :: 3.1\", \"Programming Language :: Python :: 3.2\", \"Programming Language :: Python",
"Python :: 3\", \"Programming Language :: Python :: 3.1\", \"Programming Language :: Python",
"None: self._name = name @property def path(self) -> str: return self._path @path.setter def",
"for module in cython_modules ] cmdclass = {} requirements = [ \"Bottleneck\", \"cycler\",",
"package, specialised in forecasting grouped timeseries\", author=\"<NAME>\", author_email=\"<EMAIL>\", url=\"http://github.com/sam-bailey/tyme\", packages=find_packages(where=\"src\"), package_dir={\"\": \"src\"}, cmdclass=cmdclass,",
"supported\") if USE_CYTHON: class sdist(_sdist): def run(self): # Make sure the compiled Cython",
"# from the C file. import sys from setuptools import setup, find_packages, Extension",
"\"auto\": USE_CYTHON = False else: raise class CythonModule(object): def __init__(self, name: str, path:",
"previously created using Cython). # Set it to 'auto' to build with Cython",
"author=\"<NAME>\", author_email=\"<EMAIL>\", url=\"http://github.com/sam-bailey/tyme\", packages=find_packages(where=\"src\"), package_dir={\"\": \"src\"}, cmdclass=cmdclass, ext_modules=ext_modules, include_dirs=[numpy.get_include()], long_description=open(\"README.md\").read(), install_requires=requirements, extras_require={\"dev\": requirements_dev},",
"3.3\", \"Programming Language :: Python :: 3.4\", \"Programming Language :: Python :: 3.5\",",
"dict(build_ext=build_ext, sdist=sdist) else: ext_modules = [ Extension(module.name, [module.c]) for module in cython_modules ]",
"\"tox\"] setup( name=\"tyme\", # version=\"0.1.0\", description=\"A timeseries forecasting package, specialised in forecasting grouped",
":: 3.4\", \"Programming Language :: Python :: 3.5\", \"Programming Language :: Python ::",
"to enable building extensions using Cython. # Set it to False to build",
"build extensions from the C file (that # was previously created using Cython).",
"build with Cython if available, otherwise # from the C file. import sys",
"= [ Extension(module.name, [module.pyx]) for module in cython_modules ] cmdclass = dict(build_ext=build_ext, sdist=sdist)",
"from setuptools import setup, find_packages, Extension from distutils.command.sdist import sdist as _sdist import",
"Set it to 'auto' to build with Cython if available, otherwise # from",
"str: return self._name @name.setter def name(self, name: str) -> None: self._name = name",
"if USE_CYTHON: try: from Cython.Distutils import build_ext from Cython.Build import cythonize except ImportError:",
":: Python :: 3.1\", \"Programming Language :: Python :: 3.2\", \"Programming Language ::",
"str): self.name = name self.path = path @property def name(self) -> str: return",
"pyx(self) -> str: return self.path + \".pyx\" @property def c(self) -> str: return",
"def run(self): # Make sure the compiled Cython files in the distribution are",
"-> str: return self._path @path.setter def path(self, path: str) -> None: self._path =",
"was previously created using Cython). # Set it to 'auto' to build with",
"Python :: 3.5\", \"Programming Language :: Python :: 3.6\", \"Programming Language :: Python",
"[ Extension(module.name, [module.pyx]) for module in cython_modules ] cmdclass = dict(build_ext=build_ext, sdist=sdist) else:",
"Approved :: MIT License\", \"Programming Language :: Python\", \"Programming Language :: Python ::",
"), ] if sys.version_info[0] == 2: raise Exception(\"Python 2.x is no longer supported\")",
"[module.c]) for module in cython_modules ] cmdclass = {} requirements = [ \"Bottleneck\",",
"Language :: Python :: 3.3\", \"Programming Language :: Python :: 3.4\", \"Programming Language",
"-> str: return self._name @name.setter def name(self, name: str) -> None: self._name =",
"name=\"tyme\", # version=\"0.1.0\", description=\"A timeseries forecasting package, specialised in forecasting grouped timeseries\", author=\"<NAME>\",",
"def c(self) -> str: return self.path + \".c\" cython_modules = [ CythonModule( name=\"tyme.base_forecasters.exponential_smoothing_cy\",",
"distribution are up-to-date cythonize([module.pyx for module in cython_modules]) _sdist.run(self) ext_modules = [ Extension(module.name,",
"sdist=sdist) else: ext_modules = [ Extension(module.name, [module.c]) for module in cython_modules ] cmdclass",
"for module in cython_modules]) _sdist.run(self) ext_modules = [ Extension(module.name, [module.pyx]) for module in",
"install_requires=requirements, extras_require={\"dev\": requirements_dev}, license=\"MIT\", classifiers=[ \"Development Status :: 4 - Beta\", \"Intended Audience",
"file. import sys from setuptools import setup, find_packages, Extension from distutils.command.sdist import sdist",
"def path(self, path: str) -> None: self._path = path @property def pyx(self) ->",
"@property def c(self) -> str: return self.path + \".c\" cython_modules = [ CythonModule(",
"3.1\", \"Programming Language :: Python :: 3.2\", \"Programming Language :: Python :: 3.3\",",
"\"Programming Language :: Python\", \"Programming Language :: Python :: 3\", \"Programming Language ::",
"Python :: 3.2\", \"Programming Language :: Python :: 3.3\", \"Programming Language :: Python",
":: Python :: 3.5\", \"Programming Language :: Python :: 3.6\", \"Programming Language ::",
":: Python :: 3.6\", \"Programming Language :: Python :: 3.7\", \"Programming Language ::",
"\"License :: OSI Approved :: MIT License\", \"Programming Language :: Python\", \"Programming Language",
"# version=\"0.1.0\", description=\"A timeseries forecasting package, specialised in forecasting grouped timeseries\", author=\"<NAME>\", author_email=\"<EMAIL>\",",
"Python :: 3.8\", \"Programming Language :: Cython\", \"Topic :: Scientific/Engineering :: Mathematics\", ],",
"Python :: 3.3\", \"Programming Language :: Python :: 3.4\", \"Programming Language :: Python",
"name: str, path: str): self.name = name self.path = path @property def name(self)",
"False else: raise class CythonModule(object): def __init__(self, name: str, path: str): self.name =",
"USE_CYTHON: class sdist(_sdist): def run(self): # Make sure the compiled Cython files in",
"\"pytest-cov\", \"Cython\", \"pre-commit\", \"tox\"] setup( name=\"tyme\", # version=\"0.1.0\", description=\"A timeseries forecasting package, specialised",
"the distribution are up-to-date cythonize([module.pyx for module in cython_modules]) _sdist.run(self) ext_modules = [",
":: 3.7\", \"Programming Language :: Python :: 3.8\", \"Programming Language :: Cython\", \"Topic",
"] cmdclass = {} requirements = [ \"Bottleneck\", \"cycler\", \"kiwisolver\", \"numpy\", \"pandas\", \"Pillow\",",
"\"pandas\", \"Pillow\", \"pyparsing\", \"python-dateutil\", \"pytz\", \"six\", \"scipy\", \"Cython\", ] requirements_dev = [\"pytest\", \"pytest-cov\",",
"specialised in forecasting grouped timeseries\", author=\"<NAME>\", author_email=\"<EMAIL>\", url=\"http://github.com/sam-bailey/tyme\", packages=find_packages(where=\"src\"), package_dir={\"\": \"src\"}, cmdclass=cmdclass, ext_modules=ext_modules,",
"it to 'auto' to build with Cython if available, otherwise # from the",
"Developers\", \"License :: OSI Approved :: MIT License\", \"Programming Language :: Python\", \"Programming",
"@property def pyx(self) -> str: return self.path + \".pyx\" @property def c(self) ->",
"Status :: 4 - Beta\", \"Intended Audience :: Developers\", \"License :: OSI Approved",
"self._name = name @property def path(self) -> str: return self._path @path.setter def path(self,",
"are up-to-date cythonize([module.pyx for module in cython_modules]) _sdist.run(self) ext_modules = [ Extension(module.name, [module.pyx])",
"= {} requirements = [ \"Bottleneck\", \"cycler\", \"kiwisolver\", \"numpy\", \"pandas\", \"Pillow\", \"pyparsing\", \"python-dateutil\",",
"building extensions using Cython. # Set it to False to build extensions from",
"str: return self.path + \".c\" cython_modules = [ CythonModule( name=\"tyme.base_forecasters.exponential_smoothing_cy\", path=\"src/cython/exponential_smoothing_cy\", ), CythonModule(",
"ImportError: if USE_CYTHON == \"auto\": USE_CYTHON = False else: raise class CythonModule(object): def",
"sys from setuptools import setup, find_packages, Extension from distutils.command.sdist import sdist as _sdist",
"-> None: self._name = name @property def path(self) -> str: return self._path @path.setter",
"), CythonModule( name=\"tyme.base_forecasters.robust_exponential_smoothing_cy\", path=\"src/cython/robust_exponential_smoothing_cy\", ), ] if sys.version_info[0] == 2: raise Exception(\"Python 2.x",
"module in cython_modules ] cmdclass = {} requirements = [ \"Bottleneck\", \"cycler\", \"kiwisolver\",",
"# Make sure the compiled Cython files in the distribution are up-to-date cythonize([module.pyx",
"raise class CythonModule(object): def __init__(self, name: str, path: str): self.name = name self.path",
":: Python :: 3\", \"Programming Language :: Python :: 3.1\", \"Programming Language ::",
"-> str: return self.path + \".c\" cython_modules = [ CythonModule( name=\"tyme.base_forecasters.exponential_smoothing_cy\", path=\"src/cython/exponential_smoothing_cy\", ),",
"up-to-date cythonize([module.pyx for module in cython_modules]) _sdist.run(self) ext_modules = [ Extension(module.name, [module.pyx]) for",
"the compiled Cython files in the distribution are up-to-date cythonize([module.pyx for module in",
"str) -> None: self._path = path @property def pyx(self) -> str: return self.path",
"to build with Cython if available, otherwise # from the C file. import",
"[\"pytest\", \"pytest-cov\", \"Cython\", \"pre-commit\", \"tox\"] setup( name=\"tyme\", # version=\"0.1.0\", description=\"A timeseries forecasting package,",
":: 3.8\", \"Programming Language :: Cython\", \"Topic :: Scientific/Engineering :: Mathematics\", ], keywords=\"timeseries",
"with Cython if available, otherwise # from the C file. import sys from",
"import sys from setuptools import setup, find_packages, Extension from distutils.command.sdist import sdist as",
"path=\"src/cython/robust_exponential_smoothing_cy\", ), ] if sys.version_info[0] == 2: raise Exception(\"Python 2.x is no longer",
"version=\"0.1.0\", description=\"A timeseries forecasting package, specialised in forecasting grouped timeseries\", author=\"<NAME>\", author_email=\"<EMAIL>\", url=\"http://github.com/sam-bailey/tyme\",",
"longer supported\") if USE_CYTHON: class sdist(_sdist): def run(self): # Make sure the compiled",
"from Cython.Distutils import build_ext from Cython.Build import cythonize except ImportError: if USE_CYTHON ==",
"= [ Extension(module.name, [module.c]) for module in cython_modules ] cmdclass = {} requirements",
"Language :: Python :: 3.1\", \"Programming Language :: Python :: 3.2\", \"Programming Language",
"packages=find_packages(where=\"src\"), package_dir={\"\": \"src\"}, cmdclass=cmdclass, ext_modules=ext_modules, include_dirs=[numpy.get_include()], long_description=open(\"README.md\").read(), install_requires=requirements, extras_require={\"dev\": requirements_dev}, license=\"MIT\", classifiers=[ \"Development",
"\"Pillow\", \"pyparsing\", \"python-dateutil\", \"pytz\", \"six\", \"scipy\", \"Cython\", ] requirements_dev = [\"pytest\", \"pytest-cov\", \"Cython\",",
"extras_require={\"dev\": requirements_dev}, license=\"MIT\", classifiers=[ \"Development Status :: 4 - Beta\", \"Intended Audience ::",
"self._path = path @property def pyx(self) -> str: return self.path + \".pyx\" @property",
"name self.path = path @property def name(self) -> str: return self._name @name.setter def",
"str, path: str): self.name = name self.path = path @property def name(self) ->",
"the C file (that # was previously created using Cython). # Set it",
"name @property def path(self) -> str: return self._path @path.setter def path(self, path: str)",
":: 3.3\", \"Programming Language :: Python :: 3.4\", \"Programming Language :: Python ::",
"(that # was previously created using Cython). # Set it to 'auto' to",
"else: ext_modules = [ Extension(module.name, [module.c]) for module in cython_modules ] cmdclass =",
"this to True to enable building extensions using Cython. # Set it to",
"try: from Cython.Distutils import build_ext from Cython.Build import cythonize except ImportError: if USE_CYTHON",
"Beta\", \"Intended Audience :: Developers\", \"License :: OSI Approved :: MIT License\", \"Programming",
"sdist(_sdist): def run(self): # Make sure the compiled Cython files in the distribution",
":: Python :: 3.2\", \"Programming Language :: Python :: 3.3\", \"Programming Language ::",
"@name.setter def name(self, name: str) -> None: self._name = name @property def path(self)",
"no longer supported\") if USE_CYTHON: class sdist(_sdist): def run(self): # Make sure the",
"in cython_modules]) _sdist.run(self) ext_modules = [ Extension(module.name, [module.pyx]) for module in cython_modules ]",
"_sdist.run(self) ext_modules = [ Extension(module.name, [module.pyx]) for module in cython_modules ] cmdclass =",
"\".c\" cython_modules = [ CythonModule( name=\"tyme.base_forecasters.exponential_smoothing_cy\", path=\"src/cython/exponential_smoothing_cy\", ), CythonModule( name=\"tyme.base_forecasters.robust_exponential_smoothing_cy\", path=\"src/cython/robust_exponential_smoothing_cy\", ), ]",
"for module in cython_modules ] cmdclass = dict(build_ext=build_ext, sdist=sdist) else: ext_modules = [",
"Language :: Python\", \"Programming Language :: Python :: 3\", \"Programming Language :: Python",
"= \"auto\" if USE_CYTHON: try: from Cython.Distutils import build_ext from Cython.Build import cythonize",
"author_email=\"<EMAIL>\", url=\"http://github.com/sam-bailey/tyme\", packages=find_packages(where=\"src\"), package_dir={\"\": \"src\"}, cmdclass=cmdclass, ext_modules=ext_modules, include_dirs=[numpy.get_include()], long_description=open(\"README.md\").read(), install_requires=requirements, extras_require={\"dev\": requirements_dev}, license=\"MIT\",",
"\"Development Status :: 4 - Beta\", \"Intended Audience :: Developers\", \"License :: OSI",
"using Cython). # Set it to 'auto' to build with Cython if available,",
"except ImportError: if USE_CYTHON == \"auto\": USE_CYTHON = False else: raise class CythonModule(object):",
"cython_modules = [ CythonModule( name=\"tyme.base_forecasters.exponential_smoothing_cy\", path=\"src/cython/exponential_smoothing_cy\", ), CythonModule( name=\"tyme.base_forecasters.robust_exponential_smoothing_cy\", path=\"src/cython/robust_exponential_smoothing_cy\", ), ] if",
"# Set this to True to enable building extensions using Cython. # Set",
"\"Programming Language :: Python :: 3.5\", \"Programming Language :: Python :: 3.6\", \"Programming",
"# Set it to 'auto' to build with Cython if available, otherwise #",
"in cython_modules ] cmdclass = dict(build_ext=build_ext, sdist=sdist) else: ext_modules = [ Extension(module.name, [module.c])",
"\"src\"}, cmdclass=cmdclass, ext_modules=ext_modules, include_dirs=[numpy.get_include()], long_description=open(\"README.md\").read(), install_requires=requirements, extras_require={\"dev\": requirements_dev}, license=\"MIT\", classifiers=[ \"Development Status ::",
"self._path @path.setter def path(self, path: str) -> None: self._path = path @property def",
":: Python :: 3.4\", \"Programming Language :: Python :: 3.5\", \"Programming Language ::",
"Cython). # Set it to 'auto' to build with Cython if available, otherwise",
"def __init__(self, name: str, path: str): self.name = name self.path = path @property",
"@path.setter def path(self, path: str) -> None: self._path = path @property def pyx(self)",
"self.path + \".c\" cython_modules = [ CythonModule( name=\"tyme.base_forecasters.exponential_smoothing_cy\", path=\"src/cython/exponential_smoothing_cy\", ), CythonModule( name=\"tyme.base_forecasters.robust_exponential_smoothing_cy\", path=\"src/cython/robust_exponential_smoothing_cy\",",
"timeseries forecasting package, specialised in forecasting grouped timeseries\", author=\"<NAME>\", author_email=\"<EMAIL>\", url=\"http://github.com/sam-bailey/tyme\", packages=find_packages(where=\"src\"), package_dir={\"\":",
"Language :: Python :: 3.6\", \"Programming Language :: Python :: 3.7\", \"Programming Language",
":: 3\", \"Programming Language :: Python :: 3.1\", \"Programming Language :: Python ::",
"long_description=open(\"README.md\").read(), install_requires=requirements, extras_require={\"dev\": requirements_dev}, license=\"MIT\", classifiers=[ \"Development Status :: 4 - Beta\", \"Intended",
"import cythonize except ImportError: if USE_CYTHON == \"auto\": USE_CYTHON = False else: raise",
"USE_CYTHON = \"auto\" if USE_CYTHON: try: from Cython.Distutils import build_ext from Cython.Build import",
"3.4\", \"Programming Language :: Python :: 3.5\", \"Programming Language :: Python :: 3.6\",",
"to True to enable building extensions using Cython. # Set it to False",
"def name(self, name: str) -> None: self._name = name @property def path(self) ->",
"path=\"src/cython/exponential_smoothing_cy\", ), CythonModule( name=\"tyme.base_forecasters.robust_exponential_smoothing_cy\", path=\"src/cython/robust_exponential_smoothing_cy\", ), ] if sys.version_info[0] == 2: raise Exception(\"Python",
"Language :: Python :: 3\", \"Programming Language :: Python :: 3.1\", \"Programming Language",
":: MIT License\", \"Programming Language :: Python\", \"Programming Language :: Python :: 3\",",
"# was previously created using Cython). # Set it to 'auto' to build",
"CythonModule( name=\"tyme.base_forecasters.robust_exponential_smoothing_cy\", path=\"src/cython/robust_exponential_smoothing_cy\", ), ] if sys.version_info[0] == 2: raise Exception(\"Python 2.x is",
"extensions using Cython. # Set it to False to build extensions from the",
"-> None: self._path = path @property def pyx(self) -> str: return self.path +",
"class sdist(_sdist): def run(self): # Make sure the compiled Cython files in the",
"+ \".pyx\" @property def c(self) -> str: return self.path + \".c\" cython_modules =",
"self.name = name self.path = path @property def name(self) -> str: return self._name",
"requirements = [ \"Bottleneck\", \"cycler\", \"kiwisolver\", \"numpy\", \"pandas\", \"Pillow\", \"pyparsing\", \"python-dateutil\", \"pytz\", \"six\",",
"available, otherwise # from the C file. import sys from setuptools import setup,",
"License\", \"Programming Language :: Python\", \"Programming Language :: Python :: 3\", \"Programming Language",
"MIT License\", \"Programming Language :: Python\", \"Programming Language :: Python :: 3\", \"Programming",
"Language :: Python :: 3.7\", \"Programming Language :: Python :: 3.8\", \"Programming Language",
"using Cython. # Set it to False to build extensions from the C",
"Python\", \"Programming Language :: Python :: 3\", \"Programming Language :: Python :: 3.1\",",
"] requirements_dev = [\"pytest\", \"pytest-cov\", \"Cython\", \"pre-commit\", \"tox\"] setup( name=\"tyme\", # version=\"0.1.0\", description=\"A",
"cythonize except ImportError: if USE_CYTHON == \"auto\": USE_CYTHON = False else: raise class",
"[module.pyx]) for module in cython_modules ] cmdclass = dict(build_ext=build_ext, sdist=sdist) else: ext_modules =",
"\"Programming Language :: Python :: 3\", \"Programming Language :: Python :: 3.1\", \"Programming",
"import sdist as _sdist import numpy USE_CYTHON = \"auto\" if USE_CYTHON: try: from",
"it to False to build extensions from the C file (that # was",
"= False else: raise class CythonModule(object): def __init__(self, name: str, path: str): self.name",
"name(self) -> str: return self._name @name.setter def name(self, name: str) -> None: self._name",
":: Python :: 3.3\", \"Programming Language :: Python :: 3.4\", \"Programming Language ::",
"\"pytz\", \"six\", \"scipy\", \"Cython\", ] requirements_dev = [\"pytest\", \"pytest-cov\", \"Cython\", \"pre-commit\", \"tox\"] setup(",
"to build extensions from the C file (that # was previously created using",
"in forecasting grouped timeseries\", author=\"<NAME>\", author_email=\"<EMAIL>\", url=\"http://github.com/sam-bailey/tyme\", packages=find_packages(where=\"src\"), package_dir={\"\": \"src\"}, cmdclass=cmdclass, ext_modules=ext_modules, include_dirs=[numpy.get_include()],",
"[ CythonModule( name=\"tyme.base_forecasters.exponential_smoothing_cy\", path=\"src/cython/exponential_smoothing_cy\", ), CythonModule( name=\"tyme.base_forecasters.robust_exponential_smoothing_cy\", path=\"src/cython/robust_exponential_smoothing_cy\", ), ] if sys.version_info[0] ==",
"self.path + \".pyx\" @property def c(self) -> str: return self.path + \".c\" cython_modules",
"sys.version_info[0] == 2: raise Exception(\"Python 2.x is no longer supported\") if USE_CYTHON: class",
"name=\"tyme.base_forecasters.exponential_smoothing_cy\", path=\"src/cython/exponential_smoothing_cy\", ), CythonModule( name=\"tyme.base_forecasters.robust_exponential_smoothing_cy\", path=\"src/cython/robust_exponential_smoothing_cy\", ), ] if sys.version_info[0] == 2: raise",
"\"cycler\", \"kiwisolver\", \"numpy\", \"pandas\", \"Pillow\", \"pyparsing\", \"python-dateutil\", \"pytz\", \"six\", \"scipy\", \"Cython\", ] requirements_dev",
"created using Cython). # Set it to 'auto' to build with Cython if",
"'auto' to build with Cython if available, otherwise # from the C file.",
"to 'auto' to build with Cython if available, otherwise # from the C",
"sure the compiled Cython files in the distribution are up-to-date cythonize([module.pyx for module",
"= dict(build_ext=build_ext, sdist=sdist) else: ext_modules = [ Extension(module.name, [module.c]) for module in cython_modules",
"Cython.Build import cythonize except ImportError: if USE_CYTHON == \"auto\": USE_CYTHON = False else:",
"CythonModule(object): def __init__(self, name: str, path: str): self.name = name self.path = path",
"3.5\", \"Programming Language :: Python :: 3.6\", \"Programming Language :: Python :: 3.7\",",
"Language :: Python :: 3.8\", \"Programming Language :: Cython\", \"Topic :: Scientific/Engineering ::",
"ext_modules = [ Extension(module.name, [module.pyx]) for module in cython_modules ] cmdclass = dict(build_ext=build_ext,",
"# Set it to False to build extensions from the C file (that",
"cmdclass=cmdclass, ext_modules=ext_modules, include_dirs=[numpy.get_include()], long_description=open(\"README.md\").read(), install_requires=requirements, extras_require={\"dev\": requirements_dev}, license=\"MIT\", classifiers=[ \"Development Status :: 4",
":: 3.5\", \"Programming Language :: Python :: 3.6\", \"Programming Language :: Python ::",
"class CythonModule(object): def __init__(self, name: str, path: str): self.name = name self.path =",
"Exception(\"Python 2.x is no longer supported\") if USE_CYTHON: class sdist(_sdist): def run(self): #",
"C file (that # was previously created using Cython). # Set it to",
"setup( name=\"tyme\", # version=\"0.1.0\", description=\"A timeseries forecasting package, specialised in forecasting grouped timeseries\",",
"to False to build extensions from the C file (that # was previously",
"def name(self) -> str: return self._name @name.setter def name(self, name: str) -> None:",
"str: return self._path @path.setter def path(self, path: str) -> None: self._path = path",
"from the C file. import sys from setuptools import setup, find_packages, Extension from",
"= path @property def name(self) -> str: return self._name @name.setter def name(self, name:",
"USE_CYTHON = False else: raise class CythonModule(object): def __init__(self, name: str, path: str):",
"in cython_modules ] cmdclass = {} requirements = [ \"Bottleneck\", \"cycler\", \"kiwisolver\", \"numpy\",",
"\"Bottleneck\", \"cycler\", \"kiwisolver\", \"numpy\", \"pandas\", \"Pillow\", \"pyparsing\", \"python-dateutil\", \"pytz\", \"six\", \"scipy\", \"Cython\", ]",
"\"Programming Language :: Python :: 3.6\", \"Programming Language :: Python :: 3.7\", \"Programming",
"self._name @name.setter def name(self, name: str) -> None: self._name = name @property def",
"False to build extensions from the C file (that # was previously created",
"name=\"tyme.base_forecasters.robust_exponential_smoothing_cy\", path=\"src/cython/robust_exponential_smoothing_cy\", ), ] if sys.version_info[0] == 2: raise Exception(\"Python 2.x is no",
"path(self) -> str: return self._path @path.setter def path(self, path: str) -> None: self._path",
"cython_modules]) _sdist.run(self) ext_modules = [ Extension(module.name, [module.pyx]) for module in cython_modules ] cmdclass",
"if available, otherwise # from the C file. import sys from setuptools import",
"c(self) -> str: return self.path + \".c\" cython_modules = [ CythonModule( name=\"tyme.base_forecasters.exponential_smoothing_cy\", path=\"src/cython/exponential_smoothing_cy\",",
"find_packages, Extension from distutils.command.sdist import sdist as _sdist import numpy USE_CYTHON = \"auto\"",
"@property def name(self) -> str: return self._name @name.setter def name(self, name: str) ->",
"module in cython_modules]) _sdist.run(self) ext_modules = [ Extension(module.name, [module.pyx]) for module in cython_modules",
"C file. import sys from setuptools import setup, find_packages, Extension from distutils.command.sdist import",
"otherwise # from the C file. import sys from setuptools import setup, find_packages,",
"return self.path + \".pyx\" @property def c(self) -> str: return self.path + \".c\"",
"Cython.Distutils import build_ext from Cython.Build import cythonize except ImportError: if USE_CYTHON == \"auto\":",
"\"scipy\", \"Cython\", ] requirements_dev = [\"pytest\", \"pytest-cov\", \"Cython\", \"pre-commit\", \"tox\"] setup( name=\"tyme\", #",
"distutils.command.sdist import sdist as _sdist import numpy USE_CYTHON = \"auto\" if USE_CYTHON: try:",
"return self._path @path.setter def path(self, path: str) -> None: self._path = path @property",
"cython_modules ] cmdclass = {} requirements = [ \"Bottleneck\", \"cycler\", \"kiwisolver\", \"numpy\", \"pandas\",",
"__init__(self, name: str, path: str): self.name = name self.path = path @property def",
"Python :: 3.7\", \"Programming Language :: Python :: 3.8\", \"Programming Language :: Cython\",",
"the C file. import sys from setuptools import setup, find_packages, Extension from distutils.command.sdist",
"self.path = path @property def name(self) -> str: return self._name @name.setter def name(self,",
"path: str): self.name = name self.path = path @property def name(self) -> str:",
"Extension(module.name, [module.pyx]) for module in cython_modules ] cmdclass = dict(build_ext=build_ext, sdist=sdist) else: ext_modules",
"\"Programming Language :: Python :: 3.1\", \"Programming Language :: Python :: 3.2\", \"Programming",
"Extension from distutils.command.sdist import sdist as _sdist import numpy USE_CYTHON = \"auto\" if",
"else: raise class CythonModule(object): def __init__(self, name: str, path: str): self.name = name",
"package_dir={\"\": \"src\"}, cmdclass=cmdclass, ext_modules=ext_modules, include_dirs=[numpy.get_include()], long_description=open(\"README.md\").read(), install_requires=requirements, extras_require={\"dev\": requirements_dev}, license=\"MIT\", classifiers=[ \"Development Status",
"from the C file (that # was previously created using Cython). # Set",
":: OSI Approved :: MIT License\", \"Programming Language :: Python\", \"Programming Language ::",
"[ Extension(module.name, [module.c]) for module in cython_modules ] cmdclass = {} requirements =",
"as _sdist import numpy USE_CYTHON = \"auto\" if USE_CYTHON: try: from Cython.Distutils import",
"from distutils.command.sdist import sdist as _sdist import numpy USE_CYTHON = \"auto\" if USE_CYTHON:",
"= path @property def pyx(self) -> str: return self.path + \".pyx\" @property def",
"name: str) -> None: self._name = name @property def path(self) -> str: return",
"import numpy USE_CYTHON = \"auto\" if USE_CYTHON: try: from Cython.Distutils import build_ext from",
"extensions from the C file (that # was previously created using Cython). #",
"def path(self) -> str: return self._path @path.setter def path(self, path: str) -> None:",
"2.x is no longer supported\") if USE_CYTHON: class sdist(_sdist): def run(self): # Make",
"\"Programming Language :: Python :: 3.8\", \"Programming Language :: Cython\", \"Topic :: Scientific/Engineering",
"module in cython_modules ] cmdclass = dict(build_ext=build_ext, sdist=sdist) else: ext_modules = [ Extension(module.name,",
"\"python-dateutil\", \"pytz\", \"six\", \"scipy\", \"Cython\", ] requirements_dev = [\"pytest\", \"pytest-cov\", \"Cython\", \"pre-commit\", \"tox\"]",
"if USE_CYTHON: class sdist(_sdist): def run(self): # Make sure the compiled Cython files",
"[ \"Bottleneck\", \"cycler\", \"kiwisolver\", \"numpy\", \"pandas\", \"Pillow\", \"pyparsing\", \"python-dateutil\", \"pytz\", \"six\", \"scipy\", \"Cython\",",
"\"pre-commit\", \"tox\"] setup( name=\"tyme\", # version=\"0.1.0\", description=\"A timeseries forecasting package, specialised in forecasting",
"#!/usr/bin/env python3 # Set this to True to enable building extensions using Cython.",
"import build_ext from Cython.Build import cythonize except ImportError: if USE_CYTHON == \"auto\": USE_CYTHON",
"if sys.version_info[0] == 2: raise Exception(\"Python 2.x is no longer supported\") if USE_CYTHON:",
"\"Intended Audience :: Developers\", \"License :: OSI Approved :: MIT License\", \"Programming Language",
"classifiers=[ \"Development Status :: 4 - Beta\", \"Intended Audience :: Developers\", \"License ::",
"= [\"pytest\", \"pytest-cov\", \"Cython\", \"pre-commit\", \"tox\"] setup( name=\"tyme\", # version=\"0.1.0\", description=\"A timeseries forecasting",
"3.8\", \"Programming Language :: Cython\", \"Topic :: Scientific/Engineering :: Mathematics\", ], keywords=\"timeseries forecast",
"None: self._path = path @property def pyx(self) -> str: return self.path + \".pyx\"",
"Language :: Python :: 3.5\", \"Programming Language :: Python :: 3.6\", \"Programming Language",
"name(self, name: str) -> None: self._name = name @property def path(self) -> str:",
"\"auto\" if USE_CYTHON: try: from Cython.Distutils import build_ext from Cython.Build import cythonize except",
"] if sys.version_info[0] == 2: raise Exception(\"Python 2.x is no longer supported\") if",
"forecasting package, specialised in forecasting grouped timeseries\", author=\"<NAME>\", author_email=\"<EMAIL>\", url=\"http://github.com/sam-bailey/tyme\", packages=find_packages(where=\"src\"), package_dir={\"\": \"src\"},",
"license=\"MIT\", classifiers=[ \"Development Status :: 4 - Beta\", \"Intended Audience :: Developers\", \"License",
"cmdclass = dict(build_ext=build_ext, sdist=sdist) else: ext_modules = [ Extension(module.name, [module.c]) for module in",
"from Cython.Build import cythonize except ImportError: if USE_CYTHON == \"auto\": USE_CYTHON = False",
"2: raise Exception(\"Python 2.x is no longer supported\") if USE_CYTHON: class sdist(_sdist): def",
"+ \".c\" cython_modules = [ CythonModule( name=\"tyme.base_forecasters.exponential_smoothing_cy\", path=\"src/cython/exponential_smoothing_cy\", ), CythonModule( name=\"tyme.base_forecasters.robust_exponential_smoothing_cy\", path=\"src/cython/robust_exponential_smoothing_cy\", ),",
"in the distribution are up-to-date cythonize([module.pyx for module in cython_modules]) _sdist.run(self) ext_modules =",
"sdist as _sdist import numpy USE_CYTHON = \"auto\" if USE_CYTHON: try: from Cython.Distutils",
"\"kiwisolver\", \"numpy\", \"pandas\", \"Pillow\", \"pyparsing\", \"python-dateutil\", \"pytz\", \"six\", \"scipy\", \"Cython\", ] requirements_dev =",
"build_ext from Cython.Build import cythonize except ImportError: if USE_CYTHON == \"auto\": USE_CYTHON =",
"OSI Approved :: MIT License\", \"Programming Language :: Python\", \"Programming Language :: Python",
"4 - Beta\", \"Intended Audience :: Developers\", \"License :: OSI Approved :: MIT",
":: Python :: 3.8\", \"Programming Language :: Cython\", \"Topic :: Scientific/Engineering :: Mathematics\",",
"Language :: Python :: 3.4\", \"Programming Language :: Python :: 3.5\", \"Programming Language",
"\".pyx\" @property def c(self) -> str: return self.path + \".c\" cython_modules = [",
":: Developers\", \"License :: OSI Approved :: MIT License\", \"Programming Language :: Python\",",
":: 4 - Beta\", \"Intended Audience :: Developers\", \"License :: OSI Approved ::",
":: Python :: 3.7\", \"Programming Language :: Python :: 3.8\", \"Programming Language ::",
"return self.path + \".c\" cython_modules = [ CythonModule( name=\"tyme.base_forecasters.exponential_smoothing_cy\", path=\"src/cython/exponential_smoothing_cy\", ), CythonModule( name=\"tyme.base_forecasters.robust_exponential_smoothing_cy\",",
"str) -> None: self._name = name @property def path(self) -> str: return self._path",
"def pyx(self) -> str: return self.path + \".pyx\" @property def c(self) -> str:",
"Make sure the compiled Cython files in the distribution are up-to-date cythonize([module.pyx for",
"Audience :: Developers\", \"License :: OSI Approved :: MIT License\", \"Programming Language ::",
"3.6\", \"Programming Language :: Python :: 3.7\", \"Programming Language :: Python :: 3.8\",",
"3.2\", \"Programming Language :: Python :: 3.3\", \"Programming Language :: Python :: 3.4\","
] |
[
"str, pluginRootDir: str, platform: PeekAgentPlatformHookABC): PluginCommonEntryHookABC.__init__(self, pluginName=pluginName, pluginRootDir=pluginRootDir) self._platform = platform @property def",
"class PluginAgentEntryHookABC(PluginCommonEntryHookABC): def __init__(self, pluginName: str, pluginRootDir: str, platform: PeekAgentPlatformHookABC): PluginCommonEntryHookABC.__init__(self, pluginName=pluginName, pluginRootDir=pluginRootDir)",
"import PluginCommonEntryHookABC from peek_plugin_base.agent.PeekAgentPlatformHookABC import PeekAgentPlatformHookABC class PluginAgentEntryHookABC(PluginCommonEntryHookABC): def __init__(self, pluginName: str, pluginRootDir:",
"pluginName: str, pluginRootDir: str, platform: PeekAgentPlatformHookABC): PluginCommonEntryHookABC.__init__(self, pluginName=pluginName, pluginRootDir=pluginRootDir) self._platform = platform @property",
"= platform @property def platform(self) -> PeekAgentPlatformHookABC: return self._platform @property def publishedAgentApi(self) ->",
"pluginName=pluginName, pluginRootDir=pluginRootDir) self._platform = platform @property def platform(self) -> PeekAgentPlatformHookABC: return self._platform @property",
"Optional from peek_plugin_base.PluginCommonEntryHookABC import PluginCommonEntryHookABC from peek_plugin_base.agent.PeekAgentPlatformHookABC import PeekAgentPlatformHookABC class PluginAgentEntryHookABC(PluginCommonEntryHookABC): def __init__(self,",
"def platform(self) -> PeekAgentPlatformHookABC: return self._platform @property def publishedAgentApi(self) -> Optional[object]: return None",
"def __init__(self, pluginName: str, pluginRootDir: str, platform: PeekAgentPlatformHookABC): PluginCommonEntryHookABC.__init__(self, pluginName=pluginName, pluginRootDir=pluginRootDir) self._platform =",
"typing import Optional from peek_plugin_base.PluginCommonEntryHookABC import PluginCommonEntryHookABC from peek_plugin_base.agent.PeekAgentPlatformHookABC import PeekAgentPlatformHookABC class PluginAgentEntryHookABC(PluginCommonEntryHookABC):",
"PeekAgentPlatformHookABC): PluginCommonEntryHookABC.__init__(self, pluginName=pluginName, pluginRootDir=pluginRootDir) self._platform = platform @property def platform(self) -> PeekAgentPlatformHookABC: return",
"PeekAgentPlatformHookABC class PluginAgentEntryHookABC(PluginCommonEntryHookABC): def __init__(self, pluginName: str, pluginRootDir: str, platform: PeekAgentPlatformHookABC): PluginCommonEntryHookABC.__init__(self, pluginName=pluginName,",
"import Optional from peek_plugin_base.PluginCommonEntryHookABC import PluginCommonEntryHookABC from peek_plugin_base.agent.PeekAgentPlatformHookABC import PeekAgentPlatformHookABC class PluginAgentEntryHookABC(PluginCommonEntryHookABC): def",
"from peek_plugin_base.PluginCommonEntryHookABC import PluginCommonEntryHookABC from peek_plugin_base.agent.PeekAgentPlatformHookABC import PeekAgentPlatformHookABC class PluginAgentEntryHookABC(PluginCommonEntryHookABC): def __init__(self, pluginName:",
"peek_plugin_base.agent.PeekAgentPlatformHookABC import PeekAgentPlatformHookABC class PluginAgentEntryHookABC(PluginCommonEntryHookABC): def __init__(self, pluginName: str, pluginRootDir: str, platform: PeekAgentPlatformHookABC):",
"str, platform: PeekAgentPlatformHookABC): PluginCommonEntryHookABC.__init__(self, pluginName=pluginName, pluginRootDir=pluginRootDir) self._platform = platform @property def platform(self) ->",
"@property def platform(self) -> PeekAgentPlatformHookABC: return self._platform @property def publishedAgentApi(self) -> Optional[object]: return",
"from typing import Optional from peek_plugin_base.PluginCommonEntryHookABC import PluginCommonEntryHookABC from peek_plugin_base.agent.PeekAgentPlatformHookABC import PeekAgentPlatformHookABC class",
"pluginRootDir: str, platform: PeekAgentPlatformHookABC): PluginCommonEntryHookABC.__init__(self, pluginName=pluginName, pluginRootDir=pluginRootDir) self._platform = platform @property def platform(self)",
"import PeekAgentPlatformHookABC class PluginAgentEntryHookABC(PluginCommonEntryHookABC): def __init__(self, pluginName: str, pluginRootDir: str, platform: PeekAgentPlatformHookABC): PluginCommonEntryHookABC.__init__(self,",
"from peek_plugin_base.agent.PeekAgentPlatformHookABC import PeekAgentPlatformHookABC class PluginAgentEntryHookABC(PluginCommonEntryHookABC): def __init__(self, pluginName: str, pluginRootDir: str, platform:",
"platform @property def platform(self) -> PeekAgentPlatformHookABC: return self._platform @property def publishedAgentApi(self) -> Optional[object]:",
"peek_plugin_base.PluginCommonEntryHookABC import PluginCommonEntryHookABC from peek_plugin_base.agent.PeekAgentPlatformHookABC import PeekAgentPlatformHookABC class PluginAgentEntryHookABC(PluginCommonEntryHookABC): def __init__(self, pluginName: str,",
"pluginRootDir=pluginRootDir) self._platform = platform @property def platform(self) -> PeekAgentPlatformHookABC: return self._platform @property def",
"PluginCommonEntryHookABC.__init__(self, pluginName=pluginName, pluginRootDir=pluginRootDir) self._platform = platform @property def platform(self) -> PeekAgentPlatformHookABC: return self._platform",
"__init__(self, pluginName: str, pluginRootDir: str, platform: PeekAgentPlatformHookABC): PluginCommonEntryHookABC.__init__(self, pluginName=pluginName, pluginRootDir=pluginRootDir) self._platform = platform",
"platform: PeekAgentPlatformHookABC): PluginCommonEntryHookABC.__init__(self, pluginName=pluginName, pluginRootDir=pluginRootDir) self._platform = platform @property def platform(self) -> PeekAgentPlatformHookABC:",
"PluginAgentEntryHookABC(PluginCommonEntryHookABC): def __init__(self, pluginName: str, pluginRootDir: str, platform: PeekAgentPlatformHookABC): PluginCommonEntryHookABC.__init__(self, pluginName=pluginName, pluginRootDir=pluginRootDir) self._platform",
"self._platform = platform @property def platform(self) -> PeekAgentPlatformHookABC: return self._platform @property def publishedAgentApi(self)",
"PluginCommonEntryHookABC from peek_plugin_base.agent.PeekAgentPlatformHookABC import PeekAgentPlatformHookABC class PluginAgentEntryHookABC(PluginCommonEntryHookABC): def __init__(self, pluginName: str, pluginRootDir: str,"
] |
[
"\"RadioButton\") actionsCheck(pFrame.radio3, \"RadioButton\") ########################### # check panel's AtkAccessible ########################### # check panel states",
"# doesn't change panel1's state statesCheck(pFrame.panel1, \"Panel\") # click on radiobutton which is",
"checked state rising pFrame.check2.click(log=True) sleep(config.SHORT_DELAY) # BUG525428 - doing click action doesn't move",
"Description: main test script of panel # ../samples/winforms/panel.py is the test sample script",
"script # panel/* is the wrapper of panel test sample script ############################################################################## #",
"= None try: app_path = argv[1] except IndexError: pass #expected # open the",
"# check panel states statesCheck(pFrame.panel1, \"Panel\") statesCheck(pFrame.panel2, \"Panel\") ########################### # check children's AtkAccessible",
"panel's AtkAccessible ########################### # check panel states statesCheck(pFrame.panel1, \"Panel\") statesCheck(pFrame.panel2, \"Panel\") ########################### #",
"########################### # check children's AtkAction ########################### # check if checkbox and radiobutton in",
"the generated log file \"\"\" Test accessibility of Panel widget \"\"\" # imports",
"click action doesn't move focus on that control #statesCheck(pFrame.radio2, \"RadioButton\", add_states=[\"checked\", \"focused\"]) #",
"import * from sys import argv app_path = None try: app_path = argv[1]",
"pFrame.radio2.click(log=True) sleep(config.SHORT_DELAY) pFrame.assertText(pFrame.label3, 'You are Female') # BUG525428 - doing click action doesn't",
"########################### # check if checkbox and radiobutton in panel still have correct actions",
"label in panel still have correct states statesCheck(pFrame.label1, \"Label\") statesCheck(pFrame.label2, \"Label\") statesCheck(pFrame.label3, \"Label\")",
"generated log file \"\"\" Test accessibility of Panel widget \"\"\" # imports from",
"add_states=[\"checked\", \"focused\"]) statesCheck(pFrame.check3, \"CheckBox\", add_states=[\"checked\"]) # doesn't change panel1's state statesCheck(pFrame.panel1, \"Panel\") #",
"pFrame.assertText(pFrame.label3, 'You are Female') # BUG525428 - doing click action doesn't move focus",
"pass #expected # open the panel sample application try: app = launchPanel(app_path) except",
"IOError, msg: print \"ERROR: %s\" % msg exit(2) # make sure we got",
"the app back if app is None: exit(4) # just an alias to",
"file \"\"\" Test accessibility of Panel widget \"\"\" # imports from panel import",
"print \"ERROR: %s\" % msg exit(2) # make sure we got the app",
"and radiobutton in panel still have correct states statesCheck(pFrame.check1, \"CheckBox\", add_states=[\"focused\"]) statesCheck(pFrame.check2, \"CheckBox\")",
"have correct states statesCheck(pFrame.check1, \"CheckBox\", add_states=[\"focused\"]) statesCheck(pFrame.check2, \"CheckBox\") statesCheck(pFrame.check3, \"CheckBox\", add_states=[\"checked\"]) statesCheck(pFrame.check4, \"CheckBox\",",
"its child # check if checkbox and radiobutton in panel still have correct",
"in panel still have correct states statesCheck(pFrame.label1, \"Label\") statesCheck(pFrame.label2, \"Label\") statesCheck(pFrame.label3, \"Label\") #",
"<filename>test/testers/winforms/panel-regression.py #!/usr/bin/env python # vim: set tabstop=4 shiftwidth=4 expandtab ############################################################################## # Written by:",
"state statesCheck(pFrame.panel1, \"Panel\") # click on radiobutton which is in panel2 to update",
"label pFrame.radio2.click(log=True) sleep(config.SHORT_DELAY) pFrame.assertText(pFrame.label3, 'You are Female') # BUG525428 - doing click action",
"\"Panel\") statesCheck(pFrame.panel2, \"Panel\") ########################### # check children's AtkAccessible ########################### # panel should be",
"that control #statesCheck(pFrame.radio2, \"RadioButton\", add_states=[\"checked\", \"focused\"]) # doesn't change panel2's state statesCheck(pFrame.panel2, \"Panel\")",
"AtkAction ########################### # check if checkbox and radiobutton in panel still have correct",
"statesCheck(pFrame.check3, \"CheckBox\", add_states=[\"checked\"]) # doesn't change panel1's state statesCheck(pFrame.panel1, \"Panel\") # click on",
"AtkAccessible ########################### # panel should be focused, but focus on its child #",
"test script of panel # ../samples/winforms/panel.py is the test sample script # panel/*",
"is the wrapper of panel test sample script ############################################################################## # The docstring below",
"doesn't change panel1's state statesCheck(pFrame.panel1, \"Panel\") # click on radiobutton which is in",
"focus on that control #statesCheck(pFrame.check2, \"CheckBox\", add_states=[\"checked\", \"focused\"]) statesCheck(pFrame.check3, \"CheckBox\", add_states=[\"checked\"]) # doesn't",
"except IndexError: pass #expected # open the panel sample application try: app =",
"focus on that control #statesCheck(pFrame.radio2, \"RadioButton\", add_states=[\"checked\", \"focused\"]) # doesn't change panel2's state",
"if checkbox and radiobutton in panel still have correct states statesCheck(pFrame.check1, \"CheckBox\", add_states=[\"focused\"])",
"on that control #statesCheck(pFrame.check2, \"CheckBox\", add_states=[\"checked\", \"focused\"]) statesCheck(pFrame.check3, \"CheckBox\", add_states=[\"checked\"]) # doesn't change",
"\"CheckBox\", add_states=[\"checked\"]) # doesn't change panel1's state statesCheck(pFrame.panel1, \"Panel\") # click on radiobutton",
"are Female') # BUG525428 - doing click action doesn't move focus on that",
"move focus on that control #statesCheck(pFrame.radio2, \"RadioButton\", add_states=[\"checked\", \"focused\"]) # doesn't change panel2's",
"\"ERROR: %s\" % msg exit(2) # make sure we got the app back",
"argv[1] except IndexError: pass #expected # open the panel sample application try: app",
"# click on checkbox which is in panel1 to assert checked state rising",
"actionsCheck(pFrame.radio3, \"RadioButton\") ########################### # check panel's AtkAccessible ########################### # check panel states statesCheck(pFrame.panel1,",
"#!/usr/bin/env python # vim: set tabstop=4 shiftwidth=4 expandtab ############################################################################## # Written by: <NAME>",
"\"RadioButton\") actionsCheck(pFrame.radio2, \"RadioButton\") actionsCheck(pFrame.radio3, \"RadioButton\") ########################### # check panel's AtkAccessible ########################### # check",
"#statesCheck(pFrame.radio2, \"RadioButton\", add_states=[\"checked\", \"focused\"]) # doesn't change panel2's state statesCheck(pFrame.panel2, \"Panel\") # close",
"IndexError: pass #expected # open the panel sample application try: app = launchPanel(app_path)",
"# BUG525428 - doing click action doesn't move focus on that control #statesCheck(pFrame.check2,",
"from states import * from actions import * from sys import argv app_path",
"\"CheckBox\", add_states=[\"checked\"]) statesCheck(pFrame.check4, \"CheckBox\", invalid_states=[\"sensitive\", \"enabled\",\"focusable\"]) statesCheck(pFrame.radio1, \"RadioButton\", add_states=[\"checked\"]) statesCheck(pFrame.radio2, \"RadioButton\") statesCheck(pFrame.radio3, \"RadioButton\",",
"msg: print \"ERROR: %s\" % msg exit(2) # make sure we got the",
"statesCheck(pFrame.check1, \"CheckBox\", add_states=[\"focused\"]) statesCheck(pFrame.check2, \"CheckBox\") statesCheck(pFrame.check3, \"CheckBox\", add_states=[\"checked\"]) statesCheck(pFrame.check4, \"CheckBox\", invalid_states=[\"sensitive\", \"enabled\",\"focusable\"]) statesCheck(pFrame.radio1,",
"which is in panel2 to update label pFrame.radio2.click(log=True) sleep(config.SHORT_DELAY) pFrame.assertText(pFrame.label3, 'You are Female')",
"try: app_path = argv[1] except IndexError: pass #expected # open the panel sample",
"# just an alias to make things shorter pFrame = app.panelFrame ########################### #",
"exit(4) # just an alias to make things shorter pFrame = app.panelFrame ###########################",
"things shorter pFrame = app.panelFrame ########################### # check children's AtkAction ########################### # check",
"change panel1's state statesCheck(pFrame.panel1, \"Panel\") # click on radiobutton which is in panel2",
"\"CheckBox\") statesCheck(pFrame.check3, \"CheckBox\", add_states=[\"checked\"]) statesCheck(pFrame.check4, \"CheckBox\", invalid_states=[\"sensitive\", \"enabled\",\"focusable\"]) statesCheck(pFrame.radio1, \"RadioButton\", add_states=[\"checked\"]) statesCheck(pFrame.radio2, \"RadioButton\")",
"from sys import argv app_path = None try: app_path = argv[1] except IndexError:",
"# check children's AtkAccessible ########################### # panel should be focused, but focus on",
"panel/* is the wrapper of panel test sample script ############################################################################## # The docstring",
"Female') # BUG525428 - doing click action doesn't move focus on that control",
"\"CheckBox\") actionsCheck(pFrame.check2, \"CheckBox\") actionsCheck(pFrame.check3, \"CheckBox\") actionsCheck(pFrame.check4, \"CheckBox\") actionsCheck(pFrame.radio1, \"RadioButton\") actionsCheck(pFrame.radio2, \"RadioButton\") actionsCheck(pFrame.radio3, \"RadioButton\")",
"############################################################################## # The docstring below is used in the generated log file \"\"\"",
"that control #statesCheck(pFrame.check2, \"CheckBox\", add_states=[\"checked\", \"focused\"]) statesCheck(pFrame.check3, \"CheckBox\", add_states=[\"checked\"]) # doesn't change panel1's",
"panel1 to assert checked state rising pFrame.check2.click(log=True) sleep(config.SHORT_DELAY) # BUG525428 - doing click",
"used in the generated log file \"\"\" Test accessibility of Panel widget \"\"\"",
"actionsCheck(pFrame.check4, \"CheckBox\") actionsCheck(pFrame.radio1, \"RadioButton\") actionsCheck(pFrame.radio2, \"RadioButton\") actionsCheck(pFrame.radio3, \"RadioButton\") ########################### # check panel's AtkAccessible",
"statesCheck(pFrame.check2, \"CheckBox\") statesCheck(pFrame.check3, \"CheckBox\", add_states=[\"checked\"]) statesCheck(pFrame.check4, \"CheckBox\", invalid_states=[\"sensitive\", \"enabled\",\"focusable\"]) statesCheck(pFrame.radio1, \"RadioButton\", add_states=[\"checked\"]) statesCheck(pFrame.radio2,",
"check panel's AtkAccessible ########################### # check panel states statesCheck(pFrame.panel1, \"Panel\") statesCheck(pFrame.panel2, \"Panel\") ###########################",
"doing click action doesn't move focus on that control #statesCheck(pFrame.check2, \"CheckBox\", add_states=[\"checked\", \"focused\"])",
"\"Label\") statesCheck(pFrame.label2, \"Label\") statesCheck(pFrame.label3, \"Label\") # click on checkbox which is in panel1",
"on that control #statesCheck(pFrame.radio2, \"RadioButton\", add_states=[\"checked\", \"focused\"]) # doesn't change panel2's state statesCheck(pFrame.panel2,",
"except IOError, msg: print \"ERROR: %s\" % msg exit(2) # make sure we",
"got the app back if app is None: exit(4) # just an alias",
"pFrame.check2.click(log=True) sleep(config.SHORT_DELAY) # BUG525428 - doing click action doesn't move focus on that",
"panel1's state statesCheck(pFrame.panel1, \"Panel\") # click on radiobutton which is in panel2 to",
"None try: app_path = argv[1] except IndexError: pass #expected # open the panel",
"statesCheck(pFrame.check3, \"CheckBox\", add_states=[\"checked\"]) statesCheck(pFrame.check4, \"CheckBox\", invalid_states=[\"sensitive\", \"enabled\",\"focusable\"]) statesCheck(pFrame.radio1, \"RadioButton\", add_states=[\"checked\"]) statesCheck(pFrame.radio2, \"RadioButton\") statesCheck(pFrame.radio3,",
"in panel1 to assert checked state rising pFrame.check2.click(log=True) sleep(config.SHORT_DELAY) # BUG525428 - doing",
"%s\" % msg exit(2) # make sure we got the app back if",
"\"RadioButton\", add_states=[\"checked\"]) statesCheck(pFrame.radio2, \"RadioButton\") statesCheck(pFrame.radio3, \"RadioButton\", invalid_states=[\"focusable\", \"sensitive\", \"enabled\"]) # check if label",
"in panel still have correct actions actionsCheck(pFrame.check1, \"CheckBox\") actionsCheck(pFrame.check2, \"CheckBox\") actionsCheck(pFrame.check3, \"CheckBox\") actionsCheck(pFrame.check4,",
"Written by: <NAME> <<EMAIL>> # Date: 10/21/2008 # Description: main test script of",
"have correct actions actionsCheck(pFrame.check1, \"CheckBox\") actionsCheck(pFrame.check2, \"CheckBox\") actionsCheck(pFrame.check3, \"CheckBox\") actionsCheck(pFrame.check4, \"CheckBox\") actionsCheck(pFrame.radio1, \"RadioButton\")",
"focused, but focus on its child # check if checkbox and radiobutton in",
"in panel still have correct states statesCheck(pFrame.check1, \"CheckBox\", add_states=[\"focused\"]) statesCheck(pFrame.check2, \"CheckBox\") statesCheck(pFrame.check3, \"CheckBox\",",
"sample application try: app = launchPanel(app_path) except IOError, msg: print \"ERROR: %s\" %",
"<NAME> <<EMAIL>> # Date: 10/21/2008 # Description: main test script of panel #",
"10/21/2008 # Description: main test script of panel # ../samples/winforms/panel.py is the test",
"close application frame window pFrame.quit() print \"INFO: Log written to: %s\" % config.OUTPUT_DIR",
"states statesCheck(pFrame.panel1, \"Panel\") statesCheck(pFrame.panel2, \"Panel\") ########################### # check children's AtkAccessible ########################### # panel",
"# check if label in panel still have correct states statesCheck(pFrame.label1, \"Label\") statesCheck(pFrame.label2,",
"check if label in panel still have correct states statesCheck(pFrame.label1, \"Label\") statesCheck(pFrame.label2, \"Label\")",
"argv app_path = None try: app_path = argv[1] except IndexError: pass #expected #",
"is None: exit(4) # just an alias to make things shorter pFrame =",
"<<EMAIL>> # Date: 10/21/2008 # Description: main test script of panel # ../samples/winforms/panel.py",
"exit(2) # make sure we got the app back if app is None:",
"import * from helpers import * from states import * from actions import",
"control #statesCheck(pFrame.radio2, \"RadioButton\", add_states=[\"checked\", \"focused\"]) # doesn't change panel2's state statesCheck(pFrame.panel2, \"Panel\") #",
"\"Label\") # click on checkbox which is in panel1 to assert checked state",
"script ############################################################################## # The docstring below is used in the generated log file",
"checkbox which is in panel1 to assert checked state rising pFrame.check2.click(log=True) sleep(config.SHORT_DELAY) #",
"\"focused\"]) statesCheck(pFrame.check3, \"CheckBox\", add_states=[\"checked\"]) # doesn't change panel1's state statesCheck(pFrame.panel1, \"Panel\") # click",
"expandtab ############################################################################## # Written by: <NAME> <<EMAIL>> # Date: 10/21/2008 # Description: main",
"panel should be focused, but focus on its child # check if checkbox",
"vim: set tabstop=4 shiftwidth=4 expandtab ############################################################################## # Written by: <NAME> <<EMAIL>> # Date:",
"app.panelFrame ########################### # check children's AtkAction ########################### # check if checkbox and radiobutton",
"is in panel1 to assert checked state rising pFrame.check2.click(log=True) sleep(config.SHORT_DELAY) # BUG525428 -",
"states statesCheck(pFrame.label1, \"Label\") statesCheck(pFrame.label2, \"Label\") statesCheck(pFrame.label3, \"Label\") # click on checkbox which is",
"imports from panel import * from helpers import * from states import *",
"states statesCheck(pFrame.check1, \"CheckBox\", add_states=[\"focused\"]) statesCheck(pFrame.check2, \"CheckBox\") statesCheck(pFrame.check3, \"CheckBox\", add_states=[\"checked\"]) statesCheck(pFrame.check4, \"CheckBox\", invalid_states=[\"sensitive\", \"enabled\",\"focusable\"])",
"if app is None: exit(4) # just an alias to make things shorter",
"pFrame = app.panelFrame ########################### # check children's AtkAction ########################### # check if checkbox",
"\"RadioButton\", invalid_states=[\"focusable\", \"sensitive\", \"enabled\"]) # check if label in panel still have correct",
"= app.panelFrame ########################### # check children's AtkAction ########################### # check if checkbox and",
"\"Label\") statesCheck(pFrame.label3, \"Label\") # click on checkbox which is in panel1 to assert",
"docstring below is used in the generated log file \"\"\" Test accessibility of",
"by: <NAME> <<EMAIL>> # Date: 10/21/2008 # Description: main test script of panel",
"actionsCheck(pFrame.check3, \"CheckBox\") actionsCheck(pFrame.check4, \"CheckBox\") actionsCheck(pFrame.radio1, \"RadioButton\") actionsCheck(pFrame.radio2, \"RadioButton\") actionsCheck(pFrame.radio3, \"RadioButton\") ########################### # check",
"is used in the generated log file \"\"\" Test accessibility of Panel widget",
"state statesCheck(pFrame.panel2, \"Panel\") # close application frame window pFrame.quit() print \"INFO: Log written",
"check children's AtkAction ########################### # check if checkbox and radiobutton in panel still",
"shorter pFrame = app.panelFrame ########################### # check children's AtkAction ########################### # check if",
"correct actions actionsCheck(pFrame.check1, \"CheckBox\") actionsCheck(pFrame.check2, \"CheckBox\") actionsCheck(pFrame.check3, \"CheckBox\") actionsCheck(pFrame.check4, \"CheckBox\") actionsCheck(pFrame.radio1, \"RadioButton\") actionsCheck(pFrame.radio2,",
"\"enabled\",\"focusable\"]) statesCheck(pFrame.radio1, \"RadioButton\", add_states=[\"checked\"]) statesCheck(pFrame.radio2, \"RadioButton\") statesCheck(pFrame.radio3, \"RadioButton\", invalid_states=[\"focusable\", \"sensitive\", \"enabled\"]) # check",
"# imports from panel import * from helpers import * from states import",
"action doesn't move focus on that control #statesCheck(pFrame.radio2, \"RadioButton\", add_states=[\"checked\", \"focused\"]) # doesn't",
"statesCheck(pFrame.panel1, \"Panel\") # click on radiobutton which is in panel2 to update label",
"= launchPanel(app_path) except IOError, msg: print \"ERROR: %s\" % msg exit(2) # make",
"radiobutton in panel still have correct actions actionsCheck(pFrame.check1, \"CheckBox\") actionsCheck(pFrame.check2, \"CheckBox\") actionsCheck(pFrame.check3, \"CheckBox\")",
"log file \"\"\" Test accessibility of Panel widget \"\"\" # imports from panel",
"correct states statesCheck(pFrame.label1, \"Label\") statesCheck(pFrame.label2, \"Label\") statesCheck(pFrame.label3, \"Label\") # click on checkbox which",
"set tabstop=4 shiftwidth=4 expandtab ############################################################################## # Written by: <NAME> <<EMAIL>> # Date: 10/21/2008",
"doesn't move focus on that control #statesCheck(pFrame.radio2, \"RadioButton\", add_states=[\"checked\", \"focused\"]) # doesn't change",
"the wrapper of panel test sample script ############################################################################## # The docstring below is",
"# BUG525428 - doing click action doesn't move focus on that control #statesCheck(pFrame.radio2,",
"have correct states statesCheck(pFrame.label1, \"Label\") statesCheck(pFrame.label2, \"Label\") statesCheck(pFrame.label3, \"Label\") # click on checkbox",
"panel2's state statesCheck(pFrame.panel2, \"Panel\") # close application frame window pFrame.quit() print \"INFO: Log",
"children's AtkAccessible ########################### # panel should be focused, but focus on its child",
"app back if app is None: exit(4) # just an alias to make",
"if checkbox and radiobutton in panel still have correct actions actionsCheck(pFrame.check1, \"CheckBox\") actionsCheck(pFrame.check2,",
"actionsCheck(pFrame.radio2, \"RadioButton\") actionsCheck(pFrame.radio3, \"RadioButton\") ########################### # check panel's AtkAccessible ########################### # check panel",
"update label pFrame.radio2.click(log=True) sleep(config.SHORT_DELAY) pFrame.assertText(pFrame.label3, 'You are Female') # BUG525428 - doing click",
"* from helpers import * from states import * from actions import *",
"still have correct actions actionsCheck(pFrame.check1, \"CheckBox\") actionsCheck(pFrame.check2, \"CheckBox\") actionsCheck(pFrame.check3, \"CheckBox\") actionsCheck(pFrame.check4, \"CheckBox\") actionsCheck(pFrame.radio1,",
"from helpers import * from states import * from actions import * from",
"assert checked state rising pFrame.check2.click(log=True) sleep(config.SHORT_DELAY) # BUG525428 - doing click action doesn't",
"add_states=[\"checked\", \"focused\"]) # doesn't change panel2's state statesCheck(pFrame.panel2, \"Panel\") # close application frame",
"helpers import * from states import * from actions import * from sys",
"statesCheck(pFrame.panel1, \"Panel\") statesCheck(pFrame.panel2, \"Panel\") ########################### # check children's AtkAccessible ########################### # panel should",
"\"\"\" Test accessibility of Panel widget \"\"\" # imports from panel import *",
"invalid_states=[\"focusable\", \"sensitive\", \"enabled\"]) # check if label in panel still have correct states",
"panel still have correct states statesCheck(pFrame.check1, \"CheckBox\", add_states=[\"focused\"]) statesCheck(pFrame.check2, \"CheckBox\") statesCheck(pFrame.check3, \"CheckBox\", add_states=[\"checked\"])",
"panel2 to update label pFrame.radio2.click(log=True) sleep(config.SHORT_DELAY) pFrame.assertText(pFrame.label3, 'You are Female') # BUG525428 -",
"radiobutton which is in panel2 to update label pFrame.radio2.click(log=True) sleep(config.SHORT_DELAY) pFrame.assertText(pFrame.label3, 'You are",
"change panel2's state statesCheck(pFrame.panel2, \"Panel\") # close application frame window pFrame.quit() print \"INFO:",
"# ../samples/winforms/panel.py is the test sample script # panel/* is the wrapper of",
"app is None: exit(4) # just an alias to make things shorter pFrame",
"BUG525428 - doing click action doesn't move focus on that control #statesCheck(pFrame.check2, \"CheckBox\",",
"statesCheck(pFrame.label1, \"Label\") statesCheck(pFrame.label2, \"Label\") statesCheck(pFrame.label3, \"Label\") # click on checkbox which is in",
"script of panel # ../samples/winforms/panel.py is the test sample script # panel/* is",
"click on radiobutton which is in panel2 to update label pFrame.radio2.click(log=True) sleep(config.SHORT_DELAY) pFrame.assertText(pFrame.label3,",
"make sure we got the app back if app is None: exit(4) #",
"sample script ############################################################################## # The docstring below is used in the generated log",
"move focus on that control #statesCheck(pFrame.check2, \"CheckBox\", add_states=[\"checked\", \"focused\"]) statesCheck(pFrame.check3, \"CheckBox\", add_states=[\"checked\"]) #",
"try: app = launchPanel(app_path) except IOError, msg: print \"ERROR: %s\" % msg exit(2)",
"below is used in the generated log file \"\"\" Test accessibility of Panel",
"test sample script # panel/* is the wrapper of panel test sample script",
"checkbox and radiobutton in panel still have correct actions actionsCheck(pFrame.check1, \"CheckBox\") actionsCheck(pFrame.check2, \"CheckBox\")",
"- doing click action doesn't move focus on that control #statesCheck(pFrame.radio2, \"RadioButton\", add_states=[\"checked\",",
"* from states import * from actions import * from sys import argv",
"of panel # ../samples/winforms/panel.py is the test sample script # panel/* is the",
"statesCheck(pFrame.check4, \"CheckBox\", invalid_states=[\"sensitive\", \"enabled\",\"focusable\"]) statesCheck(pFrame.radio1, \"RadioButton\", add_states=[\"checked\"]) statesCheck(pFrame.radio2, \"RadioButton\") statesCheck(pFrame.radio3, \"RadioButton\", invalid_states=[\"focusable\", \"sensitive\",",
"# panel/* is the wrapper of panel test sample script ############################################################################## # The",
"shiftwidth=4 expandtab ############################################################################## # Written by: <NAME> <<EMAIL>> # Date: 10/21/2008 # Description:",
"the panel sample application try: app = launchPanel(app_path) except IOError, msg: print \"ERROR:",
"# vim: set tabstop=4 shiftwidth=4 expandtab ############################################################################## # Written by: <NAME> <<EMAIL>> #",
"panel still have correct states statesCheck(pFrame.label1, \"Label\") statesCheck(pFrame.label2, \"Label\") statesCheck(pFrame.label3, \"Label\") # click",
"of panel test sample script ############################################################################## # The docstring below is used in",
"AtkAccessible ########################### # check panel states statesCheck(pFrame.panel1, \"Panel\") statesCheck(pFrame.panel2, \"Panel\") ########################### # check",
"BUG525428 - doing click action doesn't move focus on that control #statesCheck(pFrame.radio2, \"RadioButton\",",
"add_states=[\"checked\"]) statesCheck(pFrame.check4, \"CheckBox\", invalid_states=[\"sensitive\", \"enabled\",\"focusable\"]) statesCheck(pFrame.radio1, \"RadioButton\", add_states=[\"checked\"]) statesCheck(pFrame.radio2, \"RadioButton\") statesCheck(pFrame.radio3, \"RadioButton\", invalid_states=[\"focusable\",",
"actionsCheck(pFrame.check1, \"CheckBox\") actionsCheck(pFrame.check2, \"CheckBox\") actionsCheck(pFrame.check3, \"CheckBox\") actionsCheck(pFrame.check4, \"CheckBox\") actionsCheck(pFrame.radio1, \"RadioButton\") actionsCheck(pFrame.radio2, \"RadioButton\") actionsCheck(pFrame.radio3,",
"\"CheckBox\") actionsCheck(pFrame.check3, \"CheckBox\") actionsCheck(pFrame.check4, \"CheckBox\") actionsCheck(pFrame.radio1, \"RadioButton\") actionsCheck(pFrame.radio2, \"RadioButton\") actionsCheck(pFrame.radio3, \"RadioButton\") ########################### #",
"import * from states import * from actions import * from sys import",
"\"RadioButton\", add_states=[\"checked\", \"focused\"]) # doesn't change panel2's state statesCheck(pFrame.panel2, \"Panel\") # close application",
"and radiobutton in panel still have correct actions actionsCheck(pFrame.check1, \"CheckBox\") actionsCheck(pFrame.check2, \"CheckBox\") actionsCheck(pFrame.check3,",
"% msg exit(2) # make sure we got the app back if app",
"still have correct states statesCheck(pFrame.check1, \"CheckBox\", add_states=[\"focused\"]) statesCheck(pFrame.check2, \"CheckBox\") statesCheck(pFrame.check3, \"CheckBox\", add_states=[\"checked\"]) statesCheck(pFrame.check4,",
"we got the app back if app is None: exit(4) # just an",
"########################### # check children's AtkAccessible ########################### # panel should be focused, but focus",
"# panel should be focused, but focus on its child # check if",
"in the generated log file \"\"\" Test accessibility of Panel widget \"\"\" #",
"# check panel's AtkAccessible ########################### # check panel states statesCheck(pFrame.panel1, \"Panel\") statesCheck(pFrame.panel2, \"Panel\")",
"The docstring below is used in the generated log file \"\"\" Test accessibility",
"tabstop=4 shiftwidth=4 expandtab ############################################################################## # Written by: <NAME> <<EMAIL>> # Date: 10/21/2008 #",
"back if app is None: exit(4) # just an alias to make things",
"check children's AtkAccessible ########################### # panel should be focused, but focus on its",
"sleep(config.SHORT_DELAY) # BUG525428 - doing click action doesn't move focus on that control",
"add_states=[\"checked\"]) statesCheck(pFrame.radio2, \"RadioButton\") statesCheck(pFrame.radio3, \"RadioButton\", invalid_states=[\"focusable\", \"sensitive\", \"enabled\"]) # check if label in",
"radiobutton in panel still have correct states statesCheck(pFrame.check1, \"CheckBox\", add_states=[\"focused\"]) statesCheck(pFrame.check2, \"CheckBox\") statesCheck(pFrame.check3,",
"\"CheckBox\", invalid_states=[\"sensitive\", \"enabled\",\"focusable\"]) statesCheck(pFrame.radio1, \"RadioButton\", add_states=[\"checked\"]) statesCheck(pFrame.radio2, \"RadioButton\") statesCheck(pFrame.radio3, \"RadioButton\", invalid_states=[\"focusable\", \"sensitive\", \"enabled\"])",
"launchPanel(app_path) except IOError, msg: print \"ERROR: %s\" % msg exit(2) # make sure",
"statesCheck(pFrame.radio2, \"RadioButton\") statesCheck(pFrame.radio3, \"RadioButton\", invalid_states=[\"focusable\", \"sensitive\", \"enabled\"]) # check if label in panel",
"add_states=[\"focused\"]) statesCheck(pFrame.check2, \"CheckBox\") statesCheck(pFrame.check3, \"CheckBox\", add_states=[\"checked\"]) statesCheck(pFrame.check4, \"CheckBox\", invalid_states=[\"sensitive\", \"enabled\",\"focusable\"]) statesCheck(pFrame.radio1, \"RadioButton\", add_states=[\"checked\"])",
"Test accessibility of Panel widget \"\"\" # imports from panel import * from",
"\"focused\"]) # doesn't change panel2's state statesCheck(pFrame.panel2, \"Panel\") # close application frame window",
"focus on its child # check if checkbox and radiobutton in panel still",
"app = launchPanel(app_path) except IOError, msg: print \"ERROR: %s\" % msg exit(2) #",
"\"CheckBox\") actionsCheck(pFrame.radio1, \"RadioButton\") actionsCheck(pFrame.radio2, \"RadioButton\") actionsCheck(pFrame.radio3, \"RadioButton\") ########################### # check panel's AtkAccessible ###########################",
"still have correct states statesCheck(pFrame.label1, \"Label\") statesCheck(pFrame.label2, \"Label\") statesCheck(pFrame.label3, \"Label\") # click on",
"# Written by: <NAME> <<EMAIL>> # Date: 10/21/2008 # Description: main test script",
"panel states statesCheck(pFrame.panel1, \"Panel\") statesCheck(pFrame.panel2, \"Panel\") ########################### # check children's AtkAccessible ########################### #",
"invalid_states=[\"sensitive\", \"enabled\",\"focusable\"]) statesCheck(pFrame.radio1, \"RadioButton\", add_states=[\"checked\"]) statesCheck(pFrame.radio2, \"RadioButton\") statesCheck(pFrame.radio3, \"RadioButton\", invalid_states=[\"focusable\", \"sensitive\", \"enabled\"]) #",
"########################### # panel should be focused, but focus on its child # check",
"# Description: main test script of panel # ../samples/winforms/panel.py is the test sample",
"doing click action doesn't move focus on that control #statesCheck(pFrame.radio2, \"RadioButton\", add_states=[\"checked\", \"focused\"])",
"# check if checkbox and radiobutton in panel still have correct states statesCheck(pFrame.check1,",
"statesCheck(pFrame.panel2, \"Panel\") # close application frame window pFrame.quit() print \"INFO: Log written to:",
"wrapper of panel test sample script ############################################################################## # The docstring below is used",
"\"RadioButton\") statesCheck(pFrame.radio3, \"RadioButton\", invalid_states=[\"focusable\", \"sensitive\", \"enabled\"]) # check if label in panel still",
"- doing click action doesn't move focus on that control #statesCheck(pFrame.check2, \"CheckBox\", add_states=[\"checked\",",
"which is in panel1 to assert checked state rising pFrame.check2.click(log=True) sleep(config.SHORT_DELAY) # BUG525428",
"#expected # open the panel sample application try: app = launchPanel(app_path) except IOError,",
"test sample script ############################################################################## # The docstring below is used in the generated",
"open the panel sample application try: app = launchPanel(app_path) except IOError, msg: print",
"check panel states statesCheck(pFrame.panel1, \"Panel\") statesCheck(pFrame.panel2, \"Panel\") ########################### # check children's AtkAccessible ###########################",
"= argv[1] except IndexError: pass #expected # open the panel sample application try:",
"\"Panel\") # click on radiobutton which is in panel2 to update label pFrame.radio2.click(log=True)",
"make things shorter pFrame = app.panelFrame ########################### # check children's AtkAction ########################### #",
"statesCheck(pFrame.radio3, \"RadioButton\", invalid_states=[\"focusable\", \"sensitive\", \"enabled\"]) # check if label in panel still have",
"########################### # check panel's AtkAccessible ########################### # check panel states statesCheck(pFrame.panel1, \"Panel\") statesCheck(pFrame.panel2,",
"check if checkbox and radiobutton in panel still have correct actions actionsCheck(pFrame.check1, \"CheckBox\")",
"correct states statesCheck(pFrame.check1, \"CheckBox\", add_states=[\"focused\"]) statesCheck(pFrame.check2, \"CheckBox\") statesCheck(pFrame.check3, \"CheckBox\", add_states=[\"checked\"]) statesCheck(pFrame.check4, \"CheckBox\", invalid_states=[\"sensitive\",",
"child # check if checkbox and radiobutton in panel still have correct states",
"states import * from actions import * from sys import argv app_path =",
"but focus on its child # check if checkbox and radiobutton in panel",
"# Date: 10/21/2008 # Description: main test script of panel # ../samples/winforms/panel.py is",
"app_path = None try: app_path = argv[1] except IndexError: pass #expected # open",
"Date: 10/21/2008 # Description: main test script of panel # ../samples/winforms/panel.py is the",
"\"\"\" # imports from panel import * from helpers import * from states",
"* from actions import * from sys import argv app_path = None try:",
"check if checkbox and radiobutton in panel still have correct states statesCheck(pFrame.check1, \"CheckBox\",",
"import * from actions import * from sys import argv app_path = None",
"on radiobutton which is in panel2 to update label pFrame.radio2.click(log=True) sleep(config.SHORT_DELAY) pFrame.assertText(pFrame.label3, 'You",
"\"Panel\") # close application frame window pFrame.quit() print \"INFO: Log written to: %s\"",
"app_path = argv[1] except IndexError: pass #expected # open the panel sample application",
"actions actionsCheck(pFrame.check1, \"CheckBox\") actionsCheck(pFrame.check2, \"CheckBox\") actionsCheck(pFrame.check3, \"CheckBox\") actionsCheck(pFrame.check4, \"CheckBox\") actionsCheck(pFrame.radio1, \"RadioButton\") actionsCheck(pFrame.radio2, \"RadioButton\")",
"application try: app = launchPanel(app_path) except IOError, msg: print \"ERROR: %s\" % msg",
"actionsCheck(pFrame.check2, \"CheckBox\") actionsCheck(pFrame.check3, \"CheckBox\") actionsCheck(pFrame.check4, \"CheckBox\") actionsCheck(pFrame.radio1, \"RadioButton\") actionsCheck(pFrame.radio2, \"RadioButton\") actionsCheck(pFrame.radio3, \"RadioButton\") ###########################",
"of Panel widget \"\"\" # imports from panel import * from helpers import",
"doesn't change panel2's state statesCheck(pFrame.panel2, \"Panel\") # close application frame window pFrame.quit() print",
"############################################################################## # Written by: <NAME> <<EMAIL>> # Date: 10/21/2008 # Description: main test",
"just an alias to make things shorter pFrame = app.panelFrame ########################### # check",
"\"sensitive\", \"enabled\"]) # check if label in panel still have correct states statesCheck(pFrame.label1,",
"None: exit(4) # just an alias to make things shorter pFrame = app.panelFrame",
"msg exit(2) # make sure we got the app back if app is",
"sure we got the app back if app is None: exit(4) # just",
"# open the panel sample application try: app = launchPanel(app_path) except IOError, msg:",
"'You are Female') # BUG525428 - doing click action doesn't move focus on",
"sleep(config.SHORT_DELAY) pFrame.assertText(pFrame.label3, 'You are Female') # BUG525428 - doing click action doesn't move",
"to update label pFrame.radio2.click(log=True) sleep(config.SHORT_DELAY) pFrame.assertText(pFrame.label3, 'You are Female') # BUG525428 - doing",
"doesn't move focus on that control #statesCheck(pFrame.check2, \"CheckBox\", add_states=[\"checked\", \"focused\"]) statesCheck(pFrame.check3, \"CheckBox\", add_states=[\"checked\"])",
"sample script # panel/* is the wrapper of panel test sample script ##############################################################################",
"panel import * from helpers import * from states import * from actions",
"to assert checked state rising pFrame.check2.click(log=True) sleep(config.SHORT_DELAY) # BUG525428 - doing click action",
"to make things shorter pFrame = app.panelFrame ########################### # check children's AtkAction ###########################",
"control #statesCheck(pFrame.check2, \"CheckBox\", add_states=[\"checked\", \"focused\"]) statesCheck(pFrame.check3, \"CheckBox\", add_states=[\"checked\"]) # doesn't change panel1's state",
"action doesn't move focus on that control #statesCheck(pFrame.check2, \"CheckBox\", add_states=[\"checked\", \"focused\"]) statesCheck(pFrame.check3, \"CheckBox\",",
"panel # ../samples/winforms/panel.py is the test sample script # panel/* is the wrapper",
"add_states=[\"checked\"]) # doesn't change panel1's state statesCheck(pFrame.panel1, \"Panel\") # click on radiobutton which",
"click action doesn't move focus on that control #statesCheck(pFrame.check2, \"CheckBox\", add_states=[\"checked\", \"focused\"]) statesCheck(pFrame.check3,",
"#statesCheck(pFrame.check2, \"CheckBox\", add_states=[\"checked\", \"focused\"]) statesCheck(pFrame.check3, \"CheckBox\", add_states=[\"checked\"]) # doesn't change panel1's state statesCheck(pFrame.panel1,",
"from actions import * from sys import argv app_path = None try: app_path",
"statesCheck(pFrame.panel2, \"Panel\") ########################### # check children's AtkAccessible ########################### # panel should be focused,",
"click on checkbox which is in panel1 to assert checked state rising pFrame.check2.click(log=True)",
"\"CheckBox\", add_states=[\"focused\"]) statesCheck(pFrame.check2, \"CheckBox\") statesCheck(pFrame.check3, \"CheckBox\", add_states=[\"checked\"]) statesCheck(pFrame.check4, \"CheckBox\", invalid_states=[\"sensitive\", \"enabled\",\"focusable\"]) statesCheck(pFrame.radio1, \"RadioButton\",",
"statesCheck(pFrame.radio1, \"RadioButton\", add_states=[\"checked\"]) statesCheck(pFrame.radio2, \"RadioButton\") statesCheck(pFrame.radio3, \"RadioButton\", invalid_states=[\"focusable\", \"sensitive\", \"enabled\"]) # check if",
"Panel widget \"\"\" # imports from panel import * from helpers import *",
"# make sure we got the app back if app is None: exit(4)",
"actions import * from sys import argv app_path = None try: app_path =",
"panel test sample script ############################################################################## # The docstring below is used in the",
"sys import argv app_path = None try: app_path = argv[1] except IndexError: pass",
"widget \"\"\" # imports from panel import * from helpers import * from",
"\"CheckBox\", add_states=[\"checked\", \"focused\"]) statesCheck(pFrame.check3, \"CheckBox\", add_states=[\"checked\"]) # doesn't change panel1's state statesCheck(pFrame.panel1, \"Panel\")",
"\"enabled\"]) # check if label in panel still have correct states statesCheck(pFrame.label1, \"Label\")",
"########################### # check panel states statesCheck(pFrame.panel1, \"Panel\") statesCheck(pFrame.panel2, \"Panel\") ########################### # check children's",
"# click on radiobutton which is in panel2 to update label pFrame.radio2.click(log=True) sleep(config.SHORT_DELAY)",
"the test sample script # panel/* is the wrapper of panel test sample",
"\"RadioButton\") ########################### # check panel's AtkAccessible ########################### # check panel states statesCheck(pFrame.panel1, \"Panel\")",
"../samples/winforms/panel.py is the test sample script # panel/* is the wrapper of panel",
"if label in panel still have correct states statesCheck(pFrame.label1, \"Label\") statesCheck(pFrame.label2, \"Label\") statesCheck(pFrame.label3,",
"actionsCheck(pFrame.radio1, \"RadioButton\") actionsCheck(pFrame.radio2, \"RadioButton\") actionsCheck(pFrame.radio3, \"RadioButton\") ########################### # check panel's AtkAccessible ########################### #",
"checkbox and radiobutton in panel still have correct states statesCheck(pFrame.check1, \"CheckBox\", add_states=[\"focused\"]) statesCheck(pFrame.check2,",
"children's AtkAction ########################### # check if checkbox and radiobutton in panel still have",
"in panel2 to update label pFrame.radio2.click(log=True) sleep(config.SHORT_DELAY) pFrame.assertText(pFrame.label3, 'You are Female') # BUG525428",
"\"Panel\") ########################### # check children's AtkAccessible ########################### # panel should be focused, but",
"from panel import * from helpers import * from states import * from",
"on its child # check if checkbox and radiobutton in panel still have",
"* from sys import argv app_path = None try: app_path = argv[1] except",
"statesCheck(pFrame.label3, \"Label\") # click on checkbox which is in panel1 to assert checked",
"panel still have correct actions actionsCheck(pFrame.check1, \"CheckBox\") actionsCheck(pFrame.check2, \"CheckBox\") actionsCheck(pFrame.check3, \"CheckBox\") actionsCheck(pFrame.check4, \"CheckBox\")",
"an alias to make things shorter pFrame = app.panelFrame ########################### # check children's",
"# The docstring below is used in the generated log file \"\"\" Test",
"# check if checkbox and radiobutton in panel still have correct actions actionsCheck(pFrame.check1,",
"be focused, but focus on its child # check if checkbox and radiobutton",
"alias to make things shorter pFrame = app.panelFrame ########################### # check children's AtkAction",
"is the test sample script # panel/* is the wrapper of panel test",
"accessibility of Panel widget \"\"\" # imports from panel import * from helpers",
"python # vim: set tabstop=4 shiftwidth=4 expandtab ############################################################################## # Written by: <NAME> <<EMAIL>>",
"\"CheckBox\") actionsCheck(pFrame.check4, \"CheckBox\") actionsCheck(pFrame.radio1, \"RadioButton\") actionsCheck(pFrame.radio2, \"RadioButton\") actionsCheck(pFrame.radio3, \"RadioButton\") ########################### # check panel's",
"on checkbox which is in panel1 to assert checked state rising pFrame.check2.click(log=True) sleep(config.SHORT_DELAY)",
"statesCheck(pFrame.label2, \"Label\") statesCheck(pFrame.label3, \"Label\") # click on checkbox which is in panel1 to",
"main test script of panel # ../samples/winforms/panel.py is the test sample script #",
"# check children's AtkAction ########################### # check if checkbox and radiobutton in panel",
"# close application frame window pFrame.quit() print \"INFO: Log written to: %s\" %",
"import argv app_path = None try: app_path = argv[1] except IndexError: pass #expected",
"rising pFrame.check2.click(log=True) sleep(config.SHORT_DELAY) # BUG525428 - doing click action doesn't move focus on",
"should be focused, but focus on its child # check if checkbox and",
"panel sample application try: app = launchPanel(app_path) except IOError, msg: print \"ERROR: %s\"",
"state rising pFrame.check2.click(log=True) sleep(config.SHORT_DELAY) # BUG525428 - doing click action doesn't move focus",
"is in panel2 to update label pFrame.radio2.click(log=True) sleep(config.SHORT_DELAY) pFrame.assertText(pFrame.label3, 'You are Female') #",
"# doesn't change panel2's state statesCheck(pFrame.panel2, \"Panel\") # close application frame window pFrame.quit()"
] |
[
"('compute', 'app_catalog_listing', 'get'): ['compute', 'pic', 'listing', 'get'], ('compute', 'app_catalog_listing', 'list'): ['compute', 'pic', 'listing',",
"'app_catalog_subscription', 'create'): ['compute', 'pic', 'subscription', 'create'], ('compute', 'app_catalog_subscription', 'delete'): ['compute', 'pic', 'subscription', 'delete'],",
"(c) 2016, 2019, Oracle and/or its affiliates. All rights reserved. # These mappings",
"'app_catalog_listing_resource_version', 'get'): ['compute', 'pic', 'version', 'get'], ('compute', 'app_catalog_listing_resource_version', 'list'): ['compute', 'pic', 'version', 'list'],",
"mappings are used by generated tests to look up operations that have been",
"'pic', 'subscription', 'create'], ('compute', 'app_catalog_subscription', 'delete'): ['compute', 'pic', 'subscription', 'delete'], ('compute', 'app_catalog_subscription', 'list'):",
"['compute', 'pic', 'agreements', 'get'], ('compute', 'app_catalog_subscription', 'create'): ['compute', 'pic', 'subscription', 'create'], ('compute', 'app_catalog_subscription',",
"tests to look up operations that have been moved in code in the",
"'subscription', 'create'], ('compute', 'app_catalog_subscription', 'delete'): ['compute', 'pic', 'subscription', 'delete'], ('compute', 'app_catalog_subscription', 'list'): ['compute',",
"2016, 2019, Oracle and/or its affiliates. All rights reserved. # These mappings are",
"'app_catalog_listing_resource_version_agreements', 'get-app-catalog-listing-agreements'): ['compute', 'pic', 'agreements', 'get'], ('compute', 'app_catalog_subscription', 'create'): ['compute', 'pic', 'subscription', 'create'],",
"Copyright (c) 2016, 2019, Oracle and/or its affiliates. All rights reserved. # These",
"'pic', 'version', 'get'], ('compute', 'app_catalog_listing_resource_version', 'list'): ['compute', 'pic', 'version', 'list'], ('compute', 'app_catalog_listing_resource_version_agreements', 'get-app-catalog-listing-agreements'):",
"that have been moved in code in the CLI. MOVED_COMMANDS = { ('compute',",
"2019, Oracle and/or its affiliates. All rights reserved. # These mappings are used",
"['compute', 'pic', 'listing', 'list'], ('compute', 'app_catalog_listing_resource_version', 'get'): ['compute', 'pic', 'version', 'get'], ('compute', 'app_catalog_listing_resource_version',",
"look up operations that have been moved in code in the CLI. MOVED_COMMANDS",
"have been moved in code in the CLI. MOVED_COMMANDS = { ('compute', 'app_catalog_listing',",
"'listing', 'list'], ('compute', 'app_catalog_listing_resource_version', 'get'): ['compute', 'pic', 'version', 'get'], ('compute', 'app_catalog_listing_resource_version', 'list'): ['compute',",
"'get'], ('compute', 'app_catalog_subscription', 'create'): ['compute', 'pic', 'subscription', 'create'], ('compute', 'app_catalog_subscription', 'delete'): ['compute', 'pic',",
"# Copyright (c) 2016, 2019, Oracle and/or its affiliates. All rights reserved. #",
"to look up operations that have been moved in code in the CLI.",
"'create'): ['compute', 'pic', 'subscription', 'create'], ('compute', 'app_catalog_subscription', 'delete'): ['compute', 'pic', 'subscription', 'delete'], ('compute',",
"been moved in code in the CLI. MOVED_COMMANDS = { ('compute', 'app_catalog_listing', 'get'):",
"{ ('compute', 'app_catalog_listing', 'get'): ['compute', 'pic', 'listing', 'get'], ('compute', 'app_catalog_listing', 'list'): ['compute', 'pic',",
"('compute', 'app_catalog_listing_resource_version', 'get'): ['compute', 'pic', 'version', 'get'], ('compute', 'app_catalog_listing_resource_version', 'list'): ['compute', 'pic', 'version',",
"['compute', 'pic', 'subscription', 'create'], ('compute', 'app_catalog_subscription', 'delete'): ['compute', 'pic', 'subscription', 'delete'], ('compute', 'app_catalog_subscription',",
"'create'], ('compute', 'app_catalog_subscription', 'delete'): ['compute', 'pic', 'subscription', 'delete'], ('compute', 'app_catalog_subscription', 'list'): ['compute', 'pic',",
"('compute', 'app_catalog_listing_resource_version_agreements', 'get-app-catalog-listing-agreements'): ['compute', 'pic', 'agreements', 'get'], ('compute', 'app_catalog_subscription', 'create'): ['compute', 'pic', 'subscription',",
"used by generated tests to look up operations that have been moved in",
"('compute', 'app_catalog_listing_resource_version', 'list'): ['compute', 'pic', 'version', 'list'], ('compute', 'app_catalog_listing_resource_version_agreements', 'get-app-catalog-listing-agreements'): ['compute', 'pic', 'agreements',",
"'delete'): ['compute', 'pic', 'subscription', 'delete'], ('compute', 'app_catalog_subscription', 'list'): ['compute', 'pic', 'subscription', 'list'] }",
"'get'): ['compute', 'pic', 'listing', 'get'], ('compute', 'app_catalog_listing', 'list'): ['compute', 'pic', 'listing', 'list'], ('compute',",
"rights reserved. # These mappings are used by generated tests to look up",
"'agreements', 'get'], ('compute', 'app_catalog_subscription', 'create'): ['compute', 'pic', 'subscription', 'create'], ('compute', 'app_catalog_subscription', 'delete'): ['compute',",
"'app_catalog_subscription', 'delete'): ['compute', 'pic', 'subscription', 'delete'], ('compute', 'app_catalog_subscription', 'list'): ['compute', 'pic', 'subscription', 'list']",
"generated tests to look up operations that have been moved in code in",
"and/or its affiliates. All rights reserved. # These mappings are used by generated",
"CLI. MOVED_COMMANDS = { ('compute', 'app_catalog_listing', 'get'): ['compute', 'pic', 'listing', 'get'], ('compute', 'app_catalog_listing',",
"'pic', 'agreements', 'get'], ('compute', 'app_catalog_subscription', 'create'): ['compute', 'pic', 'subscription', 'create'], ('compute', 'app_catalog_subscription', 'delete'):",
"utf-8 # Copyright (c) 2016, 2019, Oracle and/or its affiliates. All rights reserved.",
"# coding: utf-8 # Copyright (c) 2016, 2019, Oracle and/or its affiliates. All",
"by generated tests to look up operations that have been moved in code",
"MOVED_COMMANDS = { ('compute', 'app_catalog_listing', 'get'): ['compute', 'pic', 'listing', 'get'], ('compute', 'app_catalog_listing', 'list'):",
"All rights reserved. # These mappings are used by generated tests to look",
"are used by generated tests to look up operations that have been moved",
"'listing', 'get'], ('compute', 'app_catalog_listing', 'list'): ['compute', 'pic', 'listing', 'list'], ('compute', 'app_catalog_listing_resource_version', 'get'): ['compute',",
"['compute', 'pic', 'version', 'get'], ('compute', 'app_catalog_listing_resource_version', 'list'): ['compute', 'pic', 'version', 'list'], ('compute', 'app_catalog_listing_resource_version_agreements',",
"'pic', 'version', 'list'], ('compute', 'app_catalog_listing_resource_version_agreements', 'get-app-catalog-listing-agreements'): ['compute', 'pic', 'agreements', 'get'], ('compute', 'app_catalog_subscription', 'create'):",
"moved in code in the CLI. MOVED_COMMANDS = { ('compute', 'app_catalog_listing', 'get'): ['compute',",
"'get'): ['compute', 'pic', 'version', 'get'], ('compute', 'app_catalog_listing_resource_version', 'list'): ['compute', 'pic', 'version', 'list'], ('compute',",
"'pic', 'listing', 'list'], ('compute', 'app_catalog_listing_resource_version', 'get'): ['compute', 'pic', 'version', 'get'], ('compute', 'app_catalog_listing_resource_version', 'list'):",
"'app_catalog_listing', 'get'): ['compute', 'pic', 'listing', 'get'], ('compute', 'app_catalog_listing', 'list'): ['compute', 'pic', 'listing', 'list'],",
"in code in the CLI. MOVED_COMMANDS = { ('compute', 'app_catalog_listing', 'get'): ['compute', 'pic',",
"['compute', 'pic', 'listing', 'get'], ('compute', 'app_catalog_listing', 'list'): ['compute', 'pic', 'listing', 'list'], ('compute', 'app_catalog_listing_resource_version',",
"Oracle and/or its affiliates. All rights reserved. # These mappings are used by",
"'get'], ('compute', 'app_catalog_listing_resource_version', 'list'): ['compute', 'pic', 'version', 'list'], ('compute', 'app_catalog_listing_resource_version_agreements', 'get-app-catalog-listing-agreements'): ['compute', 'pic',",
"'list'): ['compute', 'pic', 'listing', 'list'], ('compute', 'app_catalog_listing_resource_version', 'get'): ['compute', 'pic', 'version', 'get'], ('compute',",
"operations that have been moved in code in the CLI. MOVED_COMMANDS = {",
"in the CLI. MOVED_COMMANDS = { ('compute', 'app_catalog_listing', 'get'): ['compute', 'pic', 'listing', 'get'],",
"('compute', 'app_catalog_subscription', 'create'): ['compute', 'pic', 'subscription', 'create'], ('compute', 'app_catalog_subscription', 'delete'): ['compute', 'pic', 'subscription',",
"'get-app-catalog-listing-agreements'): ['compute', 'pic', 'agreements', 'get'], ('compute', 'app_catalog_subscription', 'create'): ['compute', 'pic', 'subscription', 'create'], ('compute',",
"the CLI. MOVED_COMMANDS = { ('compute', 'app_catalog_listing', 'get'): ['compute', 'pic', 'listing', 'get'], ('compute',",
"'get'], ('compute', 'app_catalog_listing', 'list'): ['compute', 'pic', 'listing', 'list'], ('compute', 'app_catalog_listing_resource_version', 'get'): ['compute', 'pic',",
"up operations that have been moved in code in the CLI. MOVED_COMMANDS =",
"['compute', 'pic', 'version', 'list'], ('compute', 'app_catalog_listing_resource_version_agreements', 'get-app-catalog-listing-agreements'): ['compute', 'pic', 'agreements', 'get'], ('compute', 'app_catalog_subscription',",
"# These mappings are used by generated tests to look up operations that",
"'list'): ['compute', 'pic', 'version', 'list'], ('compute', 'app_catalog_listing_resource_version_agreements', 'get-app-catalog-listing-agreements'): ['compute', 'pic', 'agreements', 'get'], ('compute',",
"('compute', 'app_catalog_listing', 'list'): ['compute', 'pic', 'listing', 'list'], ('compute', 'app_catalog_listing_resource_version', 'get'): ['compute', 'pic', 'version',",
"= { ('compute', 'app_catalog_listing', 'get'): ['compute', 'pic', 'listing', 'get'], ('compute', 'app_catalog_listing', 'list'): ['compute',",
"('compute', 'app_catalog_subscription', 'delete'): ['compute', 'pic', 'subscription', 'delete'], ('compute', 'app_catalog_subscription', 'list'): ['compute', 'pic', 'subscription',",
"'app_catalog_listing', 'list'): ['compute', 'pic', 'listing', 'list'], ('compute', 'app_catalog_listing_resource_version', 'get'): ['compute', 'pic', 'version', 'get'],",
"These mappings are used by generated tests to look up operations that have",
"'list'], ('compute', 'app_catalog_listing_resource_version', 'get'): ['compute', 'pic', 'version', 'get'], ('compute', 'app_catalog_listing_resource_version', 'list'): ['compute', 'pic',",
"'version', 'list'], ('compute', 'app_catalog_listing_resource_version_agreements', 'get-app-catalog-listing-agreements'): ['compute', 'pic', 'agreements', 'get'], ('compute', 'app_catalog_subscription', 'create'): ['compute',",
"'pic', 'listing', 'get'], ('compute', 'app_catalog_listing', 'list'): ['compute', 'pic', 'listing', 'list'], ('compute', 'app_catalog_listing_resource_version', 'get'):",
"'list'], ('compute', 'app_catalog_listing_resource_version_agreements', 'get-app-catalog-listing-agreements'): ['compute', 'pic', 'agreements', 'get'], ('compute', 'app_catalog_subscription', 'create'): ['compute', 'pic',",
"coding: utf-8 # Copyright (c) 2016, 2019, Oracle and/or its affiliates. All rights",
"reserved. # These mappings are used by generated tests to look up operations",
"'version', 'get'], ('compute', 'app_catalog_listing_resource_version', 'list'): ['compute', 'pic', 'version', 'list'], ('compute', 'app_catalog_listing_resource_version_agreements', 'get-app-catalog-listing-agreements'): ['compute',",
"affiliates. All rights reserved. # These mappings are used by generated tests to",
"code in the CLI. MOVED_COMMANDS = { ('compute', 'app_catalog_listing', 'get'): ['compute', 'pic', 'listing',",
"'app_catalog_listing_resource_version', 'list'): ['compute', 'pic', 'version', 'list'], ('compute', 'app_catalog_listing_resource_version_agreements', 'get-app-catalog-listing-agreements'): ['compute', 'pic', 'agreements', 'get'],",
"its affiliates. All rights reserved. # These mappings are used by generated tests"
] |
[
"import ckan.plugins.toolkit as tk def {{cookiecutter.project_shortname}}_get_sum(): not_empty = tk.get_validator(\"not_empty\") convert_int = tk.get_validator(\"convert_int\") return",
"= tk.get_validator(\"not_empty\") convert_int = tk.get_validator(\"convert_int\") return { \"left\": [not_empty, convert_int], \"right\": [not_empty, convert_int]",
"tk def {{cookiecutter.project_shortname}}_get_sum(): not_empty = tk.get_validator(\"not_empty\") convert_int = tk.get_validator(\"convert_int\") return { \"left\": [not_empty,",
"<reponame>gg2/ckan import ckan.plugins.toolkit as tk def {{cookiecutter.project_shortname}}_get_sum(): not_empty = tk.get_validator(\"not_empty\") convert_int = tk.get_validator(\"convert_int\")",
"def {{cookiecutter.project_shortname}}_get_sum(): not_empty = tk.get_validator(\"not_empty\") convert_int = tk.get_validator(\"convert_int\") return { \"left\": [not_empty, convert_int],",
"{{cookiecutter.project_shortname}}_get_sum(): not_empty = tk.get_validator(\"not_empty\") convert_int = tk.get_validator(\"convert_int\") return { \"left\": [not_empty, convert_int], \"right\":",
"ckan.plugins.toolkit as tk def {{cookiecutter.project_shortname}}_get_sum(): not_empty = tk.get_validator(\"not_empty\") convert_int = tk.get_validator(\"convert_int\") return {",
"not_empty = tk.get_validator(\"not_empty\") convert_int = tk.get_validator(\"convert_int\") return { \"left\": [not_empty, convert_int], \"right\": [not_empty,",
"as tk def {{cookiecutter.project_shortname}}_get_sum(): not_empty = tk.get_validator(\"not_empty\") convert_int = tk.get_validator(\"convert_int\") return { \"left\":",
"tk.get_validator(\"not_empty\") convert_int = tk.get_validator(\"convert_int\") return { \"left\": [not_empty, convert_int], \"right\": [not_empty, convert_int] }"
] |
[
"preprocore from hots import corpus from nlpyutil import Logger from .ltp import Ltp",
"最低tfidf限制 :param allow_tags: 统计指定词性的词,如果为空则表示所有词性 :return: \"\"\" corpus_data, _ = corpus.process_origin_corpus_data(corpus_data, split=False, level=corpus.CorpusItemLevel.Article) _logger.info(\"start",
"corpus from nlpyutil import Logger from .ltp import Ltp _mds = set() DEFAULT_CSV_COLS",
"空白分割] :return: word_list: 词典列表 word_count_list: 词统计列表 idf_list: idfs列表 \"\"\" if not corpus: return",
"'cat', 'dog', 'fish'] 列表形式呈现文章生成的词典 word_list = cv.get_feature_names() # 词频统计 word_count_list = cv_fit.sum(axis=0).tolist() word_count_list",
":return: 返回词统计结果列表,每个元素:('词', 个数, idf值, 全局的tf-idf值) \"\"\" word_counter_path = os.path.join(common.HOT_WORDS_PATH, \"word_statistics_{}.pkl\".format(name_prefix)) with open(word_counter_path, 'rb')",
"from hots import common from nlpyutil import preprocess as preprocore from hots import",
"词典列表 word_count_list: 词统计列表 idf_list: idfs列表 \"\"\" if not corpus: return None, None, None",
"open(common.FILTER_HOT_WORDS_PATH, encoding='UTF-8').readlines()]) _STOPWORDS = preprocore.get_stopwords() def word_count_and_idf(corpus, idf=False): \"\"\" 词频统计 和 idf值计算 :param",
"if not corpus: return None, None, None cv = CountVectorizer(stop_words=_STOPWORDS) cv_fit = cv.fit_transform(corpus)",
"毕业 与 中国 科学院\", \"我 爱 北京 天安门\"] word_list, word_count_list, idf_list = word_count_and_idf(corpus)",
"filepath = os.path.join(common.DATA_PROCESSED_PATH, name_prefix + \".corpus\") count_words_with_corpus(filepath) \"\"\" corpus = [\"我 来到 北京",
"# word_count_list = np.array(word_count_list) # idf_list = np.array(idf_list) # tfidf_list = word_count_list *",
"assert len(word_list) == len(word_count_list) # analyzer='word',token_pattern=u\"(?u)\\\\b\\\\w+\\\\b\" idf_list = [] if idf: transformer =",
"the dump\") \"\"\" return total_counter def load_word_statistics(name_prefix) -> Counter: \"\"\" :param name_prefix: :return:",
"= Ltp(exword_path=common.SELF_USER_WV_DICT) _HOT_FILTER_WORDS = set([word.strip() for word in open(common.FILTER_HOT_WORDS_PATH, encoding='UTF-8').readlines()]) _STOPWORDS = preprocore.get_stopwords()",
"18:00 # @Author : WangKun # @Email : <EMAIL> import os import pickle",
"word_counter_path = os.path.join(common.HOT_WORDS_PATH, \"word_statistics_{}.pkl\".format(name_prefix)) with open(word_counter_path, 'rb') as f: word_counter = pickle.load(f) return",
"def count_words_with_corpus(corpus_data, name_prefix, data_mark, allow_tags=['n', 'j', 'i'], deny_tags=['nt', 'nd']): \"\"\" 在处理好的数据集上进行词频统计 :param filepath:",
"del total_counter[word] continue word_tags = _ltp.ltp_postagger(word) if len(word_tags) == 1: word_tag = word_tags[0]",
"corpus = [\"我 来到 北京 清华大学\", \"他 来到 了 网易 杭研 大厦\", \"小明",
"count\") # 根据词性过滤 for word in list(total_counter.keys()): if total_counter[word] < 10: del total_counter[word]",
"partial_len]) for idx in range(0, len(corpus_data), partial_len)) total_counter = Counter() for counter in",
"= word_tags[0] # 如果当前词的词性属于deny_tags中,则直接跳过 deny = any(word_tag[1].startswith(tag) for tag in deny_tags) if deny:",
"len(idf_list) == len(word_count_list) return word_list, word_count_list, idf_list def count_and_filter_single(partial_corpus): word_list, word_count_list, idf_list =",
"in list(total_counter.keys()): if total_counter[word] < 10: del total_counter[word] continue if word in _HOT_FILTER_WORDS:",
"partial_len = len(corpus_data) num_task = 1 partial_results = Parallel(n_jobs=num_task, backend=\"multiprocessing\")( delayed(count_and_filter_single)(corpus_data[idx:idx + partial_len])",
"word in _HOT_FILTER_WORDS: del total_counter[word] continue word_tags = _ltp.ltp_postagger(word) if len(word_tags) == 1:",
"collections import Counter import numpy as np from joblib import Parallel, delayed from",
"== 1: word_tag = word_tags[0] # 如果当前词的词性属于deny_tags中,则直接跳过 deny = any(word_tag[1].startswith(tag) for tag in",
"\"\"\" 在处理好的数据集上进行词频统计 :param filepath: :param count_base: 词的最低频次 :param idf_base: 最低idf限制 :param tfidf_base: 最低tfidf限制",
"[文章1 空白分割, 文章2 空白分割] :return: word_list: 词典列表 word_count_list: 词统计列表 idf_list: idfs列表 \"\"\" if",
"filepath: :param count_base: 词的最低频次 :param idf_base: 最低idf限制 :param tfidf_base: 最低tfidf限制 :param allow_tags: 统计指定词性的词,如果为空则表示所有词性",
"name_prefix: :return: 返回词统计结果列表,每个元素:('词', 个数, idf值, 全局的tf-idf值) \"\"\" word_counter_path = os.path.join(common.HOT_WORDS_PATH, \"word_statistics_{}.pkl\".format(name_prefix)) with open(word_counter_path,",
"in _HOT_FILTER_WORDS: del total_counter[word] continue word_tags = _ltp.ltp_postagger(word) if len(word_tags) == 1: word_tag",
"ValueError(\"parameter error\") name_prefix = sys.argv[1] filepath = os.path.join(common.DATA_PROCESSED_PATH, name_prefix + \".corpus\") count_words_with_corpus(filepath) \"\"\"",
"_ = corpus.process_origin_corpus_data(corpus_data, split=False, level=corpus.CorpusItemLevel.Article) _logger.info(\"start counting with multi thread\") num_task = max(1,",
"del total_counter[word] continue allow = any(word_tag[1].startswith(tag) for tag in allow_tags) if not allow:",
"hots import corpus from nlpyutil import Logger from .ltp import Ltp _mds =",
":param allow_tags: 统计指定词性的词,如果为空则表示所有词性 :return: \"\"\" corpus_data, _ = corpus.process_origin_corpus_data(corpus_data, split=False, level=corpus.CorpusItemLevel.Article) _logger.info(\"start counting",
"\"\"\" corpus = [\"我 来到 北京 清华大学\", \"他 来到 了 网易 杭研 大厦\",",
"CountVectorizer from hots import common from nlpyutil import preprocess as preprocore from hots",
"continue allow = any(word_tag[1].startswith(tag) for tag in allow_tags) if not allow: del total_counter[word]",
"load_word_statistics(name_prefix) -> Counter: \"\"\" :param name_prefix: :return: 返回词统计结果列表,每个元素:('词', 个数, idf值, 全局的tf-idf值) \"\"\" word_counter_path",
"None, None cv = CountVectorizer(stop_words=_STOPWORDS) cv_fit = cv.fit_transform(corpus) # ['bird', 'cat', 'dog', 'fish']",
"word_count_and_idf(corpus, idf=False): \"\"\" 词频统计 和 idf值计算 :param corpus: [文章1 空白分割, 文章2 空白分割] :return:",
"tfidf_base: 最低tfidf限制 :param allow_tags: 统计指定词性的词,如果为空则表示所有词性 :return: \"\"\" corpus_data, _ = corpus.process_origin_corpus_data(corpus_data, split=False, level=corpus.CorpusItemLevel.Article)",
"partial_len)) total_counter = Counter() for counter in partial_results: total_counter.update(counter) # 根据条件进行过滤 _logger.info(\"start filtering",
"joblib import Parallel, delayed from sklearn.feature_extraction.text import TfidfTransformer, CountVectorizer from hots import common",
"transformer = TfidfTransformer() tfidf = transformer.fit(cv_fit) # 计算全局的tfidf值 idf_list = tfidf.idf_ assert len(idf_list)",
"cv_fit.sum(axis=0).tolist() word_count_list = word_count_list[0] assert len(word_list) == len(word_count_list) # analyzer='word',token_pattern=u\"(?u)\\\\b\\\\w+\\\\b\" idf_list = []",
"= transformer.fit(cv_fit) # 计算全局的tfidf值 idf_list = tfidf.idf_ assert len(idf_list) == len(word_count_list) return word_list,",
"import pickle import sys from collections import Counter import numpy as np from",
"# tfidf_list = word_count_list * idf_list # word_statistics_list = list(zip(word_list, word_count_list, idf_list, tfidf_list))",
"return word_counter def count_words_with_corpus(corpus_data, name_prefix, data_mark, allow_tags=['n', 'j', 'i'], deny_tags=['nt', 'nd']): \"\"\" 在处理好的数据集上进行词频统计",
"os import pickle import sys from collections import Counter import numpy as np",
"corpus_data, _ = corpus.process_origin_corpus_data(corpus_data, split=False, level=corpus.CorpusItemLevel.Article) _logger.info(\"start counting with multi thread\") num_task =",
"与 中国 科学院\", \"我 爱 北京 天安门\"] word_list, word_count_list, idf_list = word_count_and_idf(corpus) print(word_list)",
"with multi thread\") num_task = max(1, common.NUM_CPU) partial_len = int(np.ceil(len(corpus_data) / num_task)) if",
"if total_counter[word] < 10: del total_counter[word] continue if word in _HOT_FILTER_WORDS: del total_counter[word]",
"word_list: 词典列表 word_count_list: 词统计列表 idf_list: idfs列表 \"\"\" if not corpus: return None, None,",
"from joblib import Parallel, delayed from sklearn.feature_extraction.text import TfidfTransformer, CountVectorizer from hots import",
"科学院\", \"我 爱 北京 天安门\"] word_list, word_count_list, idf_list = word_count_and_idf(corpus) print(word_list) print(word_count_list) print(idf_list)",
"del total_counter[word] continue if word in _HOT_FILTER_WORDS: del total_counter[word] continue word_tags = _ltp.ltp_postagger(word)",
":param corpus: [文章1 空白分割, 文章2 空白分割] :return: word_list: 词典列表 word_count_list: 词统计列表 idf_list: idfs列表",
"pickle file\") with open(word_statistics_list_path, 'wb') as f: pickle.dump(total_counter, f) _logger.info(\"finished the dump\") \"\"\"",
"continue if word in _HOT_FILTER_WORDS: del total_counter[word] continue word_tags = _ltp.ltp_postagger(word) if len(word_tags)",
"word_count_list))) return word_counter def count_words_with_corpus(corpus_data, name_prefix, data_mark, allow_tags=['n', 'j', 'i'], deny_tags=['nt', 'nd']): \"\"\"",
"== len(word_count_list) # analyzer='word',token_pattern=u\"(?u)\\\\b\\\\w+\\\\b\" idf_list = [] if idf: transformer = TfidfTransformer() tfidf",
"int(np.ceil(len(corpus_data) / num_task)) if partial_len == 0: partial_len = len(corpus_data) num_task = 1",
"word_count_list = cv_fit.sum(axis=0).tolist() word_count_list = word_count_list[0] assert len(word_list) == len(word_count_list) # analyzer='word',token_pattern=u\"(?u)\\\\b\\\\w+\\\\b\" idf_list",
"common from nlpyutil import preprocess as preprocore from hots import corpus from nlpyutil",
"# @Email : <EMAIL> import os import pickle import sys from collections import",
"/ num_task)) if partial_len == 0: partial_len = len(corpus_data) num_task = 1 partial_results",
"import os import pickle import sys from collections import Counter import numpy as",
"_HOT_FILTER_WORDS = set([word.strip() for word in open(common.FILTER_HOT_WORDS_PATH, encoding='UTF-8').readlines()]) _STOPWORDS = preprocore.get_stopwords() def word_count_and_idf(corpus,",
"tag in deny_tags) if deny: del total_counter[word] continue allow = any(word_tag[1].startswith(tag) for tag",
"count_words_with_corpus(corpus_data, name_prefix, data_mark, allow_tags=['n', 'j', 'i'], deny_tags=['nt', 'nd']): \"\"\" 在处理好的数据集上进行词频统计 :param filepath: :param",
"multi thread\") num_task = max(1, common.NUM_CPU) partial_len = int(np.ceil(len(corpus_data) / num_task)) if partial_len",
"allow_tags: 统计指定词性的词,如果为空则表示所有词性 :return: \"\"\" corpus_data, _ = corpus.process_origin_corpus_data(corpus_data, split=False, level=corpus.CorpusItemLevel.Article) _logger.info(\"start counting with",
"None cv = CountVectorizer(stop_words=_STOPWORDS) cv_fit = cv.fit_transform(corpus) # ['bird', 'cat', 'dog', 'fish'] 列表形式呈现文章生成的词典",
"\"他 来到 了 网易 杭研 大厦\", \"小明 硕士 毕业 与 中国 科学院\", \"我",
"1 partial_results = Parallel(n_jobs=num_task, backend=\"multiprocessing\")( delayed(count_and_filter_single)(corpus_data[idx:idx + partial_len]) for idx in range(0, len(corpus_data),",
"import preprocess as preprocore from hots import corpus from nlpyutil import Logger from",
"range(0, len(corpus_data), partial_len)) total_counter = Counter() for counter in partial_results: total_counter.update(counter) # 根据条件进行过滤",
"# @Time : 2020/9/1 18:00 # @Author : WangKun # @Email : <EMAIL>",
"idf_list # word_statistics_list = list(zip(word_list, word_count_list, idf_list, tfidf_list)) word_counter = Counter(dict(zip(word_list, word_count_list))) return",
"num_task = max(1, common.NUM_CPU) partial_len = int(np.ceil(len(corpus_data) / num_task)) if partial_len == 0:",
"backend=\"multiprocessing\")( delayed(count_and_filter_single)(corpus_data[idx:idx + partial_len]) for idx in range(0, len(corpus_data), partial_len)) total_counter = Counter()",
"raise ValueError(\"parameter error\") name_prefix = sys.argv[1] filepath = os.path.join(common.DATA_PROCESSED_PATH, name_prefix + \".corpus\") count_words_with_corpus(filepath)",
"idf值, 全局的tf-idf值) \"\"\" word_counter_path = os.path.join(common.HOT_WORDS_PATH, \"word_statistics_{}.pkl\".format(name_prefix)) with open(word_counter_path, 'rb') as f: word_counter",
"partial_len == 0: partial_len = len(corpus_data) num_task = 1 partial_results = Parallel(n_jobs=num_task, backend=\"multiprocessing\")(",
"'__main__': if len(sys.argv) != 2: raise ValueError(\"parameter error\") name_prefix = sys.argv[1] filepath =",
"for idx in range(0, len(corpus_data), partial_len)) total_counter = Counter() for counter in partial_results:",
"count_and_filter_single(partial_corpus): word_list, word_count_list, idf_list = word_count_and_idf(partial_corpus, idf=False) if not word_list or not word_count_list:",
"_HOT_FILTER_WORDS: del total_counter[word] continue word_tags = _ltp.ltp_postagger(word) if len(word_tags) == 1: word_tag =",
"_logger.info(\"dump to pickle file\") with open(word_statistics_list_path, 'wb') as f: pickle.dump(total_counter, f) _logger.info(\"finished the",
"if idf: transformer = TfidfTransformer() tfidf = transformer.fit(cv_fit) # 计算全局的tfidf值 idf_list = tfidf.idf_",
"word_list or not word_count_list: return Counter() # word_count_list = np.array(word_count_list) # idf_list =",
"name_prefix)) _logger.info(\"dump to pickle file\") with open(word_statistics_list_path, 'wb') as f: pickle.dump(total_counter, f) _logger.info(\"finished",
"for word in list(total_counter.keys()): if total_counter[word] < 10: del total_counter[word] continue if word",
"and count\") # 根据词性过滤 for word in list(total_counter.keys()): if total_counter[word] < 10: del",
"or not word_count_list: return Counter() # word_count_list = np.array(word_count_list) # idf_list = np.array(idf_list)",
"__name__ == '__main__': if len(sys.argv) != 2: raise ValueError(\"parameter error\") name_prefix = sys.argv[1]",
"= os.path.join(common.HOT_WORDS_PATH, \"word_statistics_{}.pkl\".format(name_prefix)) with open(word_counter_path, 'rb') as f: word_counter = pickle.load(f) return word_counter",
"word_statistics_list = list(zip(word_list, word_count_list, idf_list, tfidf_list)) word_counter = Counter(dict(zip(word_list, word_count_list))) return word_counter def",
"word_count_list, idf_list = word_count_and_idf(partial_corpus, idf=False) if not word_list or not word_count_list: return Counter()",
"计算全局的tfidf值 idf_list = tfidf.idf_ assert len(idf_list) == len(word_count_list) return word_list, word_count_list, idf_list def",
"'wb') as f: pickle.dump(total_counter, f) _logger.info(\"finished the dump\") \"\"\" return total_counter def load_word_statistics(name_prefix)",
"= Parallel(n_jobs=num_task, backend=\"multiprocessing\")( delayed(count_and_filter_single)(corpus_data[idx:idx + partial_len]) for idx in range(0, len(corpus_data), partial_len)) total_counter",
"os.path.join(common.HOT_WORDS_PATH, \"{}_word_statistics_{}.pkl\".format(data_mark, name_prefix)) _logger.info(\"dump to pickle file\") with open(word_statistics_list_path, 'wb') as f: pickle.dump(total_counter,",
"idf: transformer = TfidfTransformer() tfidf = transformer.fit(cv_fit) # 计算全局的tfidf值 idf_list = tfidf.idf_ assert",
"analyzer='word',token_pattern=u\"(?u)\\\\b\\\\w+\\\\b\" idf_list = [] if idf: transformer = TfidfTransformer() tfidf = transformer.fit(cv_fit) #",
"for word in open(common.FILTER_HOT_WORDS_PATH, encoding='UTF-8').readlines()]) _STOPWORDS = preprocore.get_stopwords() def word_count_and_idf(corpus, idf=False): \"\"\" 词频统计",
"== 0: partial_len = len(corpus_data) num_task = 1 partial_results = Parallel(n_jobs=num_task, backend=\"multiprocessing\")( delayed(count_and_filter_single)(corpus_data[idx:idx",
"@Author : WangKun # @Email : <EMAIL> import os import pickle import sys",
"\".corpus\") count_words_with_corpus(filepath) \"\"\" corpus = [\"我 来到 北京 清华大学\", \"他 来到 了 网易",
"import Ltp _mds = set() DEFAULT_CSV_COLS = 5 _logger = Logger() _ltp =",
"os.path.join(common.DATA_PROCESSED_PATH, name_prefix + \".corpus\") count_words_with_corpus(filepath) \"\"\" corpus = [\"我 来到 北京 清华大学\", \"他",
": WangKun # @Email : <EMAIL> import os import pickle import sys from",
"word_counter = Counter(dict(zip(word_list, word_count_list))) return word_counter def count_words_with_corpus(corpus_data, name_prefix, data_mark, allow_tags=['n', 'j', 'i'],",
"Counter: \"\"\" :param name_prefix: :return: 返回词统计结果列表,每个元素:('词', 个数, idf值, 全局的tf-idf值) \"\"\" word_counter_path = os.path.join(common.HOT_WORDS_PATH,",
"word in list(total_counter.keys()): if total_counter[word] < 10: del total_counter[word] continue if word in",
"np.array(idf_list) # tfidf_list = word_count_list * idf_list # word_statistics_list = list(zip(word_list, word_count_list, idf_list,",
"WangKun # @Email : <EMAIL> import os import pickle import sys from collections",
"word_counter def count_words_with_corpus(corpus_data, name_prefix, data_mark, allow_tags=['n', 'j', 'i'], deny_tags=['nt', 'nd']): \"\"\" 在处理好的数据集上进行词频统计 :param",
"tag in allow_tags) if not allow: del total_counter[word] \"\"\" word_statistics_list_path = os.path.join(common.HOT_WORDS_PATH, \"{}_word_statistics_{}.pkl\".format(data_mark,",
"< 10: del total_counter[word] continue if word in _HOT_FILTER_WORDS: del total_counter[word] continue word_tags",
"= _ltp.ltp_postagger(word) if len(word_tags) == 1: word_tag = word_tags[0] # 如果当前词的词性属于deny_tags中,则直接跳过 deny =",
"not allow: del total_counter[word] \"\"\" word_statistics_list_path = os.path.join(common.HOT_WORDS_PATH, \"{}_word_statistics_{}.pkl\".format(data_mark, name_prefix)) _logger.info(\"dump to pickle",
"词频统计 word_count_list = cv_fit.sum(axis=0).tolist() word_count_list = word_count_list[0] assert len(word_list) == len(word_count_list) # analyzer='word',token_pattern=u\"(?u)\\\\b\\\\w+\\\\b\"",
"allow_tags=['n', 'j', 'i'], deny_tags=['nt', 'nd']): \"\"\" 在处理好的数据集上进行词频统计 :param filepath: :param count_base: 词的最低频次 :param",
"assert len(idf_list) == len(word_count_list) return word_list, word_count_list, idf_list def count_and_filter_single(partial_corpus): word_list, word_count_list, idf_list",
"= max(1, common.NUM_CPU) partial_len = int(np.ceil(len(corpus_data) / num_task)) if partial_len == 0: partial_len",
"\"\"\" 词频统计 和 idf值计算 :param corpus: [文章1 空白分割, 文章2 空白分割] :return: word_list: 词典列表",
"2020/9/1 18:00 # @Author : WangKun # @Email : <EMAIL> import os import",
"utf-8 -*- # @Time : 2020/9/1 18:00 # @Author : WangKun # @Email",
"as np from joblib import Parallel, delayed from sklearn.feature_extraction.text import TfidfTransformer, CountVectorizer from",
"the with postag and count\") # 根据词性过滤 for word in list(total_counter.keys()): if total_counter[word]",
"了 网易 杭研 大厦\", \"小明 硕士 毕业 与 中国 科学院\", \"我 爱 北京",
"len(word_tags) == 1: word_tag = word_tags[0] # 如果当前词的词性属于deny_tags中,则直接跳过 deny = any(word_tag[1].startswith(tag) for tag",
"列表形式呈现文章生成的词典 word_list = cv.get_feature_names() # 词频统计 word_count_list = cv_fit.sum(axis=0).tolist() word_count_list = word_count_list[0] assert",
"len(sys.argv) != 2: raise ValueError(\"parameter error\") name_prefix = sys.argv[1] filepath = os.path.join(common.DATA_PROCESSED_PATH, name_prefix",
"\"{}_word_statistics_{}.pkl\".format(data_mark, name_prefix)) _logger.info(\"dump to pickle file\") with open(word_statistics_list_path, 'wb') as f: pickle.dump(total_counter, f)",
"= cv.fit_transform(corpus) # ['bird', 'cat', 'dog', 'fish'] 列表形式呈现文章生成的词典 word_list = cv.get_feature_names() # 词频统计",
"0: partial_len = len(corpus_data) num_task = 1 partial_results = Parallel(n_jobs=num_task, backend=\"multiprocessing\")( delayed(count_and_filter_single)(corpus_data[idx:idx +",
"词统计列表 idf_list: idfs列表 \"\"\" if not corpus: return None, None, None cv =",
"tfidf.idf_ assert len(idf_list) == len(word_count_list) return word_list, word_count_list, idf_list def count_and_filter_single(partial_corpus): word_list, word_count_list,",
"[\"我 来到 北京 清华大学\", \"他 来到 了 网易 杭研 大厦\", \"小明 硕士 毕业",
"= tfidf.idf_ assert len(idf_list) == len(word_count_list) return word_list, word_count_list, idf_list def count_and_filter_single(partial_corpus): word_list,",
"name_prefix = sys.argv[1] filepath = os.path.join(common.DATA_PROCESSED_PATH, name_prefix + \".corpus\") count_words_with_corpus(filepath) \"\"\" corpus =",
"num_task = 1 partial_results = Parallel(n_jobs=num_task, backend=\"multiprocessing\")( delayed(count_and_filter_single)(corpus_data[idx:idx + partial_len]) for idx in",
"if word in _HOT_FILTER_WORDS: del total_counter[word] continue word_tags = _ltp.ltp_postagger(word) if len(word_tags) ==",
"= [\"我 来到 北京 清华大学\", \"他 来到 了 网易 杭研 大厦\", \"小明 硕士",
"with open(word_statistics_list_path, 'wb') as f: pickle.dump(total_counter, f) _logger.info(\"finished the dump\") \"\"\" return total_counter",
".ltp import Ltp _mds = set() DEFAULT_CSV_COLS = 5 _logger = Logger() _ltp",
"pickle.dump(total_counter, f) _logger.info(\"finished the dump\") \"\"\" return total_counter def load_word_statistics(name_prefix) -> Counter: \"\"\"",
"cv.fit_transform(corpus) # ['bird', 'cat', 'dog', 'fish'] 列表形式呈现文章生成的词典 word_list = cv.get_feature_names() # 词频统计 word_count_list",
"np.array(word_count_list) # idf_list = np.array(idf_list) # tfidf_list = word_count_list * idf_list # word_statistics_list",
"词的最低频次 :param idf_base: 最低idf限制 :param tfidf_base: 最低tfidf限制 :param allow_tags: 统计指定词性的词,如果为空则表示所有词性 :return: \"\"\" corpus_data,",
"word_counter if __name__ == '__main__': if len(sys.argv) != 2: raise ValueError(\"parameter error\") name_prefix",
"name_prefix + \".corpus\") count_words_with_corpus(filepath) \"\"\" corpus = [\"我 来到 北京 清华大学\", \"他 来到",
"idf_list: idfs列表 \"\"\" if not corpus: return None, None, None cv = CountVectorizer(stop_words=_STOPWORDS)",
"== len(word_count_list) return word_list, word_count_list, idf_list def count_and_filter_single(partial_corpus): word_list, word_count_list, idf_list = word_count_and_idf(partial_corpus,",
":return: \"\"\" corpus_data, _ = corpus.process_origin_corpus_data(corpus_data, split=False, level=corpus.CorpusItemLevel.Article) _logger.info(\"start counting with multi thread\")",
"<reponame>Brokenwind/hots<filename>src/hots/count_words.py<gh_stars>0 # -*- coding: utf-8 -*- # @Time : 2020/9/1 18:00 # @Author",
"hots import common from nlpyutil import preprocess as preprocore from hots import corpus",
"delayed(count_and_filter_single)(corpus_data[idx:idx + partial_len]) for idx in range(0, len(corpus_data), partial_len)) total_counter = Counter() for",
"with postag and count\") # 根据词性过滤 for word in list(total_counter.keys()): if total_counter[word] <",
"Counter() # word_count_list = np.array(word_count_list) # idf_list = np.array(idf_list) # tfidf_list = word_count_list",
"word_tags[0] # 如果当前词的词性属于deny_tags中,则直接跳过 deny = any(word_tag[1].startswith(tag) for tag in deny_tags) if deny: del",
"def load_word_statistics(name_prefix) -> Counter: \"\"\" :param name_prefix: :return: 返回词统计结果列表,每个元素:('词', 个数, idf值, 全局的tf-idf值) \"\"\"",
"-*- # @Time : 2020/9/1 18:00 # @Author : WangKun # @Email :",
"if not allow: del total_counter[word] \"\"\" word_statistics_list_path = os.path.join(common.HOT_WORDS_PATH, \"{}_word_statistics_{}.pkl\".format(data_mark, name_prefix)) _logger.info(\"dump to",
"idf值计算 :param corpus: [文章1 空白分割, 文章2 空白分割] :return: word_list: 词典列表 word_count_list: 词统计列表 idf_list:",
"word_count_list, idf_list def count_and_filter_single(partial_corpus): word_list, word_count_list, idf_list = word_count_and_idf(partial_corpus, idf=False) if not word_list",
"num_task)) if partial_len == 0: partial_len = len(corpus_data) num_task = 1 partial_results =",
"= CountVectorizer(stop_words=_STOPWORDS) cv_fit = cv.fit_transform(corpus) # ['bird', 'cat', 'dog', 'fish'] 列表形式呈现文章生成的词典 word_list =",
"with open(word_counter_path, 'rb') as f: word_counter = pickle.load(f) return word_counter if __name__ ==",
"np from joblib import Parallel, delayed from sklearn.feature_extraction.text import TfidfTransformer, CountVectorizer from hots",
"-*- coding: utf-8 -*- # @Time : 2020/9/1 18:00 # @Author : WangKun",
"in range(0, len(corpus_data), partial_len)) total_counter = Counter() for counter in partial_results: total_counter.update(counter) #",
"清华大学\", \"他 来到 了 网易 杭研 大厦\", \"小明 硕士 毕业 与 中国 科学院\",",
"'rb') as f: word_counter = pickle.load(f) return word_counter if __name__ == '__main__': if",
"tfidf = transformer.fit(cv_fit) # 计算全局的tfidf值 idf_list = tfidf.idf_ assert len(idf_list) == len(word_count_list) return",
"全局的tf-idf值) \"\"\" word_counter_path = os.path.join(common.HOT_WORDS_PATH, \"word_statistics_{}.pkl\".format(name_prefix)) with open(word_counter_path, 'rb') as f: word_counter =",
"as f: pickle.dump(total_counter, f) _logger.info(\"finished the dump\") \"\"\" return total_counter def load_word_statistics(name_prefix) ->",
"idf_base: 最低idf限制 :param tfidf_base: 最低tfidf限制 :param allow_tags: 统计指定词性的词,如果为空则表示所有词性 :return: \"\"\" corpus_data, _ =",
"len(corpus_data), partial_len)) total_counter = Counter() for counter in partial_results: total_counter.update(counter) # 根据条件进行过滤 _logger.info(\"start",
"Counter() for counter in partial_results: total_counter.update(counter) # 根据条件进行过滤 _logger.info(\"start filtering the with postag",
"<EMAIL> import os import pickle import sys from collections import Counter import numpy",
"encoding='UTF-8').readlines()]) _STOPWORDS = preprocore.get_stopwords() def word_count_and_idf(corpus, idf=False): \"\"\" 词频统计 和 idf值计算 :param corpus:",
"返回词统计结果列表,每个元素:('词', 个数, idf值, 全局的tf-idf值) \"\"\" word_counter_path = os.path.join(common.HOT_WORDS_PATH, \"word_statistics_{}.pkl\".format(name_prefix)) with open(word_counter_path, 'rb') as",
"= cv.get_feature_names() # 词频统计 word_count_list = cv_fit.sum(axis=0).tolist() word_count_list = word_count_list[0] assert len(word_list) ==",
"count_base: 词的最低频次 :param idf_base: 最低idf限制 :param tfidf_base: 最低tfidf限制 :param allow_tags: 统计指定词性的词,如果为空则表示所有词性 :return: \"\"\"",
"idf_list = word_count_and_idf(partial_corpus, idf=False) if not word_list or not word_count_list: return Counter() #",
"if __name__ == '__main__': if len(sys.argv) != 2: raise ValueError(\"parameter error\") name_prefix =",
"Ltp(exword_path=common.SELF_USER_WV_DICT) _HOT_FILTER_WORDS = set([word.strip() for word in open(common.FILTER_HOT_WORDS_PATH, encoding='UTF-8').readlines()]) _STOPWORDS = preprocore.get_stopwords() def",
"deny_tags) if deny: del total_counter[word] continue allow = any(word_tag[1].startswith(tag) for tag in allow_tags)",
"Logger from .ltp import Ltp _mds = set() DEFAULT_CSV_COLS = 5 _logger =",
"partial_len = int(np.ceil(len(corpus_data) / num_task)) if partial_len == 0: partial_len = len(corpus_data) num_task",
"= TfidfTransformer() tfidf = transformer.fit(cv_fit) # 计算全局的tfidf值 idf_list = tfidf.idf_ assert len(idf_list) ==",
"word_tag = word_tags[0] # 如果当前词的词性属于deny_tags中,则直接跳过 deny = any(word_tag[1].startswith(tag) for tag in deny_tags) if",
"split=False, level=corpus.CorpusItemLevel.Article) _logger.info(\"start counting with multi thread\") num_task = max(1, common.NUM_CPU) partial_len =",
"word_list, word_count_list, idf_list def count_and_filter_single(partial_corpus): word_list, word_count_list, idf_list = word_count_and_idf(partial_corpus, idf=False) if not",
"_ltp = Ltp(exword_path=common.SELF_USER_WV_DICT) _HOT_FILTER_WORDS = set([word.strip() for word in open(common.FILTER_HOT_WORDS_PATH, encoding='UTF-8').readlines()]) _STOPWORDS =",
"None, None, None cv = CountVectorizer(stop_words=_STOPWORDS) cv_fit = cv.fit_transform(corpus) # ['bird', 'cat', 'dog',",
"'j', 'i'], deny_tags=['nt', 'nd']): \"\"\" 在处理好的数据集上进行词频统计 :param filepath: :param count_base: 词的最低频次 :param idf_base:",
"cv = CountVectorizer(stop_words=_STOPWORDS) cv_fit = cv.fit_transform(corpus) # ['bird', 'cat', 'dog', 'fish'] 列表形式呈现文章生成的词典 word_list",
"if len(sys.argv) != 2: raise ValueError(\"parameter error\") name_prefix = sys.argv[1] filepath = os.path.join(common.DATA_PROCESSED_PATH,",
"def count_and_filter_single(partial_corpus): word_list, word_count_list, idf_list = word_count_and_idf(partial_corpus, idf=False) if not word_list or not",
"\"word_statistics_{}.pkl\".format(name_prefix)) with open(word_counter_path, 'rb') as f: word_counter = pickle.load(f) return word_counter if __name__",
"numpy as np from joblib import Parallel, delayed from sklearn.feature_extraction.text import TfidfTransformer, CountVectorizer",
"TfidfTransformer, CountVectorizer from hots import common from nlpyutil import preprocess as preprocore from",
"= os.path.join(common.DATA_PROCESSED_PATH, name_prefix + \".corpus\") count_words_with_corpus(filepath) \"\"\" corpus = [\"我 来到 北京 清华大学\",",
"total_counter[word] continue if word in _HOT_FILTER_WORDS: del total_counter[word] continue word_tags = _ltp.ltp_postagger(word) if",
"len(word_list) == len(word_count_list) # analyzer='word',token_pattern=u\"(?u)\\\\b\\\\w+\\\\b\" idf_list = [] if idf: transformer = TfidfTransformer()",
":param filepath: :param count_base: 词的最低频次 :param idf_base: 最低idf限制 :param tfidf_base: 最低tfidf限制 :param allow_tags:",
"+ partial_len]) for idx in range(0, len(corpus_data), partial_len)) total_counter = Counter() for counter",
"import Parallel, delayed from sklearn.feature_extraction.text import TfidfTransformer, CountVectorizer from hots import common from",
"来到 了 网易 杭研 大厦\", \"小明 硕士 毕业 与 中国 科学院\", \"我 爱",
"= pickle.load(f) return word_counter if __name__ == '__main__': if len(sys.argv) != 2: raise",
"preprocore.get_stopwords() def word_count_and_idf(corpus, idf=False): \"\"\" 词频统计 和 idf值计算 :param corpus: [文章1 空白分割, 文章2",
"in deny_tags) if deny: del total_counter[word] continue allow = any(word_tag[1].startswith(tag) for tag in",
"空白分割, 文章2 空白分割] :return: word_list: 词典列表 word_count_list: 词统计列表 idf_list: idfs列表 \"\"\" if not",
"for tag in deny_tags) if deny: del total_counter[word] continue allow = any(word_tag[1].startswith(tag) for",
"level=corpus.CorpusItemLevel.Article) _logger.info(\"start counting with multi thread\") num_task = max(1, common.NUM_CPU) partial_len = int(np.ceil(len(corpus_data)",
"total_counter[word] continue word_tags = _ltp.ltp_postagger(word) if len(word_tags) == 1: word_tag = word_tags[0] #",
"* idf_list # word_statistics_list = list(zip(word_list, word_count_list, idf_list, tfidf_list)) word_counter = Counter(dict(zip(word_list, word_count_list)))",
"统计指定词性的词,如果为空则表示所有词性 :return: \"\"\" corpus_data, _ = corpus.process_origin_corpus_data(corpus_data, split=False, level=corpus.CorpusItemLevel.Article) _logger.info(\"start counting with multi",
"个数, idf值, 全局的tf-idf值) \"\"\" word_counter_path = os.path.join(common.HOT_WORDS_PATH, \"word_statistics_{}.pkl\".format(name_prefix)) with open(word_counter_path, 'rb') as f:",
"= os.path.join(common.HOT_WORDS_PATH, \"{}_word_statistics_{}.pkl\".format(data_mark, name_prefix)) _logger.info(\"dump to pickle file\") with open(word_statistics_list_path, 'wb') as f:",
"在处理好的数据集上进行词频统计 :param filepath: :param count_base: 词的最低频次 :param idf_base: 最低idf限制 :param tfidf_base: 最低tfidf限制 :param",
"total_counter.update(counter) # 根据条件进行过滤 _logger.info(\"start filtering the with postag and count\") # 根据词性过滤 for",
"杭研 大厦\", \"小明 硕士 毕业 与 中国 科学院\", \"我 爱 北京 天安门\"] word_list,",
"= int(np.ceil(len(corpus_data) / num_task)) if partial_len == 0: partial_len = len(corpus_data) num_task =",
"total_counter[word] < 10: del total_counter[word] continue if word in _HOT_FILTER_WORDS: del total_counter[word] continue",
"\"我 爱 北京 天安门\"] word_list, word_count_list, idf_list = word_count_and_idf(corpus) print(word_list) print(word_count_list) print(idf_list) \"\"\"",
"= word_count_and_idf(partial_corpus, idf=False) if not word_list or not word_count_list: return Counter() # word_count_list",
"idf=False): \"\"\" 词频统计 和 idf值计算 :param corpus: [文章1 空白分割, 文章2 空白分割] :return: word_list:",
"from collections import Counter import numpy as np from joblib import Parallel, delayed",
"nlpyutil import Logger from .ltp import Ltp _mds = set() DEFAULT_CSV_COLS = 5",
"2: raise ValueError(\"parameter error\") name_prefix = sys.argv[1] filepath = os.path.join(common.DATA_PROCESSED_PATH, name_prefix + \".corpus\")",
"DEFAULT_CSV_COLS = 5 _logger = Logger() _ltp = Ltp(exword_path=common.SELF_USER_WV_DICT) _HOT_FILTER_WORDS = set([word.strip() for",
": 2020/9/1 18:00 # @Author : WangKun # @Email : <EMAIL> import os",
"文章2 空白分割] :return: word_list: 词典列表 word_count_list: 词统计列表 idf_list: idfs列表 \"\"\" if not corpus:",
"'fish'] 列表形式呈现文章生成的词典 word_list = cv.get_feature_names() # 词频统计 word_count_list = cv_fit.sum(axis=0).tolist() word_count_list = word_count_list[0]",
"import Logger from .ltp import Ltp _mds = set() DEFAULT_CSV_COLS = 5 _logger",
"if partial_len == 0: partial_len = len(corpus_data) num_task = 1 partial_results = Parallel(n_jobs=num_task,",
"in allow_tags) if not allow: del total_counter[word] \"\"\" word_statistics_list_path = os.path.join(common.HOT_WORDS_PATH, \"{}_word_statistics_{}.pkl\".format(data_mark, name_prefix))",
"import Counter import numpy as np from joblib import Parallel, delayed from sklearn.feature_extraction.text",
"not word_count_list: return Counter() # word_count_list = np.array(word_count_list) # idf_list = np.array(idf_list) #",
"tfidf_list = word_count_list * idf_list # word_statistics_list = list(zip(word_list, word_count_list, idf_list, tfidf_list)) word_counter",
"= any(word_tag[1].startswith(tag) for tag in allow_tags) if not allow: del total_counter[word] \"\"\" word_statistics_list_path",
"# -*- coding: utf-8 -*- # @Time : 2020/9/1 18:00 # @Author :",
"set([word.strip() for word in open(common.FILTER_HOT_WORDS_PATH, encoding='UTF-8').readlines()]) _STOPWORDS = preprocore.get_stopwords() def word_count_and_idf(corpus, idf=False): \"\"\"",
"open(word_statistics_list_path, 'wb') as f: pickle.dump(total_counter, f) _logger.info(\"finished the dump\") \"\"\" return total_counter def",
"_ltp.ltp_postagger(word) if len(word_tags) == 1: word_tag = word_tags[0] # 如果当前词的词性属于deny_tags中,则直接跳过 deny = any(word_tag[1].startswith(tag)",
"in open(common.FILTER_HOT_WORDS_PATH, encoding='UTF-8').readlines()]) _STOPWORDS = preprocore.get_stopwords() def word_count_and_idf(corpus, idf=False): \"\"\" 词频统计 和 idf值计算",
"\"\"\" word_counter_path = os.path.join(common.HOT_WORDS_PATH, \"word_statistics_{}.pkl\".format(name_prefix)) with open(word_counter_path, 'rb') as f: word_counter = pickle.load(f)",
"import TfidfTransformer, CountVectorizer from hots import common from nlpyutil import preprocess as preprocore",
"allow = any(word_tag[1].startswith(tag) for tag in allow_tags) if not allow: del total_counter[word] \"\"\"",
"to pickle file\") with open(word_statistics_list_path, 'wb') as f: pickle.dump(total_counter, f) _logger.info(\"finished the dump\")",
"set() DEFAULT_CSV_COLS = 5 _logger = Logger() _ltp = Ltp(exword_path=common.SELF_USER_WV_DICT) _HOT_FILTER_WORDS = set([word.strip()",
"word_count_list: 词统计列表 idf_list: idfs列表 \"\"\" if not corpus: return None, None, None cv",
"_STOPWORDS = preprocore.get_stopwords() def word_count_and_idf(corpus, idf=False): \"\"\" 词频统计 和 idf值计算 :param corpus: [文章1",
"common.NUM_CPU) partial_len = int(np.ceil(len(corpus_data) / num_task)) if partial_len == 0: partial_len = len(corpus_data)",
"= set([word.strip() for word in open(common.FILTER_HOT_WORDS_PATH, encoding='UTF-8').readlines()]) _STOPWORDS = preprocore.get_stopwords() def word_count_and_idf(corpus, idf=False):",
"Counter import numpy as np from joblib import Parallel, delayed from sklearn.feature_extraction.text import",
"preprocess as preprocore from hots import corpus from nlpyutil import Logger from .ltp",
"counter in partial_results: total_counter.update(counter) # 根据条件进行过滤 _logger.info(\"start filtering the with postag and count\")",
"nlpyutil import preprocess as preprocore from hots import corpus from nlpyutil import Logger",
"\"\"\" if not corpus: return None, None, None cv = CountVectorizer(stop_words=_STOPWORDS) cv_fit =",
"_logger.info(\"start filtering the with postag and count\") # 根据词性过滤 for word in list(total_counter.keys()):",
"word_count_list = word_count_list[0] assert len(word_list) == len(word_count_list) # analyzer='word',token_pattern=u\"(?u)\\\\b\\\\w+\\\\b\" idf_list = [] if",
"sklearn.feature_extraction.text import TfidfTransformer, CountVectorizer from hots import common from nlpyutil import preprocess as",
"len(word_count_list) # analyzer='word',token_pattern=u\"(?u)\\\\b\\\\w+\\\\b\" idf_list = [] if idf: transformer = TfidfTransformer() tfidf =",
"any(word_tag[1].startswith(tag) for tag in deny_tags) if deny: del total_counter[word] continue allow = any(word_tag[1].startswith(tag)",
"transformer.fit(cv_fit) # 计算全局的tfidf值 idf_list = tfidf.idf_ assert len(idf_list) == len(word_count_list) return word_list, word_count_list,",
"sys from collections import Counter import numpy as np from joblib import Parallel,",
"= cv_fit.sum(axis=0).tolist() word_count_list = word_count_list[0] assert len(word_list) == len(word_count_list) # analyzer='word',token_pattern=u\"(?u)\\\\b\\\\w+\\\\b\" idf_list =",
"tfidf_list)) word_counter = Counter(dict(zip(word_list, word_count_list))) return word_counter def count_words_with_corpus(corpus_data, name_prefix, data_mark, allow_tags=['n', 'j',",
"# 计算全局的tfidf值 idf_list = tfidf.idf_ assert len(idf_list) == len(word_count_list) return word_list, word_count_list, idf_list",
"\"小明 硕士 毕业 与 中国 科学院\", \"我 爱 北京 天安门\"] word_list, word_count_list, idf_list",
"中国 科学院\", \"我 爱 北京 天安门\"] word_list, word_count_list, idf_list = word_count_and_idf(corpus) print(word_list) print(word_count_list)",
"词频统计 和 idf值计算 :param corpus: [文章1 空白分割, 文章2 空白分割] :return: word_list: 词典列表 word_count_list:",
"'nd']): \"\"\" 在处理好的数据集上进行词频统计 :param filepath: :param count_base: 词的最低频次 :param idf_base: 最低idf限制 :param tfidf_base:",
"word_count_and_idf(partial_corpus, idf=False) if not word_list or not word_count_list: return Counter() # word_count_list =",
"word in open(common.FILTER_HOT_WORDS_PATH, encoding='UTF-8').readlines()]) _STOPWORDS = preprocore.get_stopwords() def word_count_and_idf(corpus, idf=False): \"\"\" 词频统计 和",
":return: word_list: 词典列表 word_count_list: 词统计列表 idf_list: idfs列表 \"\"\" if not corpus: return None,",
"import numpy as np from joblib import Parallel, delayed from sklearn.feature_extraction.text import TfidfTransformer,",
"= Counter() for counter in partial_results: total_counter.update(counter) # 根据条件进行过滤 _logger.info(\"start filtering the with",
"for counter in partial_results: total_counter.update(counter) # 根据条件进行过滤 _logger.info(\"start filtering the with postag and",
"sys.argv[1] filepath = os.path.join(common.DATA_PROCESSED_PATH, name_prefix + \".corpus\") count_words_with_corpus(filepath) \"\"\" corpus = [\"我 来到",
"= Counter(dict(zip(word_list, word_count_list))) return word_counter def count_words_with_corpus(corpus_data, name_prefix, data_mark, allow_tags=['n', 'j', 'i'], deny_tags=['nt',",
"dump\") \"\"\" return total_counter def load_word_statistics(name_prefix) -> Counter: \"\"\" :param name_prefix: :return: 返回词统计结果列表,每个元素:('词',",
"pickle.load(f) return word_counter if __name__ == '__main__': if len(sys.argv) != 2: raise ValueError(\"parameter",
"= np.array(word_count_list) # idf_list = np.array(idf_list) # tfidf_list = word_count_list * idf_list #",
"word_count_list: return Counter() # word_count_list = np.array(word_count_list) # idf_list = np.array(idf_list) # tfidf_list",
"= corpus.process_origin_corpus_data(corpus_data, split=False, level=corpus.CorpusItemLevel.Article) _logger.info(\"start counting with multi thread\") num_task = max(1, common.NUM_CPU)",
"= len(corpus_data) num_task = 1 partial_results = Parallel(n_jobs=num_task, backend=\"multiprocessing\")( delayed(count_and_filter_single)(corpus_data[idx:idx + partial_len]) for",
"Counter(dict(zip(word_list, word_count_list))) return word_counter def count_words_with_corpus(corpus_data, name_prefix, data_mark, allow_tags=['n', 'j', 'i'], deny_tags=['nt', 'nd']):",
"allow: del total_counter[word] \"\"\" word_statistics_list_path = os.path.join(common.HOT_WORDS_PATH, \"{}_word_statistics_{}.pkl\".format(data_mark, name_prefix)) _logger.info(\"dump to pickle file\")",
"Ltp _mds = set() DEFAULT_CSV_COLS = 5 _logger = Logger() _ltp = Ltp(exword_path=common.SELF_USER_WV_DICT)",
"return total_counter def load_word_statistics(name_prefix) -> Counter: \"\"\" :param name_prefix: :return: 返回词统计结果列表,每个元素:('词', 个数, idf值,",
"open(word_counter_path, 'rb') as f: word_counter = pickle.load(f) return word_counter if __name__ == '__main__':",
"5 _logger = Logger() _ltp = Ltp(exword_path=common.SELF_USER_WV_DICT) _HOT_FILTER_WORDS = set([word.strip() for word in",
"idf_list = [] if idf: transformer = TfidfTransformer() tfidf = transformer.fit(cv_fit) # 计算全局的tfidf值",
"not corpus: return None, None, None cv = CountVectorizer(stop_words=_STOPWORDS) cv_fit = cv.fit_transform(corpus) #",
"thread\") num_task = max(1, common.NUM_CPU) partial_len = int(np.ceil(len(corpus_data) / num_task)) if partial_len ==",
"corpus: [文章1 空白分割, 文章2 空白分割] :return: word_list: 词典列表 word_count_list: 词统计列表 idf_list: idfs列表 \"\"\"",
"return Counter() # word_count_list = np.array(word_count_list) # idf_list = np.array(idf_list) # tfidf_list =",
":param idf_base: 最低idf限制 :param tfidf_base: 最低tfidf限制 :param allow_tags: 统计指定词性的词,如果为空则表示所有词性 :return: \"\"\" corpus_data, _",
"# idf_list = np.array(idf_list) # tfidf_list = word_count_list * idf_list # word_statistics_list =",
"deny: del total_counter[word] continue allow = any(word_tag[1].startswith(tag) for tag in allow_tags) if not",
"f: pickle.dump(total_counter, f) _logger.info(\"finished the dump\") \"\"\" return total_counter def load_word_statistics(name_prefix) -> Counter:",
"word_statistics_list_path = os.path.join(common.HOT_WORDS_PATH, \"{}_word_statistics_{}.pkl\".format(data_mark, name_prefix)) _logger.info(\"dump to pickle file\") with open(word_statistics_list_path, 'wb') as",
"= list(zip(word_list, word_count_list, idf_list, tfidf_list)) word_counter = Counter(dict(zip(word_list, word_count_list))) return word_counter def count_words_with_corpus(corpus_data,",
"any(word_tag[1].startswith(tag) for tag in allow_tags) if not allow: del total_counter[word] \"\"\" word_statistics_list_path =",
"# analyzer='word',token_pattern=u\"(?u)\\\\b\\\\w+\\\\b\" idf_list = [] if idf: transformer = TfidfTransformer() tfidf = transformer.fit(cv_fit)",
"f: word_counter = pickle.load(f) return word_counter if __name__ == '__main__': if len(sys.argv) !=",
"@Email : <EMAIL> import os import pickle import sys from collections import Counter",
"deny = any(word_tag[1].startswith(tag) for tag in deny_tags) if deny: del total_counter[word] continue allow",
"for tag in allow_tags) if not allow: del total_counter[word] \"\"\" word_statistics_list_path = os.path.join(common.HOT_WORDS_PATH,",
"TfidfTransformer() tfidf = transformer.fit(cv_fit) # 计算全局的tfidf值 idf_list = tfidf.idf_ assert len(idf_list) == len(word_count_list)",
"= any(word_tag[1].startswith(tag) for tag in deny_tags) if deny: del total_counter[word] continue allow =",
"counting with multi thread\") num_task = max(1, common.NUM_CPU) partial_len = int(np.ceil(len(corpus_data) / num_task))",
"根据条件进行过滤 _logger.info(\"start filtering the with postag and count\") # 根据词性过滤 for word in",
"= set() DEFAULT_CSV_COLS = 5 _logger = Logger() _ltp = Ltp(exword_path=common.SELF_USER_WV_DICT) _HOT_FILTER_WORDS =",
"if deny: del total_counter[word] continue allow = any(word_tag[1].startswith(tag) for tag in allow_tags) if",
"total_counter[word] \"\"\" word_statistics_list_path = os.path.join(common.HOT_WORDS_PATH, \"{}_word_statistics_{}.pkl\".format(data_mark, name_prefix)) _logger.info(\"dump to pickle file\") with open(word_statistics_list_path,",
"= sys.argv[1] filepath = os.path.join(common.DATA_PROCESSED_PATH, name_prefix + \".corpus\") count_words_with_corpus(filepath) \"\"\" corpus = [\"我",
"len(corpus_data) num_task = 1 partial_results = Parallel(n_jobs=num_task, backend=\"multiprocessing\")( delayed(count_and_filter_single)(corpus_data[idx:idx + partial_len]) for idx",
"total_counter[word] continue allow = any(word_tag[1].startswith(tag) for tag in allow_tags) if not allow: del",
"deny_tags=['nt', 'nd']): \"\"\" 在处理好的数据集上进行词频统计 :param filepath: :param count_base: 词的最低频次 :param idf_base: 最低idf限制 :param",
"_mds = set() DEFAULT_CSV_COLS = 5 _logger = Logger() _ltp = Ltp(exword_path=common.SELF_USER_WV_DICT) _HOT_FILTER_WORDS",
"def word_count_and_idf(corpus, idf=False): \"\"\" 词频统计 和 idf值计算 :param corpus: [文章1 空白分割, 文章2 空白分割]",
"from nlpyutil import Logger from .ltp import Ltp _mds = set() DEFAULT_CSV_COLS =",
"# word_statistics_list = list(zip(word_list, word_count_list, idf_list, tfidf_list)) word_counter = Counter(dict(zip(word_list, word_count_list))) return word_counter",
"# 根据词性过滤 for word in list(total_counter.keys()): if total_counter[word] < 10: del total_counter[word] continue",
"corpus: return None, None, None cv = CountVectorizer(stop_words=_STOPWORDS) cv_fit = cv.fit_transform(corpus) # ['bird',",
"return word_counter if __name__ == '__main__': if len(sys.argv) != 2: raise ValueError(\"parameter error\")",
"postag and count\") # 根据词性过滤 for word in list(total_counter.keys()): if total_counter[word] < 10:",
"word_count_list, idf_list, tfidf_list)) word_counter = Counter(dict(zip(word_list, word_count_list))) return word_counter def count_words_with_corpus(corpus_data, name_prefix, data_mark,",
"word_count_list * idf_list # word_statistics_list = list(zip(word_list, word_count_list, idf_list, tfidf_list)) word_counter = Counter(dict(zip(word_list,",
"_logger.info(\"finished the dump\") \"\"\" return total_counter def load_word_statistics(name_prefix) -> Counter: \"\"\" :param name_prefix:",
"idf_list def count_and_filter_single(partial_corpus): word_list, word_count_list, idf_list = word_count_and_idf(partial_corpus, idf=False) if not word_list or",
"== '__main__': if len(sys.argv) != 2: raise ValueError(\"parameter error\") name_prefix = sys.argv[1] filepath",
"来到 北京 清华大学\", \"他 来到 了 网易 杭研 大厦\", \"小明 硕士 毕业 与",
"idf_list = np.array(idf_list) # tfidf_list = word_count_list * idf_list # word_statistics_list = list(zip(word_list,",
"网易 杭研 大厦\", \"小明 硕士 毕业 与 中国 科学院\", \"我 爱 北京 天安门\"]",
"as preprocore from hots import corpus from nlpyutil import Logger from .ltp import",
"# 根据条件进行过滤 _logger.info(\"start filtering the with postag and count\") # 根据词性过滤 for word",
"!= 2: raise ValueError(\"parameter error\") name_prefix = sys.argv[1] filepath = os.path.join(common.DATA_PROCESSED_PATH, name_prefix +",
"total_counter = Counter() for counter in partial_results: total_counter.update(counter) # 根据条件进行过滤 _logger.info(\"start filtering the",
"total_counter def load_word_statistics(name_prefix) -> Counter: \"\"\" :param name_prefix: :return: 返回词统计结果列表,每个元素:('词', 个数, idf值, 全局的tf-idf值)",
"idx in range(0, len(corpus_data), partial_len)) total_counter = Counter() for counter in partial_results: total_counter.update(counter)",
"if not word_list or not word_count_list: return Counter() # word_count_list = np.array(word_count_list) #",
"北京 清华大学\", \"他 来到 了 网易 杭研 大厦\", \"小明 硕士 毕业 与 中国",
"in partial_results: total_counter.update(counter) # 根据条件进行过滤 _logger.info(\"start filtering the with postag and count\") #",
"= [] if idf: transformer = TfidfTransformer() tfidf = transformer.fit(cv_fit) # 计算全局的tfidf值 idf_list",
"= preprocore.get_stopwords() def word_count_and_idf(corpus, idf=False): \"\"\" 词频统计 和 idf值计算 :param corpus: [文章1 空白分割,",
"# ['bird', 'cat', 'dog', 'fish'] 列表形式呈现文章生成的词典 word_list = cv.get_feature_names() # 词频统计 word_count_list =",
"_logger.info(\"start counting with multi thread\") num_task = max(1, common.NUM_CPU) partial_len = int(np.ceil(len(corpus_data) /",
"partial_results: total_counter.update(counter) # 根据条件进行过滤 _logger.info(\"start filtering the with postag and count\") # 根据词性过滤",
"delayed from sklearn.feature_extraction.text import TfidfTransformer, CountVectorizer from hots import common from nlpyutil import",
"list(zip(word_list, word_count_list, idf_list, tfidf_list)) word_counter = Counter(dict(zip(word_list, word_count_list))) return word_counter def count_words_with_corpus(corpus_data, name_prefix,",
"import corpus from nlpyutil import Logger from .ltp import Ltp _mds = set()",
"error\") name_prefix = sys.argv[1] filepath = os.path.join(common.DATA_PROCESSED_PATH, name_prefix + \".corpus\") count_words_with_corpus(filepath) \"\"\" corpus",
"[] if idf: transformer = TfidfTransformer() tfidf = transformer.fit(cv_fit) # 计算全局的tfidf值 idf_list =",
"pickle import sys from collections import Counter import numpy as np from joblib",
"from .ltp import Ltp _mds = set() DEFAULT_CSV_COLS = 5 _logger = Logger()",
"word_count_list = np.array(word_count_list) # idf_list = np.array(idf_list) # tfidf_list = word_count_list * idf_list",
"os.path.join(common.HOT_WORDS_PATH, \"word_statistics_{}.pkl\".format(name_prefix)) with open(word_counter_path, 'rb') as f: word_counter = pickle.load(f) return word_counter if",
"cv.get_feature_names() # 词频统计 word_count_list = cv_fit.sum(axis=0).tolist() word_count_list = word_count_list[0] assert len(word_list) == len(word_count_list)",
"# @Author : WangKun # @Email : <EMAIL> import os import pickle import",
"\"\"\" return total_counter def load_word_statistics(name_prefix) -> Counter: \"\"\" :param name_prefix: :return: 返回词统计结果列表,每个元素:('词', 个数,",
"= word_count_list * idf_list # word_statistics_list = list(zip(word_list, word_count_list, idf_list, tfidf_list)) word_counter =",
"coding: utf-8 -*- # @Time : 2020/9/1 18:00 # @Author : WangKun #",
"根据词性过滤 for word in list(total_counter.keys()): if total_counter[word] < 10: del total_counter[word] continue if",
"name_prefix, data_mark, allow_tags=['n', 'j', 'i'], deny_tags=['nt', 'nd']): \"\"\" 在处理好的数据集上进行词频统计 :param filepath: :param count_base:",
"not word_list or not word_count_list: return Counter() # word_count_list = np.array(word_count_list) # idf_list",
"word_count_list[0] assert len(word_list) == len(word_count_list) # analyzer='word',token_pattern=u\"(?u)\\\\b\\\\w+\\\\b\" idf_list = [] if idf: transformer",
"Parallel(n_jobs=num_task, backend=\"multiprocessing\")( delayed(count_and_filter_single)(corpus_data[idx:idx + partial_len]) for idx in range(0, len(corpus_data), partial_len)) total_counter =",
"from nlpyutil import preprocess as preprocore from hots import corpus from nlpyutil import",
"最低idf限制 :param tfidf_base: 最低tfidf限制 :param allow_tags: 统计指定词性的词,如果为空则表示所有词性 :return: \"\"\" corpus_data, _ = corpus.process_origin_corpus_data(corpus_data,",
"partial_results = Parallel(n_jobs=num_task, backend=\"multiprocessing\")( delayed(count_and_filter_single)(corpus_data[idx:idx + partial_len]) for idx in range(0, len(corpus_data), partial_len))",
"'dog', 'fish'] 列表形式呈现文章生成的词典 word_list = cv.get_feature_names() # 词频统计 word_count_list = cv_fit.sum(axis=0).tolist() word_count_list =",
"# 如果当前词的词性属于deny_tags中,则直接跳过 deny = any(word_tag[1].startswith(tag) for tag in deny_tags) if deny: del total_counter[word]",
"10: del total_counter[word] continue if word in _HOT_FILTER_WORDS: del total_counter[word] continue word_tags =",
"= Logger() _ltp = Ltp(exword_path=common.SELF_USER_WV_DICT) _HOT_FILTER_WORDS = set([word.strip() for word in open(common.FILTER_HOT_WORDS_PATH, encoding='UTF-8').readlines()])",
"continue word_tags = _ltp.ltp_postagger(word) if len(word_tags) == 1: word_tag = word_tags[0] # 如果当前词的词性属于deny_tags中,则直接跳过",
": <EMAIL> import os import pickle import sys from collections import Counter import",
"'i'], deny_tags=['nt', 'nd']): \"\"\" 在处理好的数据集上进行词频统计 :param filepath: :param count_base: 词的最低频次 :param idf_base: 最低idf限制",
"count_words_with_corpus(filepath) \"\"\" corpus = [\"我 来到 北京 清华大学\", \"他 来到 了 网易 杭研",
"如果当前词的词性属于deny_tags中,则直接跳过 deny = any(word_tag[1].startswith(tag) for tag in deny_tags) if deny: del total_counter[word] continue",
"allow_tags) if not allow: del total_counter[word] \"\"\" word_statistics_list_path = os.path.join(common.HOT_WORDS_PATH, \"{}_word_statistics_{}.pkl\".format(data_mark, name_prefix)) _logger.info(\"dump",
"filtering the with postag and count\") # 根据词性过滤 for word in list(total_counter.keys()): if",
"import sys from collections import Counter import numpy as np from joblib import",
"idfs列表 \"\"\" if not corpus: return None, None, None cv = CountVectorizer(stop_words=_STOPWORDS) cv_fit",
"= 1 partial_results = Parallel(n_jobs=num_task, backend=\"multiprocessing\")( delayed(count_and_filter_single)(corpus_data[idx:idx + partial_len]) for idx in range(0,",
"idf_list = tfidf.idf_ assert len(idf_list) == len(word_count_list) return word_list, word_count_list, idf_list def count_and_filter_single(partial_corpus):",
"data_mark, allow_tags=['n', 'j', 'i'], deny_tags=['nt', 'nd']): \"\"\" 在处理好的数据集上进行词频统计 :param filepath: :param count_base: 词的最低频次",
"cv_fit = cv.fit_transform(corpus) # ['bird', 'cat', 'dog', 'fish'] 列表形式呈现文章生成的词典 word_list = cv.get_feature_names() #",
"\"\"\" :param name_prefix: :return: 返回词统计结果列表,每个元素:('词', 个数, idf值, 全局的tf-idf值) \"\"\" word_counter_path = os.path.join(common.HOT_WORDS_PATH, \"word_statistics_{}.pkl\".format(name_prefix))",
":param name_prefix: :return: 返回词统计结果列表,每个元素:('词', 个数, idf值, 全局的tf-idf值) \"\"\" word_counter_path = os.path.join(common.HOT_WORDS_PATH, \"word_statistics_{}.pkl\".format(name_prefix)) with",
"大厦\", \"小明 硕士 毕业 与 中国 科学院\", \"我 爱 北京 天安门\"] word_list, word_count_list,",
"@Time : 2020/9/1 18:00 # @Author : WangKun # @Email : <EMAIL> import",
":param count_base: 词的最低频次 :param idf_base: 最低idf限制 :param tfidf_base: 最低tfidf限制 :param allow_tags: 统计指定词性的词,如果为空则表示所有词性 :return:",
"Parallel, delayed from sklearn.feature_extraction.text import TfidfTransformer, CountVectorizer from hots import common from nlpyutil",
"+ \".corpus\") count_words_with_corpus(filepath) \"\"\" corpus = [\"我 来到 北京 清华大学\", \"他 来到 了",
"['bird', 'cat', 'dog', 'fish'] 列表形式呈现文章生成的词典 word_list = cv.get_feature_names() # 词频统计 word_count_list = cv_fit.sum(axis=0).tolist()",
"return None, None, None cv = CountVectorizer(stop_words=_STOPWORDS) cv_fit = cv.fit_transform(corpus) # ['bird', 'cat',",
"-> Counter: \"\"\" :param name_prefix: :return: 返回词统计结果列表,每个元素:('词', 个数, idf值, 全局的tf-idf值) \"\"\" word_counter_path =",
"word_list = cv.get_feature_names() # 词频统计 word_count_list = cv_fit.sum(axis=0).tolist() word_count_list = word_count_list[0] assert len(word_list)",
"return word_list, word_count_list, idf_list def count_and_filter_single(partial_corpus): word_list, word_count_list, idf_list = word_count_and_idf(partial_corpus, idf=False) if",
"max(1, common.NUM_CPU) partial_len = int(np.ceil(len(corpus_data) / num_task)) if partial_len == 0: partial_len =",
"list(total_counter.keys()): if total_counter[word] < 10: del total_counter[word] continue if word in _HOT_FILTER_WORDS: del",
"= word_count_list[0] assert len(word_list) == len(word_count_list) # analyzer='word',token_pattern=u\"(?u)\\\\b\\\\w+\\\\b\" idf_list = [] if idf:",
"\"\"\" word_statistics_list_path = os.path.join(common.HOT_WORDS_PATH, \"{}_word_statistics_{}.pkl\".format(data_mark, name_prefix)) _logger.info(\"dump to pickle file\") with open(word_statistics_list_path, 'wb')",
"f) _logger.info(\"finished the dump\") \"\"\" return total_counter def load_word_statistics(name_prefix) -> Counter: \"\"\" :param",
"= np.array(idf_list) # tfidf_list = word_count_list * idf_list # word_statistics_list = list(zip(word_list, word_count_list,",
"word_tags = _ltp.ltp_postagger(word) if len(word_tags) == 1: word_tag = word_tags[0] # 如果当前词的词性属于deny_tags中,则直接跳过 deny",
"import common from nlpyutil import preprocess as preprocore from hots import corpus from",
"硕士 毕业 与 中国 科学院\", \"我 爱 北京 天安门\"] word_list, word_count_list, idf_list =",
"Logger() _ltp = Ltp(exword_path=common.SELF_USER_WV_DICT) _HOT_FILTER_WORDS = set([word.strip() for word in open(common.FILTER_HOT_WORDS_PATH, encoding='UTF-8').readlines()]) _STOPWORDS",
"_logger = Logger() _ltp = Ltp(exword_path=common.SELF_USER_WV_DICT) _HOT_FILTER_WORDS = set([word.strip() for word in open(common.FILTER_HOT_WORDS_PATH,",
"corpus.process_origin_corpus_data(corpus_data, split=False, level=corpus.CorpusItemLevel.Article) _logger.info(\"start counting with multi thread\") num_task = max(1, common.NUM_CPU) partial_len",
"和 idf值计算 :param corpus: [文章1 空白分割, 文章2 空白分割] :return: word_list: 词典列表 word_count_list: 词统计列表",
"del total_counter[word] \"\"\" word_statistics_list_path = os.path.join(common.HOT_WORDS_PATH, \"{}_word_statistics_{}.pkl\".format(data_mark, name_prefix)) _logger.info(\"dump to pickle file\") with",
"# 词频统计 word_count_list = cv_fit.sum(axis=0).tolist() word_count_list = word_count_list[0] assert len(word_list) == len(word_count_list) #",
"idf_list, tfidf_list)) word_counter = Counter(dict(zip(word_list, word_count_list))) return word_counter def count_words_with_corpus(corpus_data, name_prefix, data_mark, allow_tags=['n',",
"from hots import corpus from nlpyutil import Logger from .ltp import Ltp _mds",
"as f: word_counter = pickle.load(f) return word_counter if __name__ == '__main__': if len(sys.argv)",
"len(word_count_list) return word_list, word_count_list, idf_list def count_and_filter_single(partial_corpus): word_list, word_count_list, idf_list = word_count_and_idf(partial_corpus, idf=False)",
"1: word_tag = word_tags[0] # 如果当前词的词性属于deny_tags中,则直接跳过 deny = any(word_tag[1].startswith(tag) for tag in deny_tags)",
"file\") with open(word_statistics_list_path, 'wb') as f: pickle.dump(total_counter, f) _logger.info(\"finished the dump\") \"\"\" return",
"CountVectorizer(stop_words=_STOPWORDS) cv_fit = cv.fit_transform(corpus) # ['bird', 'cat', 'dog', 'fish'] 列表形式呈现文章生成的词典 word_list = cv.get_feature_names()",
"idf=False) if not word_list or not word_count_list: return Counter() # word_count_list = np.array(word_count_list)",
"= 5 _logger = Logger() _ltp = Ltp(exword_path=common.SELF_USER_WV_DICT) _HOT_FILTER_WORDS = set([word.strip() for word",
"word_counter = pickle.load(f) return word_counter if __name__ == '__main__': if len(sys.argv) != 2:",
"if len(word_tags) == 1: word_tag = word_tags[0] # 如果当前词的词性属于deny_tags中,则直接跳过 deny = any(word_tag[1].startswith(tag) for",
"\"\"\" corpus_data, _ = corpus.process_origin_corpus_data(corpus_data, split=False, level=corpus.CorpusItemLevel.Article) _logger.info(\"start counting with multi thread\") num_task",
"from sklearn.feature_extraction.text import TfidfTransformer, CountVectorizer from hots import common from nlpyutil import preprocess",
":param tfidf_base: 最低tfidf限制 :param allow_tags: 统计指定词性的词,如果为空则表示所有词性 :return: \"\"\" corpus_data, _ = corpus.process_origin_corpus_data(corpus_data, split=False,",
"word_list, word_count_list, idf_list = word_count_and_idf(partial_corpus, idf=False) if not word_list or not word_count_list: return"
] |
[
"featureFormat( dictionary, features, remove_NaN=True, remove_all_zeroes=True, remove_any_zeroes=False, sort_keys = False): \"\"\" convert dictionary to",
"that are all zero, do that here if remove_all_zeroes: append = False for",
"a numpy array like the one returned from featureFormat, separate out the first",
"into its own list (this should be the quantity you want to predict)",
"not to add the data point. append = True # exclude 'poi' class",
"remove_all_zeroes: append = False for item in test_list: if item != 0 and",
"given a numpy array like the one returned from featureFormat, separate out the",
"lists (sklearn can generally handle both lists and numpy arrays as input formats",
"target = [] features = [] for item in data: target.append( item[0] )",
"any data points for which any of the features you seek are 0.0",
"return targets and features as separate lists (sklearn can generally handle both lists",
"\"\"\" return_list = [] # Key order - first branch is for Python",
"else: test_list = tmp_list ### if all features are zero and you want",
"test_list or \"NaN\" in test_list: append = False ### Append the data point",
"values. \"\"\" return_list = [] # Key order - first branch is for",
"be left as False for the course mini-projects). NOTE: first feature is assumed",
"test_list = tmp_list[1:] else: test_list = tmp_list ### if all features are zero",
"Append the data point if flagged for addition. if append: return_list.append( np.array(tmp_list) )",
"it into its own list (this should be the quantity you want to",
"True # exclude 'poi' class as criteria. if features[0] == 'poi': test_list =",
"try: dictionary[key][feature] except KeyError: print \"error: key \", feature, \" not present\" return",
"of the features you seek are 0.0 sort_keys = True sorts keys by",
"flagged for addition. if append: return_list.append( np.array(tmp_list) ) return np.array(return_list) def targetFeatureSplit( data",
"and sort_keys should be left as False for the course mini-projects). NOTE: first",
") # Logic for deciding whether or not to add the data point.",
"its own list (this should be the quantity you want to predict) return",
"data points for which all the features you seek are 0.0 remove_any_zeroes =",
"sort_keys: keys = sorted(dictionary.keys()) else: keys = dictionary.keys() for key in keys: tmp_list",
"= False ### Append the data point if flagged for addition. if append:",
"np.array(return_list) def targetFeatureSplit( data ): \"\"\" given a numpy array like the one",
"Key order - first branch is for Python 3 compatibility on mini-projects, #",
"all zero, do that here if remove_all_zeroes: append = False for item in",
"any zeroes, ### handle that here if remove_any_zeroes: if 0 in test_list or",
"elif sort_keys: keys = sorted(dictionary.keys()) else: keys = dictionary.keys() for key in keys:",
"for key in keys: tmp_list = [] for feature in features: try: dictionary[key][feature]",
"zero ### and you want to remove data points with any zeroes, ###",
"to be 'poi' and is not checked for removal for zero or missing",
"Python 3 compatibility on mini-projects, # second branch is for compatibility on final",
"sorted(dictionary.keys()) else: keys = dictionary.keys() for key in keys: tmp_list = [] for",
"deciding whether or not to add the data point. append = True #",
"import numpy as np def featureFormat( dictionary, features, remove_NaN=True, remove_all_zeroes=True, remove_any_zeroes=False, sort_keys =",
"(this should be the quantity you want to predict) return targets and features",
"break ### if any features for a given data point are zero ###",
"and you want to remove data points with any zeroes, ### handle that",
"keys by alphabetical order. Setting the value as a string opens the corresponding",
"= [] for item in data: target.append( item[0] ) features.append( item[1:] ) return",
"[] for item in data: target.append( item[0] ) features.append( item[1:] ) return target,",
"key \", feature, \" not present\" return value = dictionary[key][feature] if value==\"NaN\" and",
"you want to remove ### data points that are all zero, do that",
"want to remove data points with any zeroes, ### handle that here if",
"### Append the data point if flagged for addition. if append: return_list.append( np.array(tmp_list)",
"you seek are 0.0 remove_any_zeroes = True will omit any data points for",
"as np def featureFormat( dictionary, features, remove_NaN=True, remove_all_zeroes=True, remove_any_zeroes=False, sort_keys = False): \"\"\"",
"as a string opens the corresponding pickle file with a preset key order",
"quantity you want to predict) return targets and features as separate lists (sklearn",
"- first branch is for Python 3 compatibility on mini-projects, # second branch",
"corresponding pickle file with a preset key order (this is used for Python",
"and numpy arrays as input formats when training/predicting) \"\"\" target = [] features",
"exclude 'poi' class as criteria. if features[0] == 'poi': test_list = tmp_list[1:] else:",
"used for Python 3 compatibility, and sort_keys should be left as False for",
"convert dictionary to numpy array of features remove_NaN = True will convert \"NaN\"",
"dictionary.keys() for key in keys: tmp_list = [] for feature in features: try:",
"dictionary[key][feature] if value==\"NaN\" and remove_NaN: value = 0 tmp_list.append( float(value) ) # Logic",
"data points that are all zero, do that here if remove_all_zeroes: append =",
"if item != 0 and item != \"NaN\": append = True break ###",
"Udacity \"\"\" import numpy as np def featureFormat( dictionary, features, remove_NaN=True, remove_all_zeroes=True, remove_any_zeroes=False,",
"if isinstance(sort_keys, str): import pickle keys = pickle.load(open(sort_keys, \"rb\")) elif sort_keys: keys =",
"sort_keys = True sorts keys by alphabetical order. Setting the value as a",
"will omit any data points for which any of the features you seek",
"add the data point. append = True # exclude 'poi' class as criteria.",
"assumed to be 'poi' and is not checked for removal for zero or",
"preset key order (this is used for Python 3 compatibility, and sort_keys should",
"feature is assumed to be 'poi' and is not checked for removal for",
"any features for a given data point are zero ### and you want",
"points for which any of the features you seek are 0.0 sort_keys =",
"and item != \"NaN\": append = True break ### if any features for",
"order (this is used for Python 3 compatibility, and sort_keys should be left",
"pickle keys = pickle.load(open(sort_keys, \"rb\")) elif sort_keys: keys = sorted(dictionary.keys()) else: keys =",
"any data points for which all the features you seek are 0.0 remove_any_zeroes",
"points with any zeroes, ### handle that here if remove_any_zeroes: if 0 in",
"print \"error: key \", feature, \" not present\" return value = dictionary[key][feature] if",
"and is not checked for removal for zero or missing values. \"\"\" return_list",
"= False for item in test_list: if item != 0 and item !=",
"the one returned from featureFormat, separate out the first feature and put it",
"the first feature and put it into its own list (this should be",
"\"NaN\": append = True break ### if any features for a given data",
"zeroes, ### handle that here if remove_any_zeroes: if 0 in test_list or \"NaN\"",
"\"\"\" target = [] features = [] for item in data: target.append( item[0]",
"is not checked for removal for zero or missing values. \"\"\" return_list =",
"branch is for compatibility on final project. if isinstance(sort_keys, str): import pickle keys",
"0.0 remove_all_zeroes = True will omit any data points for which all the",
"mini-projects). NOTE: first feature is assumed to be 'poi' and is not checked",
"\"NaN\" in test_list: append = False ### Append the data point if flagged",
"remove_all_zeroes = True will omit any data points for which all the features",
"for feature in features: try: dictionary[key][feature] except KeyError: print \"error: key \", feature,",
"numpy array of features remove_NaN = True will convert \"NaN\" string to 0.0",
"test_list = tmp_list ### if all features are zero and you want to",
"feature, \" not present\" return value = dictionary[key][feature] if value==\"NaN\" and remove_NaN: value",
"string to 0.0 remove_all_zeroes = True will omit any data points for which",
"you want to predict) return targets and features as separate lists (sklearn can",
"order. Setting the value as a string opens the corresponding pickle file with",
"you seek are 0.0 sort_keys = True sorts keys by alphabetical order. Setting",
"the features you seek are 0.0 sort_keys = True sorts keys by alphabetical",
"\"NaN\" string to 0.0 remove_all_zeroes = True will omit any data points for",
"compatibility, and sort_keys should be left as False for the course mini-projects). NOTE:",
"in test_list: append = False ### Append the data point if flagged for",
"remove_NaN: value = 0 tmp_list.append( float(value) ) # Logic for deciding whether or",
"\" not present\" return value = dictionary[key][feature] if value==\"NaN\" and remove_NaN: value =",
"# second branch is for compatibility on final project. if isinstance(sort_keys, str): import",
"alphabetical order. Setting the value as a string opens the corresponding pickle file",
"if any features for a given data point are zero ### and you",
"a string opens the corresponding pickle file with a preset key order (this",
"append = True break ### if any features for a given data point",
"# Logic for deciding whether or not to add the data point. append",
"return_list.append( np.array(tmp_list) ) return np.array(return_list) def targetFeatureSplit( data ): \"\"\" given a numpy",
"lists and numpy arrays as input formats when training/predicting) \"\"\" target = []",
"final project. if isinstance(sort_keys, str): import pickle keys = pickle.load(open(sort_keys, \"rb\")) elif sort_keys:",
"for deciding whether or not to add the data point. append = True",
"False for the course mini-projects). NOTE: first feature is assumed to be 'poi'",
"remove_any_zeroes=False, sort_keys = False): \"\"\" convert dictionary to numpy array of features remove_NaN",
"for Python 3 compatibility on mini-projects, # second branch is for compatibility on",
"keys = dictionary.keys() for key in keys: tmp_list = [] for feature in",
"data point. append = True # exclude 'poi' class as criteria. if features[0]",
"should be the quantity you want to predict) return targets and features as",
"### and you want to remove data points with any zeroes, ### handle",
"removal for zero or missing values. \"\"\" return_list = [] # Key order",
"formats when training/predicting) \"\"\" target = [] features = [] for item in",
"training/predicting) \"\"\" target = [] features = [] for item in data: target.append(",
"True will convert \"NaN\" string to 0.0 remove_all_zeroes = True will omit any",
"features for a given data point are zero ### and you want to",
"you want to remove data points with any zeroes, ### handle that here",
"convert \"NaN\" string to 0.0 remove_all_zeroes = True will omit any data points",
"both lists and numpy arrays as input formats when training/predicting) \"\"\" target =",
"the quantity you want to predict) return targets and features as separate lists",
"generally handle both lists and numpy arrays as input formats when training/predicting) \"\"\"",
"pickle file with a preset key order (this is used for Python 3",
"remove_any_zeroes = True will omit any data points for which any of the",
"of features remove_NaN = True will convert \"NaN\" string to 0.0 remove_all_zeroes =",
"True sorts keys by alphabetical order. Setting the value as a string opens",
"checked for removal for zero or missing values. \"\"\" return_list = [] #",
"missing values. \"\"\" return_list = [] # Key order - first branch is",
"do that here if remove_all_zeroes: append = False for item in test_list: if",
"branch is for Python 3 compatibility on mini-projects, # second branch is for",
"False): \"\"\" convert dictionary to numpy array of features remove_NaN = True will",
"# exclude 'poi' class as criteria. if features[0] == 'poi': test_list = tmp_list[1:]",
"item in test_list: if item != 0 and item != \"NaN\": append =",
"KeyError: print \"error: key \", feature, \" not present\" return value = dictionary[key][feature]",
"are zero ### and you want to remove data points with any zeroes,",
"= [] # Key order - first branch is for Python 3 compatibility",
"omit any data points for which all the features you seek are 0.0",
"here if remove_any_zeroes: if 0 in test_list or \"NaN\" in test_list: append =",
"points for which all the features you seek are 0.0 remove_any_zeroes = True",
"numpy arrays as input formats when training/predicting) \"\"\" target = [] features =",
"any of the features you seek are 0.0 sort_keys = True sorts keys",
"if remove_all_zeroes: append = False for item in test_list: if item != 0",
"and features as separate lists (sklearn can generally handle both lists and numpy",
"array of features remove_NaN = True will convert \"NaN\" string to 0.0 remove_all_zeroes",
"== 'poi': test_list = tmp_list[1:] else: test_list = tmp_list ### if all features",
"to predict) return targets and features as separate lists (sklearn can generally handle",
"will omit any data points for which all the features you seek are",
"first feature and put it into its own list (this should be the",
"data point if flagged for addition. if append: return_list.append( np.array(tmp_list) ) return np.array(return_list)",
"project. if isinstance(sort_keys, str): import pickle keys = pickle.load(open(sort_keys, \"rb\")) elif sort_keys: keys",
"for compatibility on final project. if isinstance(sort_keys, str): import pickle keys = pickle.load(open(sort_keys,",
"= 0 tmp_list.append( float(value) ) # Logic for deciding whether or not to",
"in keys: tmp_list = [] for feature in features: try: dictionary[key][feature] except KeyError:",
"tmp_list.append( float(value) ) # Logic for deciding whether or not to add the",
"False for item in test_list: if item != 0 and item != \"NaN\":",
"for addition. if append: return_list.append( np.array(tmp_list) ) return np.array(return_list) def targetFeatureSplit( data ):",
"list (this should be the quantity you want to predict) return targets and",
"arrays as input formats when training/predicting) \"\"\" target = [] features = []",
"import pickle keys = pickle.load(open(sort_keys, \"rb\")) elif sort_keys: keys = sorted(dictionary.keys()) else: keys",
"and you want to remove ### data points that are all zero, do",
"dictionary to numpy array of features remove_NaN = True will convert \"NaN\" string",
"own list (this should be the quantity you want to predict) return targets",
"for item in data: target.append( item[0] ) features.append( item[1:] ) return target, features",
"0.0 sort_keys = True sorts keys by alphabetical order. Setting the value as",
"given data point are zero ### and you want to remove data points",
"value = dictionary[key][feature] if value==\"NaN\" and remove_NaN: value = 0 tmp_list.append( float(value) )",
"compatibility on final project. if isinstance(sort_keys, str): import pickle keys = pickle.load(open(sort_keys, \"rb\"))",
"that here if remove_any_zeroes: if 0 in test_list or \"NaN\" in test_list: append",
"all the features you seek are 0.0 remove_any_zeroes = True will omit any",
"): \"\"\" given a numpy array like the one returned from featureFormat, separate",
"be the quantity you want to predict) return targets and features as separate",
"like the one returned from featureFormat, separate out the first feature and put",
"Setting the value as a string opens the corresponding pickle file with a",
"when training/predicting) \"\"\" target = [] features = [] for item in data:",
"tmp_list ### if all features are zero and you want to remove ###",
"and put it into its own list (this should be the quantity you",
"feature and put it into its own list (this should be the quantity",
"compatibility on mini-projects, # second branch is for compatibility on final project. if",
"\"\"\" given a numpy array like the one returned from featureFormat, separate out",
"[] features = [] for item in data: target.append( item[0] ) features.append( item[1:]",
"except KeyError: print \"error: key \", feature, \" not present\" return value =",
"class as criteria. if features[0] == 'poi': test_list = tmp_list[1:] else: test_list =",
"def featureFormat( dictionary, features, remove_NaN=True, remove_all_zeroes=True, remove_any_zeroes=False, sort_keys = False): \"\"\" convert dictionary",
"is for compatibility on final project. if isinstance(sort_keys, str): import pickle keys =",
"features remove_NaN = True will convert \"NaN\" string to 0.0 remove_all_zeroes = True",
"test_list: append = False ### Append the data point if flagged for addition.",
"False ### Append the data point if flagged for addition. if append: return_list.append(",
"= dictionary[key][feature] if value==\"NaN\" and remove_NaN: value = 0 tmp_list.append( float(value) ) #",
"if 0 in test_list or \"NaN\" in test_list: append = False ### Append",
"by Udacity \"\"\" import numpy as np def featureFormat( dictionary, features, remove_NaN=True, remove_all_zeroes=True,",
"dictionary, features, remove_NaN=True, remove_all_zeroes=True, remove_any_zeroes=False, sort_keys = False): \"\"\" convert dictionary to numpy",
"sorts keys by alphabetical order. Setting the value as a string opens the",
"the corresponding pickle file with a preset key order (this is used for",
"= True will omit any data points for which any of the features",
"if features[0] == 'poi': test_list = tmp_list[1:] else: test_list = tmp_list ### if",
"from featureFormat, separate out the first feature and put it into its own",
"is for Python 3 compatibility on mini-projects, # second branch is for compatibility",
"!= \"NaN\": append = True break ### if any features for a given",
"point if flagged for addition. if append: return_list.append( np.array(tmp_list) ) return np.array(return_list) def",
"to add the data point. append = True # exclude 'poi' class as",
"which all the features you seek are 0.0 remove_any_zeroes = True will omit",
"append: return_list.append( np.array(tmp_list) ) return np.array(return_list) def targetFeatureSplit( data ): \"\"\" given a",
"key order (this is used for Python 3 compatibility, and sort_keys should be",
"= dictionary.keys() for key in keys: tmp_list = [] for feature in features:",
"as input formats when training/predicting) \"\"\" target = [] features = [] for",
"the data point if flagged for addition. if append: return_list.append( np.array(tmp_list) ) return",
"returned from featureFormat, separate out the first feature and put it into its",
"is used for Python 3 compatibility, and sort_keys should be left as False",
"be 'poi' and is not checked for removal for zero or missing values.",
"True break ### if any features for a given data point are zero",
"whether or not to add the data point. append = True # exclude",
"[] # Key order - first branch is for Python 3 compatibility on",
"value==\"NaN\" and remove_NaN: value = 0 tmp_list.append( float(value) ) # Logic for deciding",
"remove_all_zeroes=True, remove_any_zeroes=False, sort_keys = False): \"\"\" convert dictionary to numpy array of features",
"value as a string opens the corresponding pickle file with a preset key",
"True will omit any data points for which all the features you seek",
"will convert \"NaN\" string to 0.0 remove_all_zeroes = True will omit any data",
"= True sorts keys by alphabetical order. Setting the value as a string",
"if append: return_list.append( np.array(tmp_list) ) return np.array(return_list) def targetFeatureSplit( data ): \"\"\" given",
"value = 0 tmp_list.append( float(value) ) # Logic for deciding whether or not",
"### if all features are zero and you want to remove ### data",
"handle that here if remove_any_zeroes: if 0 in test_list or \"NaN\" in test_list:",
"'poi' class as criteria. if features[0] == 'poi': test_list = tmp_list[1:] else: test_list",
"seek are 0.0 remove_any_zeroes = True will omit any data points for which",
"features: try: dictionary[key][feature] except KeyError: print \"error: key \", feature, \" not present\"",
"with a preset key order (this is used for Python 3 compatibility, and",
"are all zero, do that here if remove_all_zeroes: append = False for item",
"to remove data points with any zeroes, ### handle that here if remove_any_zeroes:",
"or not to add the data point. append = True # exclude 'poi'",
"= [] features = [] for item in data: target.append( item[0] ) features.append(",
"data ): \"\"\" given a numpy array like the one returned from featureFormat,",
"and remove_NaN: value = 0 tmp_list.append( float(value) ) # Logic for deciding whether",
"0 tmp_list.append( float(value) ) # Logic for deciding whether or not to add",
"key in keys: tmp_list = [] for feature in features: try: dictionary[key][feature] except",
"# Key order - first branch is for Python 3 compatibility on mini-projects,",
"### if any features for a given data point are zero ### and",
"provided by Udacity \"\"\" import numpy as np def featureFormat( dictionary, features, remove_NaN=True,",
"second branch is for compatibility on final project. if isinstance(sort_keys, str): import pickle",
"which any of the features you seek are 0.0 sort_keys = True sorts",
"keys = pickle.load(open(sort_keys, \"rb\")) elif sort_keys: keys = sorted(dictionary.keys()) else: keys = dictionary.keys()",
"remove data points with any zeroes, ### handle that here if remove_any_zeroes: if",
"remove_NaN=True, remove_all_zeroes=True, remove_any_zeroes=False, sort_keys = False): \"\"\" convert dictionary to numpy array of",
"to numpy array of features remove_NaN = True will convert \"NaN\" string to",
"criteria. if features[0] == 'poi': test_list = tmp_list[1:] else: test_list = tmp_list ###",
"by alphabetical order. Setting the value as a string opens the corresponding pickle",
"want to predict) return targets and features as separate lists (sklearn can generally",
"\"\"\" convert dictionary to numpy array of features remove_NaN = True will convert",
"remove_any_zeroes: if 0 in test_list or \"NaN\" in test_list: append = False ###",
"or missing values. \"\"\" return_list = [] # Key order - first branch",
"for removal for zero or missing values. \"\"\" return_list = [] # Key",
"### data points that are all zero, do that here if remove_all_zeroes: append",
"are zero and you want to remove ### data points that are all",
"can generally handle both lists and numpy arrays as input formats when training/predicting)",
"all features are zero and you want to remove ### data points that",
"addition. if append: return_list.append( np.array(tmp_list) ) return np.array(return_list) def targetFeatureSplit( data ): \"\"\"",
"Code provided by Udacity \"\"\" import numpy as np def featureFormat( dictionary, features,",
"if value==\"NaN\" and remove_NaN: value = 0 tmp_list.append( float(value) ) # Logic for",
"item != \"NaN\": append = True break ### if any features for a",
"NOTE: first feature is assumed to be 'poi' and is not checked for",
"in features: try: dictionary[key][feature] except KeyError: print \"error: key \", feature, \" not",
"\"\"\" Code provided by Udacity \"\"\" import numpy as np def featureFormat( dictionary,",
"with any zeroes, ### handle that here if remove_any_zeroes: if 0 in test_list",
"the course mini-projects). NOTE: first feature is assumed to be 'poi' and is",
"predict) return targets and features as separate lists (sklearn can generally handle both",
"first branch is for Python 3 compatibility on mini-projects, # second branch is",
"one returned from featureFormat, separate out the first feature and put it into",
"the data point. append = True # exclude 'poi' class as criteria. if",
"features you seek are 0.0 remove_any_zeroes = True will omit any data points",
"remove_NaN = True will convert \"NaN\" string to 0.0 remove_all_zeroes = True will",
"for Python 3 compatibility, and sort_keys should be left as False for the",
"for a given data point are zero ### and you want to remove",
"opens the corresponding pickle file with a preset key order (this is used",
"want to remove ### data points that are all zero, do that here",
"return value = dictionary[key][feature] if value==\"NaN\" and remove_NaN: value = 0 tmp_list.append( float(value)",
"here if remove_all_zeroes: append = False for item in test_list: if item !=",
"dictionary[key][feature] except KeyError: print \"error: key \", feature, \" not present\" return value",
"[] for feature in features: try: dictionary[key][feature] except KeyError: print \"error: key \",",
"omit any data points for which any of the features you seek are",
"\", feature, \" not present\" return value = dictionary[key][feature] if value==\"NaN\" and remove_NaN:",
"append = True # exclude 'poi' class as criteria. if features[0] == 'poi':",
"for the course mini-projects). NOTE: first feature is assumed to be 'poi' and",
"= True # exclude 'poi' class as criteria. if features[0] == 'poi': test_list",
"isinstance(sort_keys, str): import pickle keys = pickle.load(open(sort_keys, \"rb\")) elif sort_keys: keys = sorted(dictionary.keys())",
"featureFormat, separate out the first feature and put it into its own list",
"np def featureFormat( dictionary, features, remove_NaN=True, remove_all_zeroes=True, remove_any_zeroes=False, sort_keys = False): \"\"\" convert",
"Logic for deciding whether or not to add the data point. append =",
"if remove_any_zeroes: if 0 in test_list or \"NaN\" in test_list: append = False",
"seek are 0.0 sort_keys = True sorts keys by alphabetical order. Setting the",
"mini-projects, # second branch is for compatibility on final project. if isinstance(sort_keys, str):",
"'poi': test_list = tmp_list[1:] else: test_list = tmp_list ### if all features are",
"(this is used for Python 3 compatibility, and sort_keys should be left as",
"targets and features as separate lists (sklearn can generally handle both lists and",
"= pickle.load(open(sort_keys, \"rb\")) elif sort_keys: keys = sorted(dictionary.keys()) else: keys = dictionary.keys() for",
"features = [] for item in data: target.append( item[0] ) features.append( item[1:] )",
"3 compatibility, and sort_keys should be left as False for the course mini-projects).",
"0 and item != \"NaN\": append = True break ### if any features",
"Python 3 compatibility, and sort_keys should be left as False for the course",
"True will omit any data points for which any of the features you",
"remove ### data points that are all zero, do that here if remove_all_zeroes:",
"that here if remove_all_zeroes: append = False for item in test_list: if item",
"for which all the features you seek are 0.0 remove_any_zeroes = True will",
"return_list = [] # Key order - first branch is for Python 3",
"if all features are zero and you want to remove ### data points",
"test_list: if item != 0 and item != \"NaN\": append = True break",
"features as separate lists (sklearn can generally handle both lists and numpy arrays",
"= tmp_list[1:] else: test_list = tmp_list ### if all features are zero and",
"string opens the corresponding pickle file with a preset key order (this is",
"else: keys = dictionary.keys() for key in keys: tmp_list = [] for feature",
"keys = sorted(dictionary.keys()) else: keys = dictionary.keys() for key in keys: tmp_list =",
"zero and you want to remove ### data points that are all zero,",
"numpy array like the one returned from featureFormat, separate out the first feature",
"not checked for removal for zero or missing values. \"\"\" return_list = []",
"= True break ### if any features for a given data point are",
"if flagged for addition. if append: return_list.append( np.array(tmp_list) ) return np.array(return_list) def targetFeatureSplit(",
"input formats when training/predicting) \"\"\" target = [] features = [] for item",
"= sorted(dictionary.keys()) else: keys = dictionary.keys() for key in keys: tmp_list = []",
"keys: tmp_list = [] for feature in features: try: dictionary[key][feature] except KeyError: print",
"\"\"\" import numpy as np def featureFormat( dictionary, features, remove_NaN=True, remove_all_zeroes=True, remove_any_zeroes=False, sort_keys",
"put it into its own list (this should be the quantity you want",
"on mini-projects, # second branch is for compatibility on final project. if isinstance(sort_keys,",
"= tmp_list ### if all features are zero and you want to remove",
"(sklearn can generally handle both lists and numpy arrays as input formats when",
"array like the one returned from featureFormat, separate out the first feature and",
"are 0.0 sort_keys = True sorts keys by alphabetical order. Setting the value",
"separate out the first feature and put it into its own list (this",
"targetFeatureSplit( data ): \"\"\" given a numpy array like the one returned from",
"for which any of the features you seek are 0.0 sort_keys = True",
"append = False for item in test_list: if item != 0 and item",
"the features you seek are 0.0 remove_any_zeroes = True will omit any data",
"for item in test_list: if item != 0 and item != \"NaN\": append",
"as separate lists (sklearn can generally handle both lists and numpy arrays as",
"first feature is assumed to be 'poi' and is not checked for removal",
"np.array(tmp_list) ) return np.array(return_list) def targetFeatureSplit( data ): \"\"\" given a numpy array",
"tmp_list[1:] else: test_list = tmp_list ### if all features are zero and you",
"numpy as np def featureFormat( dictionary, features, remove_NaN=True, remove_all_zeroes=True, remove_any_zeroes=False, sort_keys = False):",
"data points with any zeroes, ### handle that here if remove_any_zeroes: if 0",
"\"error: key \", feature, \" not present\" return value = dictionary[key][feature] if value==\"NaN\"",
"course mini-projects). NOTE: first feature is assumed to be 'poi' and is not",
"### handle that here if remove_any_zeroes: if 0 in test_list or \"NaN\" in",
"should be left as False for the course mini-projects). NOTE: first feature is",
"is assumed to be 'poi' and is not checked for removal for zero",
"str): import pickle keys = pickle.load(open(sort_keys, \"rb\")) elif sort_keys: keys = sorted(dictionary.keys()) else:",
"as criteria. if features[0] == 'poi': test_list = tmp_list[1:] else: test_list = tmp_list",
"data point are zero ### and you want to remove data points with",
"data points for which any of the features you seek are 0.0 sort_keys",
"= True will convert \"NaN\" string to 0.0 remove_all_zeroes = True will omit",
"zero, do that here if remove_all_zeroes: append = False for item in test_list:",
"item != 0 and item != \"NaN\": append = True break ### if",
"are 0.0 remove_any_zeroes = True will omit any data points for which any",
"in test_list or \"NaN\" in test_list: append = False ### Append the data",
"as False for the course mini-projects). NOTE: first feature is assumed to be",
"return np.array(return_list) def targetFeatureSplit( data ): \"\"\" given a numpy array like the",
"file with a preset key order (this is used for Python 3 compatibility,",
"'poi' and is not checked for removal for zero or missing values. \"\"\"",
"0 in test_list or \"NaN\" in test_list: append = False ### Append the",
"append = False ### Append the data point if flagged for addition. if",
"= True will omit any data points for which all the features you",
"not present\" return value = dictionary[key][feature] if value==\"NaN\" and remove_NaN: value = 0",
"= False): \"\"\" convert dictionary to numpy array of features remove_NaN = True",
"sort_keys should be left as False for the course mini-projects). NOTE: first feature",
"\"rb\")) elif sort_keys: keys = sorted(dictionary.keys()) else: keys = dictionary.keys() for key in",
"points that are all zero, do that here if remove_all_zeroes: append = False",
"def targetFeatureSplit( data ): \"\"\" given a numpy array like the one returned",
"0.0 remove_any_zeroes = True will omit any data points for which any of",
"handle both lists and numpy arrays as input formats when training/predicting) \"\"\" target",
"zero or missing values. \"\"\" return_list = [] # Key order - first",
"feature in features: try: dictionary[key][feature] except KeyError: print \"error: key \", feature, \"",
"to 0.0 remove_all_zeroes = True will omit any data points for which all",
"features, remove_NaN=True, remove_all_zeroes=True, remove_any_zeroes=False, sort_keys = False): \"\"\" convert dictionary to numpy array",
"features you seek are 0.0 sort_keys = True sorts keys by alphabetical order.",
"a given data point are zero ### and you want to remove data",
"features are zero and you want to remove ### data points that are",
"= [] for feature in features: try: dictionary[key][feature] except KeyError: print \"error: key",
"out the first feature and put it into its own list (this should",
"order - first branch is for Python 3 compatibility on mini-projects, # second",
"left as False for the course mini-projects). NOTE: first feature is assumed to",
"features[0] == 'poi': test_list = tmp_list[1:] else: test_list = tmp_list ### if all",
"for zero or missing values. \"\"\" return_list = [] # Key order -",
"float(value) ) # Logic for deciding whether or not to add the data",
") return np.array(return_list) def targetFeatureSplit( data ): \"\"\" given a numpy array like",
"to remove ### data points that are all zero, do that here if",
"in test_list: if item != 0 and item != \"NaN\": append = True",
"pickle.load(open(sort_keys, \"rb\")) elif sort_keys: keys = sorted(dictionary.keys()) else: keys = dictionary.keys() for key",
"on final project. if isinstance(sort_keys, str): import pickle keys = pickle.load(open(sort_keys, \"rb\")) elif",
"tmp_list = [] for feature in features: try: dictionary[key][feature] except KeyError: print \"error:",
"the value as a string opens the corresponding pickle file with a preset",
"or \"NaN\" in test_list: append = False ### Append the data point if",
"point are zero ### and you want to remove data points with any",
"3 compatibility on mini-projects, # second branch is for compatibility on final project.",
"!= 0 and item != \"NaN\": append = True break ### if any",
"present\" return value = dictionary[key][feature] if value==\"NaN\" and remove_NaN: value = 0 tmp_list.append(",
"separate lists (sklearn can generally handle both lists and numpy arrays as input",
"sort_keys = False): \"\"\" convert dictionary to numpy array of features remove_NaN =",
"a preset key order (this is used for Python 3 compatibility, and sort_keys",
"point. append = True # exclude 'poi' class as criteria. if features[0] =="
] |
[
"\"\" @staticmethod def getMapTiles(mid=0, zoom=17 or db.app.config.get('DEFAULTZOOM')): from emonitor.modules.maps.map import Map _map =",
"/ n)))) return lat_deg, lon_deg def getCarTypeNames(self): return self.value @staticmethod def getCarTypes(): ctypes",
"'/')) except: pass return tiles @staticmethod def getFrontendSettings(area=\"\"): s = Settings.query.filter_by(name='frontend.default') if s.count()",
"for option :param option: name as string :param val: value of option :return:",
"\"\"\" s = Settings.query.filter_by(name=option) if s.count() == 1: # update return s.first().value return",
"def __init__(self, name, value=\"\"): self.name = name self._value = value @property def value(self):",
"of option \"\"\" s = Settings.query.filter_by(name=option) if s.count() == 1: # update return",
"pass return tiles @staticmethod def getFrontendSettings(area=\"\"): s = Settings.query.filter_by(name='frontend.default') if s.count() == 1:",
":param xtile: x-coordinate of tile :param ytile: y-coordinate of tile :param zoom: zoom",
"for ts in [f for f in os.listdir(_map.path + str(zoom) + '/') if",
"- 2 * ytile / n)))) return lat_deg, lon_deg def getCarTypeNames(self): return self.value",
"s = Settings(option, yaml.safe_dump(val, encoding='utf-8')) db.session.add(s) db.session.commit() return s @staticmethod def getIntList(option, default=[]):",
"[] try: for ts in [f for f in os.listdir(_map.path + str(zoom) +",
"if s.count() == 1: if area == \"\": return s.first().value elif area in",
"os, math, yaml from emonitor.extensions import db class Struct(dict): def __init__(self, **entries): self.__dict__.update(entries)",
"get_byType(type): return Settings.query.filter_by(name=type).first() or \"\" @staticmethod def getMapTiles(mid=0, zoom=17 or db.app.config.get('DEFAULTZOOM')): from emonitor.modules.maps.map",
"n = 2.0 ** zoom lon_deg = xtile / n * 360.0 -",
"\"\"\" Setter for option :param option: name as string :param val: value of",
"= db.Column(db.Integer, primary_key=True) name = db.Column(db.String(64)) _value = db.Column('value', db.Text) def __init__(self, name,",
"- 180.0 lat_deg = math.degrees(math.atan(math.sinh(math.pi * (1 - 2 * ytile / n))))",
"_map = Map.getMaps(mid) tiles = [] try: for ts in [f for f",
"elif area in s.first().value.keys(): return s.first().value[area] return {'module': 'default', 'width': '.2', 'visible': '0',",
"= yaml.safe_dump(val, encoding='utf-8') @staticmethod def num2deg(xtile, ytile, zoom=17 or db.config.get('DEFAULTZOOM')): \"\"\" Translate tile",
"db.session.add(s) db.session.commit() return s @staticmethod def getIntList(option, default=[]): try: return map(int, Settings.get(option, '').split(','))",
"def __init__(self, **entries): self.__dict__.update(entries) class Settings(db.Model): \"\"\"Settings class\"\"\" __tablename__ = 'settings' __table_args__ =",
"except: pass return tiles @staticmethod def getFrontendSettings(area=\"\"): s = Settings.query.filter_by(name='frontend.default') if s.count() ==",
"1: if area == \"\": return s.first().value elif area in s.first().value.keys(): return s.first().value[area]",
"default # deliver default value @staticmethod def set(option, val): \"\"\" Setter for option",
"db.session.commit() return s @staticmethod def getIntList(option, default=[]): try: return map(int, Settings.get(option, '').split(',')) except",
"class Settings(db.Model): \"\"\"Settings class\"\"\" __tablename__ = 'settings' __table_args__ = {'extend_existing': True} id =",
"add value s = Settings(option, yaml.safe_dump(val, encoding='utf-8')) db.session.add(s) db.session.commit() return s @staticmethod def",
"Settings.query.filter_by(name=type).first() or \"\" @staticmethod def getMapTiles(mid=0, zoom=17 or db.app.config.get('DEFAULTZOOM')): from emonitor.modules.maps.map import Map",
"from emonitor.modules.maps.map import Map _map = Map.getMaps(mid) tiles = [] try: for ts",
"= name self._value = value @property def value(self): return yaml.load(self._value) @value.setter def value(self,",
"@staticmethod def set(option, val): \"\"\" Setter for option :param option: name as string",
"val else: # add value s = Settings(option, yaml.safe_dump(val, encoding='utf-8')) db.session.add(s) db.session.commit() return",
"zoom: zoom level :return: lat, lon tuple \"\"\" n = 2.0 ** zoom",
"or db.config.get('DEFAULTZOOM')): \"\"\" Translate tile into coordinate (lat, lon) :param xtile: x-coordinate of",
"area == \"\": return s.first().value elif area in s.first().value.keys(): return s.first().value[area] return {'module':",
"getCarTypeNames(self): return self.value @staticmethod def getCarTypes(): ctypes = Settings.query.filter_by(name='cartypes') if ctypes.count(): return ctypes.one().value",
"def get_byType(type): return Settings.query.filter_by(name=type).first() or \"\" @staticmethod def getMapTiles(mid=0, zoom=17 or db.app.config.get('DEFAULTZOOM')): from",
"'width': '.2'}} @staticmethod def get(option, default=''): \"\"\" Getter for option values :param option:",
"self.__dict__.update(entries) class Settings(db.Model): \"\"\"Settings class\"\"\" __tablename__ = 'settings' __table_args__ = {'extend_existing': True} id",
"string :param val: value of option :return: value of option \"\"\" s =",
"Settings.query.filter_by(name='frontend.default') if s.count() == 1: if area == \"\": return s.first().value elif area",
"if ctypes.count(): return ctypes.one().value return \"\" @staticmethod def get_byType(type): return Settings.query.filter_by(name=type).first() or \"\"",
"'').split(',')) except ValueError: return default @staticmethod def getYaml(option): try: return Struct(**(Settings.get(option))) except TypeError:",
"or db.app.config.get('DEFAULTZOOM')): from emonitor.modules.maps.map import Map _map = Map.getMaps(mid) tiles = [] try:",
"* (1 - 2 * ytile / n)))) return lat_deg, lon_deg def getCarTypeNames(self):",
"lat_deg = math.degrees(math.atan(math.sinh(math.pi * (1 - 2 * ytile / n)))) return lat_deg,",
"if not found in database :return: value of option \"\"\" s = Settings.query.filter_by(name=option)",
"option :param option: name as string :param val: value of option :return: value",
"level :return: lat, lon tuple \"\"\" n = 2.0 ** zoom lon_deg =",
"lat, lon tuple \"\"\" n = 2.0 ** zoom lon_deg = xtile /",
"'visible': '0', 'center': {'module': 'default'}, 'west': {'module': 'default', 'width': '.2'}, 'east': {'module': 'default',",
"ctypes.count(): return ctypes.one().value return \"\" @staticmethod def get_byType(type): return Settings.query.filter_by(name=type).first() or \"\" @staticmethod",
"if f.endswith('png')]: tiles.append(ts.replace('-', '/')) except: pass return tiles @staticmethod def getFrontendSettings(area=\"\"): s =",
"s.first().value return default # deliver default value @staticmethod def set(option, val): \"\"\" Setter",
"return \"\" @staticmethod def get_byType(type): return Settings.query.filter_by(name=type).first() or \"\" @staticmethod def getMapTiles(mid=0, zoom=17",
"Settings.query.filter_by(name='cartypes') if ctypes.count(): return ctypes.one().value return \"\" @staticmethod def get_byType(type): return Settings.query.filter_by(name=type).first() or",
"db class Struct(dict): def __init__(self, **entries): self.__dict__.update(entries) class Settings(db.Model): \"\"\"Settings class\"\"\" __tablename__ =",
"**entries): self.__dict__.update(entries) class Settings(db.Model): \"\"\"Settings class\"\"\" __tablename__ = 'settings' __table_args__ = {'extend_existing': True}",
"getFrontendSettings(area=\"\"): s = Settings.query.filter_by(name='frontend.default') if s.count() == 1: if area == \"\": return",
"string :param optional default: default value if not found in database :return: value",
"= db.Column(db.String(64)) _value = db.Column('value', db.Text) def __init__(self, name, value=\"\"): self.name = name",
"'/') if f.endswith('png')]: tiles.append(ts.replace('-', '/')) except: pass return tiles @staticmethod def getFrontendSettings(area=\"\"): s",
"optional default: default value if not found in database :return: value of option",
"1: # update return s.first().value return default # deliver default value @staticmethod def",
":param option: name as string :param val: value of option :return: value of",
"\"\": return s.first().value elif area in s.first().value.keys(): return s.first().value[area] return {'module': 'default', 'width':",
"val): self._value = yaml.safe_dump(val, encoding='utf-8') @staticmethod def num2deg(xtile, ytile, zoom=17 or db.config.get('DEFAULTZOOM')): \"\"\"",
"in database :return: value of option \"\"\" s = Settings.query.filter_by(name=option) if s.count() ==",
"** zoom lon_deg = xtile / n * 360.0 - 180.0 lat_deg =",
"getMapTiles(mid=0, zoom=17 or db.app.config.get('DEFAULTZOOM')): from emonitor.modules.maps.map import Map _map = Map.getMaps(mid) tiles =",
"= {'extend_existing': True} id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(64)) _value = db.Column('value',",
"import Map _map = Map.getMaps(mid) tiles = [] try: for ts in [f",
"# add value s = Settings(option, yaml.safe_dump(val, encoding='utf-8')) db.session.add(s) db.session.commit() return s @staticmethod",
"\"\" @staticmethod def get_byType(type): return Settings.query.filter_by(name=type).first() or \"\" @staticmethod def getMapTiles(mid=0, zoom=17 or",
"def num2deg(xtile, ytile, zoom=17 or db.config.get('DEFAULTZOOM')): \"\"\" Translate tile into coordinate (lat, lon)",
"tiles @staticmethod def getFrontendSettings(area=\"\"): s = Settings.query.filter_by(name='frontend.default') if s.count() == 1: if area",
"'east': {'module': 'default', 'width': '.2'}} @staticmethod def get(option, default=''): \"\"\" Getter for option",
"n * 360.0 - 180.0 lat_deg = math.degrees(math.atan(math.sinh(math.pi * (1 - 2 *",
"== 1: # update return s.first().value return default # deliver default value @staticmethod",
"'center': {'module': 'default'}, 'west': {'module': 'default', 'width': '.2'}, 'east': {'module': 'default', 'width': '.2'}}",
"* 360.0 - 180.0 lat_deg = math.degrees(math.atan(math.sinh(math.pi * (1 - 2 * ytile",
"default: default value if not found in database :return: value of option \"\"\"",
"@staticmethod def getCarTypes(): ctypes = Settings.query.filter_by(name='cartypes') if ctypes.count(): return ctypes.one().value return \"\" @staticmethod",
"of option \"\"\" s = Settings.query.filter_by(name=option).first() if s: # update settings s.value =",
"deliver default value @staticmethod def set(option, val): \"\"\" Setter for option :param option:",
"self._value = yaml.safe_dump(val, encoding='utf-8') @staticmethod def num2deg(xtile, ytile, zoom=17 or db.config.get('DEFAULTZOOM')): \"\"\" Translate",
"{'module': 'default'}, 'west': {'module': 'default', 'width': '.2'}, 'east': {'module': 'default', 'width': '.2'}} @staticmethod",
"lon_deg = xtile / n * 360.0 - 180.0 lat_deg = math.degrees(math.atan(math.sinh(math.pi *",
"# update return s.first().value return default # deliver default value @staticmethod def set(option,",
"s = Settings.query.filter_by(name=option) if s.count() == 1: # update return s.first().value return default",
"== 1: if area == \"\": return s.first().value elif area in s.first().value.keys(): return",
"def get(option, default=''): \"\"\" Getter for option values :param option: name as string",
"s = Settings.query.filter_by(name='frontend.default') if s.count() == 1: if area == \"\": return s.first().value",
"return ctypes.one().value return \"\" @staticmethod def get_byType(type): return Settings.query.filter_by(name=type).first() or \"\" @staticmethod def",
"'settings' __table_args__ = {'extend_existing': True} id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(64)) _value",
"ctypes.one().value return \"\" @staticmethod def get_byType(type): return Settings.query.filter_by(name=type).first() or \"\" @staticmethod def getMapTiles(mid=0,",
"s = Settings.query.filter_by(name=option).first() if s: # update settings s.value = val else: #",
"= xtile / n * 360.0 - 180.0 lat_deg = math.degrees(math.atan(math.sinh(math.pi * (1",
"s.count() == 1: # update return s.first().value return default # deliver default value",
"getCarTypes(): ctypes = Settings.query.filter_by(name='cartypes') if ctypes.count(): return ctypes.one().value return \"\" @staticmethod def get_byType(type):",
"db.app.config.get('DEFAULTZOOM')): from emonitor.modules.maps.map import Map _map = Map.getMaps(mid) tiles = [] try: for",
"'0', 'center': {'module': 'default'}, 'west': {'module': 'default', 'width': '.2'}, 'east': {'module': 'default', 'width':",
"ytile: y-coordinate of tile :param zoom: zoom level :return: lat, lon tuple \"\"\"",
"True} id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(64)) _value = db.Column('value', db.Text) def",
":return: lat, lon tuple \"\"\" n = 2.0 ** zoom lon_deg = xtile",
"Setter for option :param option: name as string :param val: value of option",
"name = db.Column(db.String(64)) _value = db.Column('value', db.Text) def __init__(self, name, value=\"\"): self.name =",
"360.0 - 180.0 lat_deg = math.degrees(math.atan(math.sinh(math.pi * (1 - 2 * ytile /",
"if area == \"\": return s.first().value elif area in s.first().value.keys(): return s.first().value[area] return",
"@staticmethod def get(option, default=''): \"\"\" Getter for option values :param option: name as",
"* ytile / n)))) return lat_deg, lon_deg def getCarTypeNames(self): return self.value @staticmethod def",
"def value(self, val): self._value = yaml.safe_dump(val, encoding='utf-8') @staticmethod def num2deg(xtile, ytile, zoom=17 or",
"zoom=17 or db.app.config.get('DEFAULTZOOM')): from emonitor.modules.maps.map import Map _map = Map.getMaps(mid) tiles = []",
"else: # add value s = Settings(option, yaml.safe_dump(val, encoding='utf-8')) db.session.add(s) db.session.commit() return s",
"180.0 lat_deg = math.degrees(math.atan(math.sinh(math.pi * (1 - 2 * ytile / n)))) return",
"# deliver default value @staticmethod def set(option, val): \"\"\" Setter for option :param",
"def getCarTypes(): ctypes = Settings.query.filter_by(name='cartypes') if ctypes.count(): return ctypes.one().value return \"\" @staticmethod def",
"option values :param option: name as string :param optional default: default value if",
"update return s.first().value return default # deliver default value @staticmethod def set(option, val):",
"os.listdir(_map.path + str(zoom) + '/') if f.endswith('png')]: tiles.append(ts.replace('-', '/')) except: pass return tiles",
"/ n * 360.0 - 180.0 lat_deg = math.degrees(math.atan(math.sinh(math.pi * (1 - 2",
"lon_deg def getCarTypeNames(self): return self.value @staticmethod def getCarTypes(): ctypes = Settings.query.filter_by(name='cartypes') if ctypes.count():",
"update settings s.value = val else: # add value s = Settings(option, yaml.safe_dump(val,",
"__table_args__ = {'extend_existing': True} id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(64)) _value =",
"as string :param optional default: default value if not found in database :return:",
"= math.degrees(math.atan(math.sinh(math.pi * (1 - 2 * ytile / n)))) return lat_deg, lon_deg",
"name, value=\"\"): self.name = name self._value = value @property def value(self): return yaml.load(self._value)",
"{'module': 'default', 'width': '.2'}} @staticmethod def get(option, default=''): \"\"\" Getter for option values",
"in [f for f in os.listdir(_map.path + str(zoom) + '/') if f.endswith('png')]: tiles.append(ts.replace('-',",
"option :return: value of option \"\"\" s = Settings.query.filter_by(name=option).first() if s: # update",
"def getCarTypeNames(self): return self.value @staticmethod def getCarTypes(): ctypes = Settings.query.filter_by(name='cartypes') if ctypes.count(): return",
"as string :param val: value of option :return: value of option \"\"\" s",
"return lat_deg, lon_deg def getCarTypeNames(self): return self.value @staticmethod def getCarTypes(): ctypes = Settings.query.filter_by(name='cartypes')",
"def set(option, val): \"\"\" Setter for option :param option: name as string :param",
"s @staticmethod def getIntList(option, default=[]): try: return map(int, Settings.get(option, '').split(',')) except ValueError: return",
"\"\"\" s = Settings.query.filter_by(name=option).first() if s: # update settings s.value = val else:",
"yaml.safe_dump(val, encoding='utf-8')) db.session.add(s) db.session.commit() return s @staticmethod def getIntList(option, default=[]): try: return map(int,",
"= db.Column('value', db.Text) def __init__(self, name, value=\"\"): self.name = name self._value = value",
"db.Text) def __init__(self, name, value=\"\"): self.name = name self._value = value @property def",
"\"\"\" n = 2.0 ** zoom lon_deg = xtile / n * 360.0",
"of option :return: value of option \"\"\" s = Settings.query.filter_by(name=option).first() if s: #",
"= Settings.query.filter_by(name=option) if s.count() == 1: # update return s.first().value return default #",
"tile into coordinate (lat, lon) :param xtile: x-coordinate of tile :param ytile: y-coordinate",
"tile :param ytile: y-coordinate of tile :param zoom: zoom level :return: lat, lon",
"ytile / n)))) return lat_deg, lon_deg def getCarTypeNames(self): return self.value @staticmethod def getCarTypes():",
"@property def value(self): return yaml.load(self._value) @value.setter def value(self, val): self._value = yaml.safe_dump(val, encoding='utf-8')",
"{'extend_existing': True} id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(64)) _value = db.Column('value', db.Text)",
"s: # update settings s.value = val else: # add value s =",
"into coordinate (lat, lon) :param xtile: x-coordinate of tile :param ytile: y-coordinate of",
"x-coordinate of tile :param ytile: y-coordinate of tile :param zoom: zoom level :return:",
"@value.setter def value(self, val): self._value = yaml.safe_dump(val, encoding='utf-8') @staticmethod def num2deg(xtile, ytile, zoom=17",
"= Settings.query.filter_by(name='cartypes') if ctypes.count(): return ctypes.one().value return \"\" @staticmethod def get_byType(type): return Settings.query.filter_by(name=type).first()",
"return {'module': 'default', 'width': '.2', 'visible': '0', 'center': {'module': 'default'}, 'west': {'module': 'default',",
"value(self): return yaml.load(self._value) @value.setter def value(self, val): self._value = yaml.safe_dump(val, encoding='utf-8') @staticmethod def",
"db.config.get('DEFAULTZOOM')): \"\"\" Translate tile into coordinate (lat, lon) :param xtile: x-coordinate of tile",
"db.Column(db.Integer, primary_key=True) name = db.Column(db.String(64)) _value = db.Column('value', db.Text) def __init__(self, name, value=\"\"):",
"= Map.getMaps(mid) tiles = [] try: for ts in [f for f in",
"option: name as string :param val: value of option :return: value of option",
"or \"\" @staticmethod def getMapTiles(mid=0, zoom=17 or db.app.config.get('DEFAULTZOOM')): from emonitor.modules.maps.map import Map _map",
"yaml from emonitor.extensions import db class Struct(dict): def __init__(self, **entries): self.__dict__.update(entries) class Settings(db.Model):",
"database :return: value of option \"\"\" s = Settings.query.filter_by(name=option) if s.count() == 1:",
"from emonitor.extensions import db class Struct(dict): def __init__(self, **entries): self.__dict__.update(entries) class Settings(db.Model): \"\"\"Settings",
"return s.first().value return default # deliver default value @staticmethod def set(option, val): \"\"\"",
"class\"\"\" __tablename__ = 'settings' __table_args__ = {'extend_existing': True} id = db.Column(db.Integer, primary_key=True) name",
"Map _map = Map.getMaps(mid) tiles = [] try: for ts in [f for",
"== \"\": return s.first().value elif area in s.first().value.keys(): return s.first().value[area] return {'module': 'default',",
"# update settings s.value = val else: # add value s = Settings(option,",
"lon tuple \"\"\" n = 2.0 ** zoom lon_deg = xtile / n",
"tiles = [] try: for ts in [f for f in os.listdir(_map.path +",
"math.degrees(math.atan(math.sinh(math.pi * (1 - 2 * ytile / n)))) return lat_deg, lon_deg def",
"s.value = val else: # add value s = Settings(option, yaml.safe_dump(val, encoding='utf-8')) db.session.add(s)",
"primary_key=True) name = db.Column(db.String(64)) _value = db.Column('value', db.Text) def __init__(self, name, value=\"\"): self.name",
"default=''): \"\"\" Getter for option values :param option: name as string :param optional",
"ts in [f for f in os.listdir(_map.path + str(zoom) + '/') if f.endswith('png')]:",
"name self._value = value @property def value(self): return yaml.load(self._value) @value.setter def value(self, val):",
"= [] try: for ts in [f for f in os.listdir(_map.path + str(zoom)",
"math, yaml from emonitor.extensions import db class Struct(dict): def __init__(self, **entries): self.__dict__.update(entries) class",
"Settings.get(option, '').split(',')) except ValueError: return default @staticmethod def getYaml(option): try: return Struct(**(Settings.get(option))) except",
"2 * ytile / n)))) return lat_deg, lon_deg def getCarTypeNames(self): return self.value @staticmethod",
"db.Column('value', db.Text) def __init__(self, name, value=\"\"): self.name = name self._value = value @property",
"Settings.query.filter_by(name=option) if s.count() == 1: # update return s.first().value return default # deliver",
"(1 - 2 * ytile / n)))) return lat_deg, lon_deg def getCarTypeNames(self): return",
"= Settings(option, yaml.safe_dump(val, encoding='utf-8')) db.session.add(s) db.session.commit() return s @staticmethod def getIntList(option, default=[]): try:",
"= 2.0 ** zoom lon_deg = xtile / n * 360.0 - 180.0",
"_value = db.Column('value', db.Text) def __init__(self, name, value=\"\"): self.name = name self._value =",
"zoom lon_deg = xtile / n * 360.0 - 180.0 lat_deg = math.degrees(math.atan(math.sinh(math.pi",
"'default', 'width': '.2'}, 'east': {'module': 'default', 'width': '.2'}} @staticmethod def get(option, default=''): \"\"\"",
"value of option :return: value of option \"\"\" s = Settings.query.filter_by(name=option).first() if s:",
"value s = Settings(option, yaml.safe_dump(val, encoding='utf-8')) db.session.add(s) db.session.commit() return s @staticmethod def getIntList(option,",
"s.first().value[area] return {'module': 'default', 'width': '.2', 'visible': '0', 'center': {'module': 'default'}, 'west': {'module':",
"2.0 ** zoom lon_deg = xtile / n * 360.0 - 180.0 lat_deg",
"self.value @staticmethod def getCarTypes(): ctypes = Settings.query.filter_by(name='cartypes') if ctypes.count(): return ctypes.one().value return \"\"",
"__init__(self, name, value=\"\"): self.name = name self._value = value @property def value(self): return",
"'.2'}, 'east': {'module': 'default', 'width': '.2'}} @staticmethod def get(option, default=''): \"\"\" Getter for",
"return Settings.query.filter_by(name=type).first() or \"\" @staticmethod def getMapTiles(mid=0, zoom=17 or db.app.config.get('DEFAULTZOOM')): from emonitor.modules.maps.map import",
"xtile: x-coordinate of tile :param ytile: y-coordinate of tile :param zoom: zoom level",
"Map.getMaps(mid) tiles = [] try: for ts in [f for f in os.listdir(_map.path",
"@staticmethod def getIntList(option, default=[]): try: return map(int, Settings.get(option, '').split(',')) except ValueError: return default",
"\"\"\"Settings class\"\"\" __tablename__ = 'settings' __table_args__ = {'extend_existing': True} id = db.Column(db.Integer, primary_key=True)",
"in s.first().value.keys(): return s.first().value[area] return {'module': 'default', 'width': '.2', 'visible': '0', 'center': {'module':",
"f in os.listdir(_map.path + str(zoom) + '/') if f.endswith('png')]: tiles.append(ts.replace('-', '/')) except: pass",
"Struct(dict): def __init__(self, **entries): self.__dict__.update(entries) class Settings(db.Model): \"\"\"Settings class\"\"\" __tablename__ = 'settings' __table_args__",
"tuple \"\"\" n = 2.0 ** zoom lon_deg = xtile / n *",
"return map(int, Settings.get(option, '').split(',')) except ValueError: return default @staticmethod def getYaml(option): try: return",
"def getFrontendSettings(area=\"\"): s = Settings.query.filter_by(name='frontend.default') if s.count() == 1: if area == \"\":",
":param ytile: y-coordinate of tile :param zoom: zoom level :return: lat, lon tuple",
"return tiles @staticmethod def getFrontendSettings(area=\"\"): s = Settings.query.filter_by(name='frontend.default') if s.count() == 1: if",
"get(option, default=''): \"\"\" Getter for option values :param option: name as string :param",
"= 'settings' __table_args__ = {'extend_existing': True} id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(64))",
"ytile, zoom=17 or db.config.get('DEFAULTZOOM')): \"\"\" Translate tile into coordinate (lat, lon) :param xtile:",
"of tile :param ytile: y-coordinate of tile :param zoom: zoom level :return: lat,",
"Settings(option, yaml.safe_dump(val, encoding='utf-8')) db.session.add(s) db.session.commit() return s @staticmethod def getIntList(option, default=[]): try: return",
"f.endswith('png')]: tiles.append(ts.replace('-', '/')) except: pass return tiles @staticmethod def getFrontendSettings(area=\"\"): s = Settings.query.filter_by(name='frontend.default')",
"return s @staticmethod def getIntList(option, default=[]): try: return map(int, Settings.get(option, '').split(',')) except ValueError:",
"Settings(db.Model): \"\"\"Settings class\"\"\" __tablename__ = 'settings' __table_args__ = {'extend_existing': True} id = db.Column(db.Integer,",
"values :param option: name as string :param optional default: default value if not",
"of tile :param zoom: zoom level :return: lat, lon tuple \"\"\" n =",
"Getter for option values :param option: name as string :param optional default: default",
":param optional default: default value if not found in database :return: value of",
"value @property def value(self): return yaml.load(self._value) @value.setter def value(self, val): self._value = yaml.safe_dump(val,",
"Translate tile into coordinate (lat, lon) :param xtile: x-coordinate of tile :param ytile:",
"emonitor.extensions import db class Struct(dict): def __init__(self, **entries): self.__dict__.update(entries) class Settings(db.Model): \"\"\"Settings class\"\"\"",
"= val else: # add value s = Settings(option, yaml.safe_dump(val, encoding='utf-8')) db.session.add(s) db.session.commit()",
"xtile / n * 360.0 - 180.0 lat_deg = math.degrees(math.atan(math.sinh(math.pi * (1 -",
"num2deg(xtile, ytile, zoom=17 or db.config.get('DEFAULTZOOM')): \"\"\" Translate tile into coordinate (lat, lon) :param",
"yaml.safe_dump(val, encoding='utf-8') @staticmethod def num2deg(xtile, ytile, zoom=17 or db.config.get('DEFAULTZOOM')): \"\"\" Translate tile into",
"return s.first().value[area] return {'module': 'default', 'width': '.2', 'visible': '0', 'center': {'module': 'default'}, 'west':",
"s.first().value elif area in s.first().value.keys(): return s.first().value[area] return {'module': 'default', 'width': '.2', 'visible':",
"y-coordinate of tile :param zoom: zoom level :return: lat, lon tuple \"\"\" n",
"'.2', 'visible': '0', 'center': {'module': 'default'}, 'west': {'module': 'default', 'width': '.2'}, 'east': {'module':",
"option: name as string :param optional default: default value if not found in",
"'default'}, 'west': {'module': 'default', 'width': '.2'}, 'east': {'module': 'default', 'width': '.2'}} @staticmethod def",
"default=[]): try: return map(int, Settings.get(option, '').split(',')) except ValueError: return default @staticmethod def getYaml(option):",
"def getMapTiles(mid=0, zoom=17 or db.app.config.get('DEFAULTZOOM')): from emonitor.modules.maps.map import Map _map = Map.getMaps(mid) tiles",
"zoom=17 or db.config.get('DEFAULTZOOM')): \"\"\" Translate tile into coordinate (lat, lon) :param xtile: x-coordinate",
"self.name = name self._value = value @property def value(self): return yaml.load(self._value) @value.setter def",
"value of option \"\"\" s = Settings.query.filter_by(name=option).first() if s: # update settings s.value",
":return: value of option \"\"\" s = Settings.query.filter_by(name=option).first() if s: # update settings",
"\"\"\" Translate tile into coordinate (lat, lon) :param xtile: x-coordinate of tile :param",
"name as string :param optional default: default value if not found in database",
"tile :param zoom: zoom level :return: lat, lon tuple \"\"\" n = 2.0",
"coordinate (lat, lon) :param xtile: x-coordinate of tile :param ytile: y-coordinate of tile",
"zoom level :return: lat, lon tuple \"\"\" n = 2.0 ** zoom lon_deg",
"try: return map(int, Settings.get(option, '').split(',')) except ValueError: return default @staticmethod def getYaml(option): try:",
"{'module': 'default', 'width': '.2'}, 'east': {'module': 'default', 'width': '.2'}} @staticmethod def get(option, default=''):",
"self._value = value @property def value(self): return yaml.load(self._value) @value.setter def value(self, val): self._value",
"yaml.load(self._value) @value.setter def value(self, val): self._value = yaml.safe_dump(val, encoding='utf-8') @staticmethod def num2deg(xtile, ytile,",
"tiles.append(ts.replace('-', '/')) except: pass return tiles @staticmethod def getFrontendSettings(area=\"\"): s = Settings.query.filter_by(name='frontend.default') if",
"getIntList(option, default=[]): try: return map(int, Settings.get(option, '').split(',')) except ValueError: return default @staticmethod def",
"set(option, val): \"\"\" Setter for option :param option: name as string :param val:",
"id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(64)) _value = db.Column('value', db.Text) def __init__(self,",
"val): \"\"\" Setter for option :param option: name as string :param val: value",
"@staticmethod def num2deg(xtile, ytile, zoom=17 or db.config.get('DEFAULTZOOM')): \"\"\" Translate tile into coordinate (lat,",
"area in s.first().value.keys(): return s.first().value[area] return {'module': 'default', 'width': '.2', 'visible': '0', 'center':",
"encoding='utf-8') @staticmethod def num2deg(xtile, ytile, zoom=17 or db.config.get('DEFAULTZOOM')): \"\"\" Translate tile into coordinate",
"\"\"\" Getter for option values :param option: name as string :param optional default:",
":param option: name as string :param optional default: default value if not found",
"for option values :param option: name as string :param optional default: default value",
"return default # deliver default value @staticmethod def set(option, val): \"\"\" Setter for",
"= Settings.query.filter_by(name='frontend.default') if s.count() == 1: if area == \"\": return s.first().value elif",
"for f in os.listdir(_map.path + str(zoom) + '/') if f.endswith('png')]: tiles.append(ts.replace('-', '/')) except:",
"settings s.value = val else: # add value s = Settings(option, yaml.safe_dump(val, encoding='utf-8'))",
"try: for ts in [f for f in os.listdir(_map.path + str(zoom) + '/')",
"import db class Struct(dict): def __init__(self, **entries): self.__dict__.update(entries) class Settings(db.Model): \"\"\"Settings class\"\"\" __tablename__",
"return self.value @staticmethod def getCarTypes(): ctypes = Settings.query.filter_by(name='cartypes') if ctypes.count(): return ctypes.one().value return",
"option \"\"\" s = Settings.query.filter_by(name=option) if s.count() == 1: # update return s.first().value",
"+ str(zoom) + '/') if f.endswith('png')]: tiles.append(ts.replace('-', '/')) except: pass return tiles @staticmethod",
":param zoom: zoom level :return: lat, lon tuple \"\"\" n = 2.0 **",
"map(int, Settings.get(option, '').split(',')) except ValueError: return default @staticmethod def getYaml(option): try: return Struct(**(Settings.get(option)))",
"+ '/') if f.endswith('png')]: tiles.append(ts.replace('-', '/')) except: pass return tiles @staticmethod def getFrontendSettings(area=\"\"):",
"in os.listdir(_map.path + str(zoom) + '/') if f.endswith('png')]: tiles.append(ts.replace('-', '/')) except: pass return",
"def value(self): return yaml.load(self._value) @value.setter def value(self, val): self._value = yaml.safe_dump(val, encoding='utf-8') @staticmethod",
"found in database :return: value of option \"\"\" s = Settings.query.filter_by(name=option) if s.count()",
"option \"\"\" s = Settings.query.filter_by(name=option).first() if s: # update settings s.value = val",
"not found in database :return: value of option \"\"\" s = Settings.query.filter_by(name=option) if",
"return s.first().value elif area in s.first().value.keys(): return s.first().value[area] return {'module': 'default', 'width': '.2',",
":return: value of option \"\"\" s = Settings.query.filter_by(name=option) if s.count() == 1: #",
"'.2'}} @staticmethod def get(option, default=''): \"\"\" Getter for option values :param option: name",
"value of option \"\"\" s = Settings.query.filter_by(name=option) if s.count() == 1: # update",
"__init__(self, **entries): self.__dict__.update(entries) class Settings(db.Model): \"\"\"Settings class\"\"\" __tablename__ = 'settings' __table_args__ = {'extend_existing':",
"ValueError: return default @staticmethod def getYaml(option): try: return Struct(**(Settings.get(option))) except TypeError: return Struct()",
"except ValueError: return default @staticmethod def getYaml(option): try: return Struct(**(Settings.get(option))) except TypeError: return",
":param val: value of option :return: value of option \"\"\" s = Settings.query.filter_by(name=option).first()",
"s.first().value.keys(): return s.first().value[area] return {'module': 'default', 'width': '.2', 'visible': '0', 'center': {'module': 'default'},",
"lon) :param xtile: x-coordinate of tile :param ytile: y-coordinate of tile :param zoom:",
"value @staticmethod def set(option, val): \"\"\" Setter for option :param option: name as",
"= Settings.query.filter_by(name=option).first() if s: # update settings s.value = val else: # add",
"__tablename__ = 'settings' __table_args__ = {'extend_existing': True} id = db.Column(db.Integer, primary_key=True) name =",
"n)))) return lat_deg, lon_deg def getCarTypeNames(self): return self.value @staticmethod def getCarTypes(): ctypes =",
"emonitor.modules.maps.map import Map _map = Map.getMaps(mid) tiles = [] try: for ts in",
"ctypes = Settings.query.filter_by(name='cartypes') if ctypes.count(): return ctypes.one().value return \"\" @staticmethod def get_byType(type): return",
"'default', 'width': '.2', 'visible': '0', 'center': {'module': 'default'}, 'west': {'module': 'default', 'width': '.2'},",
"'default', 'width': '.2'}} @staticmethod def get(option, default=''): \"\"\" Getter for option values :param",
"'width': '.2', 'visible': '0', 'center': {'module': 'default'}, 'west': {'module': 'default', 'width': '.2'}, 'east':",
"value(self, val): self._value = yaml.safe_dump(val, encoding='utf-8') @staticmethod def num2deg(xtile, ytile, zoom=17 or db.config.get('DEFAULTZOOM')):",
"'width': '.2'}, 'east': {'module': 'default', 'width': '.2'}} @staticmethod def get(option, default=''): \"\"\" Getter",
"{'module': 'default', 'width': '.2', 'visible': '0', 'center': {'module': 'default'}, 'west': {'module': 'default', 'width':",
"str(zoom) + '/') if f.endswith('png')]: tiles.append(ts.replace('-', '/')) except: pass return tiles @staticmethod def",
"lat_deg, lon_deg def getCarTypeNames(self): return self.value @staticmethod def getCarTypes(): ctypes = Settings.query.filter_by(name='cartypes') if",
"import os, math, yaml from emonitor.extensions import db class Struct(dict): def __init__(self, **entries):",
"class Struct(dict): def __init__(self, **entries): self.__dict__.update(entries) class Settings(db.Model): \"\"\"Settings class\"\"\" __tablename__ = 'settings'",
"'west': {'module': 'default', 'width': '.2'}, 'east': {'module': 'default', 'width': '.2'}} @staticmethod def get(option,",
"val: value of option :return: value of option \"\"\" s = Settings.query.filter_by(name=option).first() if",
"[f for f in os.listdir(_map.path + str(zoom) + '/') if f.endswith('png')]: tiles.append(ts.replace('-', '/'))",
"return yaml.load(self._value) @value.setter def value(self, val): self._value = yaml.safe_dump(val, encoding='utf-8') @staticmethod def num2deg(xtile,",
"(lat, lon) :param xtile: x-coordinate of tile :param ytile: y-coordinate of tile :param",
"@staticmethod def get_byType(type): return Settings.query.filter_by(name=type).first() or \"\" @staticmethod def getMapTiles(mid=0, zoom=17 or db.app.config.get('DEFAULTZOOM')):",
"default value if not found in database :return: value of option \"\"\" s",
"Settings.query.filter_by(name=option).first() if s: # update settings s.value = val else: # add value",
"default value @staticmethod def set(option, val): \"\"\" Setter for option :param option: name",
"@staticmethod def getMapTiles(mid=0, zoom=17 or db.app.config.get('DEFAULTZOOM')): from emonitor.modules.maps.map import Map _map = Map.getMaps(mid)",
"= value @property def value(self): return yaml.load(self._value) @value.setter def value(self, val): self._value =",
"s.count() == 1: if area == \"\": return s.first().value elif area in s.first().value.keys():",
"if s: # update settings s.value = val else: # add value s",
"encoding='utf-8')) db.session.add(s) db.session.commit() return s @staticmethod def getIntList(option, default=[]): try: return map(int, Settings.get(option,",
"@staticmethod def getFrontendSettings(area=\"\"): s = Settings.query.filter_by(name='frontend.default') if s.count() == 1: if area ==",
"db.Column(db.String(64)) _value = db.Column('value', db.Text) def __init__(self, name, value=\"\"): self.name = name self._value",
"if s.count() == 1: # update return s.first().value return default # deliver default",
"name as string :param val: value of option :return: value of option \"\"\"",
"value=\"\"): self.name = name self._value = value @property def value(self): return yaml.load(self._value) @value.setter",
"def getIntList(option, default=[]): try: return map(int, Settings.get(option, '').split(',')) except ValueError: return default @staticmethod",
"value if not found in database :return: value of option \"\"\" s ="
] |
[
"file profile = ark.ArkProfile(file_path) except: print 'FAILED: %s' % file assert False def",
"for file in files: if '.arktribe' in file: try: file_path = path +",
"'generatedtribe.arktribe') tribe2 = ark.ArkTribe(output_dir + 'generatedtribe.arktribe') assert tribe2.name.value == tribe.name.value assert tribe2.tribe_id.value ==",
"pep8.StyleGuide() result = pep8style.check_files([ 'tests/test_ark.py', 'tests/test_arktypes.py', 'arkpy/binary.py', 'arkpy/utils.py', 'arkpy/ark.py', 'arkpy/arktypes.py', ]) assert result.total_errors",
"%s' % file assert False def test_read_tribes(self): path = 'data/Servers/Server01/' files = os.listdir(path)",
"os.listdir(path) for file in files: if '.arkprofile' in file: try: file_path = path",
"import pep8 import random import os from context import arktypes, ark, binary, utils",
"test_write_read(self): owner_id = utils._gen_player_id() owner_name = arktypes.StrProperty(value='Generated Owner') tribe = ark.ArkTribe() tribe.name.set('Generated Tribe')",
"def test_write_read(self): profile = ark.ArkProfile() profile.map_name = ark.GameMapMap.the_center profile.map_path = ark.GameMapMap.the_center_path profile.unique_id.set('11111111111111111') profile.player_name.set('<NAME>')",
"== profile.header_size class TestArkTribe: def test_write_read(self): owner_id = utils._gen_player_id() owner_name = arktypes.StrProperty(value='Generated Owner')",
"!= 0 assert profile2.header_size == profile.header_size class TestArkTribe: def test_write_read(self): owner_id = utils._gen_player_id()",
"'data/Servers/Server01/' files = os.listdir(path) for file in files: if '.arktribe' in file: try:",
"random import os from context import arktypes, ark, binary, utils data_dir = 'data/'",
"import pytest import pep8 import random import os from context import arktypes, ark,",
"tribe.name.set('Generated Tribe') tribe.tribe_id.set(utils._gen_tribe_id()) tribe.owner_id.set(owner_id) tribe.members_names.value.append(owner_name) member_id = arktypes.UInt32Property(value=owner_id) tribe.members_ids.value.append(member_id) tribe.save_to_file(output_dir + 'generatedtribe.arktribe') tribe2",
"path + file profile = ark.ArkProfile(file_path) except: print 'FAILED: %s' % file assert",
"result = pep8style.check_files([ 'tests/test_ark.py', 'tests/test_arktypes.py', 'arkpy/binary.py', 'arkpy/utils.py', 'arkpy/ark.py', 'arkpy/arktypes.py', ]) assert result.total_errors ==",
"<gh_stars>10-100 import pytest import pep8 import random import os from context import arktypes,",
"profile2_female = profile2.character.isFemale.value profile_female = profile.character.isFemale.value assert profile2_female == profile_female assert profile2.character.stat_points[ark.StatMap.Health].value ==",
"profile2.unique_id.value == profile.unique_id.value assert profile2.player_name.value == profile.player_name.value assert profile2.player_id.value == profile.player_id.value profile2_female =",
"'FAILED: %s' % file assert False def test_read_tribes(self): path = 'data/Servers/Server01/' files =",
"+ file profile = ark.ArkProfile(file_path) except: print 'FAILED: %s' % file assert False",
"arktypes.StrProperty(value='Generated Owner') tribe = ark.ArkTribe() tribe.name.set('Generated Tribe') tribe.tribe_id.set(utils._gen_tribe_id()) tribe.owner_id.set(owner_id) tribe.members_names.value.append(owner_name) member_id = arktypes.UInt32Property(value=owner_id)",
"tribe.members_names.value.append(owner_name) member_id = arktypes.UInt32Property(value=owner_id) tribe.members_ids.value.append(member_id) tribe.save_to_file(output_dir + 'generatedtribe.arktribe') tribe2 = ark.ArkTribe(output_dir + 'generatedtribe.arktribe')",
"class TestStyle: def test_pep8(self): pep8style = pep8.StyleGuide() result = pep8style.check_files([ 'tests/test_ark.py', 'tests/test_arktypes.py', 'arkpy/binary.py',",
"profile = ark.ArkProfile(file_path) except: print 'FAILED: %s' % file assert False def test_read_tribes(self):",
"assert False assert True @pytest.mark.style class TestStyle: def test_pep8(self): pep8style = pep8.StyleGuide() result",
"tribe.members_names.value[0].value assert tribe2.owner_id.value == tribe.owner_id.value @pytest.mark.slow class TestBulkReads: def test_read_profiles(self): path = 'data/Servers/Server01/'",
"import arktypes, ark, binary, utils data_dir = 'data/' output_dir = 'tests/output/' class TestArkProfile:",
"def test_pep8(self): pep8style = pep8.StyleGuide() result = pep8style.check_files([ 'tests/test_ark.py', 'tests/test_arktypes.py', 'arkpy/binary.py', 'arkpy/utils.py', 'arkpy/ark.py',",
"'generatedprofile.arkprofile') # TODO: Create some functionality to compare the data dicts directly #",
"TestStyle: def test_pep8(self): pep8style = pep8.StyleGuide() result = pep8style.check_files([ 'tests/test_ark.py', 'tests/test_arktypes.py', 'arkpy/binary.py', 'arkpy/utils.py',",
"they are the same profile2 = ark.ArkProfile(output_dir + 'generatedprofile.arkprofile') assert profile2.map_name == profile.map_name",
"Create some functionality to compare the data dicts directly # to see if",
"= utils._gen_player_id() owner_name = arktypes.StrProperty(value='Generated Owner') tribe = ark.ArkTribe() tribe.name.set('Generated Tribe') tribe.tribe_id.set(utils._gen_tribe_id()) tribe.owner_id.set(owner_id)",
"to see if they are the same profile2 = ark.ArkProfile(output_dir + 'generatedprofile.arkprofile') assert",
"profile.header_size class TestArkTribe: def test_write_read(self): owner_id = utils._gen_player_id() owner_name = arktypes.StrProperty(value='Generated Owner') tribe",
"= arktypes.StrProperty(value='Generated Owner') tribe = ark.ArkTribe() tribe.name.set('Generated Tribe') tribe.tribe_id.set(utils._gen_tribe_id()) tribe.owner_id.set(owner_id) tribe.members_names.value.append(owner_name) member_id =",
"tribe.save_to_file(output_dir + 'generatedtribe.arktribe') tribe2 = ark.ArkTribe(output_dir + 'generatedtribe.arktribe') assert tribe2.name.value == tribe.name.value assert",
"if they are the same profile2 = ark.ArkProfile(output_dir + 'generatedprofile.arkprofile') assert profile2.map_name ==",
"profile2.header_size == profile.header_size class TestArkTribe: def test_write_read(self): owner_id = utils._gen_player_id() owner_name = arktypes.StrProperty(value='Generated",
"= ark.ArkTribe() tribe.name.set('Generated Tribe') tribe.tribe_id.set(utils._gen_tribe_id()) tribe.owner_id.set(owner_id) tribe.members_names.value.append(owner_name) member_id = arktypes.UInt32Property(value=owner_id) tribe.members_ids.value.append(member_id) tribe.save_to_file(output_dir +",
"file in files: if '.arkprofile' in file: try: file_path = path + file",
"profile2 = ark.ArkProfile(output_dir + 'generatedprofile.arkprofile') assert profile2.map_name == profile.map_name assert profile2.map_path == profile.map_path",
"file_path = path + file profile = ark.ArkProfile(file_path) except: print 'FAILED: %s' %",
"assert profile2.player_name.value == profile.player_name.value assert profile2.player_id.value == profile.player_id.value profile2_female = profile2.character.isFemale.value profile_female =",
"print 'FAILED: %s' % file assert False def test_read_tribes(self): path = 'data/Servers/Server01/' files",
"'FAILED: %s' % file assert False assert True @pytest.mark.style class TestStyle: def test_pep8(self):",
"= 'data/' output_dir = 'tests/output/' class TestArkProfile: def test_write_read(self): profile = ark.ArkProfile() profile.map_name",
"'.arkprofile' in file: try: file_path = path + file profile = ark.ArkProfile(file_path) except:",
"@pytest.mark.style class TestStyle: def test_pep8(self): pep8style = pep8.StyleGuide() result = pep8style.check_files([ 'tests/test_ark.py', 'tests/test_arktypes.py',",
"+ 'generatedprofile.arkprofile') assert profile2.map_name == profile.map_name assert profile2.map_path == profile.map_path assert profile2.unique_id.value ==",
"profile.save_to_file(output_dir + 'generatedprofile.arkprofile') # TODO: Create some functionality to compare the data dicts",
"= arktypes.UInt32Property(value=owner_id) tribe.members_ids.value.append(member_id) tribe.save_to_file(output_dir + 'generatedtribe.arktribe') tribe2 = ark.ArkTribe(output_dir + 'generatedtribe.arktribe') assert tribe2.name.value",
"tribe.tribe_id.value assert tribe2.members_names.value[ 0].value == tribe.members_names.value[0].value assert tribe2.owner_id.value == tribe.owner_id.value @pytest.mark.slow class TestBulkReads:",
"0].value == tribe.members_names.value[0].value assert tribe2.owner_id.value == tribe.owner_id.value @pytest.mark.slow class TestBulkReads: def test_read_profiles(self): path",
"ark.ArkProfile(file_path) except: print 'FAILED: %s' % file assert False def test_read_tribes(self): path =",
"profile_female = profile.character.isFemale.value assert profile2_female == profile_female assert profile2.character.stat_points[ark.StatMap.Health].value == 9 assert profile2.header_size",
"assert True @pytest.mark.style class TestStyle: def test_pep8(self): pep8style = pep8.StyleGuide() result = pep8style.check_files([",
"profile.player_name.value assert profile2.player_id.value == profile.player_id.value profile2_female = profile2.character.isFemale.value profile_female = profile.character.isFemale.value assert profile2_female",
"profile.player_name.set('<NAME>') profile.player_id.set(utils._gen_player_id()) profile.first_spawned.set(True) profile.character.name.set('GeneratedCharacter') profile.character.level_ups.set(9) profile.character.experience.set(450) profile.character.stat_points[ark.StatMap.Health].set(9) profile.save_to_file(output_dir + 'generatedprofile.arkprofile') # TODO: Create",
"arktypes, ark, binary, utils data_dir = 'data/' output_dir = 'tests/output/' class TestArkProfile: def",
"for file in files: if '.arkprofile' in file: try: file_path = path +",
"print 'FAILED: %s' % file assert False assert True @pytest.mark.style class TestStyle: def",
"profile.player_id.value profile2_female = profile2.character.isFemale.value profile_female = profile.character.isFemale.value assert profile2_female == profile_female assert profile2.character.stat_points[ark.StatMap.Health].value",
"if '.arkprofile' in file: try: file_path = path + file profile = ark.ArkProfile(file_path)",
"files = os.listdir(path) for file in files: if '.arktribe' in file: try: file_path",
"owner_name = arktypes.StrProperty(value='Generated Owner') tribe = ark.ArkTribe() tribe.name.set('Generated Tribe') tribe.tribe_id.set(utils._gen_tribe_id()) tribe.owner_id.set(owner_id) tribe.members_names.value.append(owner_name) member_id",
"assert profile2.character.stat_points[ark.StatMap.Health].value == 9 assert profile2.header_size != 0 assert profile2.header_size == profile.header_size class",
"files: if '.arktribe' in file: try: file_path = path + file tribe =",
"path + file tribe = ark.ArkTribe(file_path) except: print 'FAILED: %s' % file assert",
"file assert False def test_read_tribes(self): path = 'data/Servers/Server01/' files = os.listdir(path) for file",
"= ark.ArkProfile(output_dir + 'generatedprofile.arkprofile') assert profile2.map_name == profile.map_name assert profile2.map_path == profile.map_path assert",
"profile.map_path = ark.GameMapMap.the_center_path profile.unique_id.set('11111111111111111') profile.player_name.set('<NAME>') profile.player_id.set(utils._gen_player_id()) profile.first_spawned.set(True) profile.character.name.set('GeneratedCharacter') profile.character.level_ups.set(9) profile.character.experience.set(450) profile.character.stat_points[ark.StatMap.Health].set(9) profile.save_to_file(output_dir +",
"ark.GameMapMap.the_center_path profile.unique_id.set('11111111111111111') profile.player_name.set('<NAME>') profile.player_id.set(utils._gen_player_id()) profile.first_spawned.set(True) profile.character.name.set('GeneratedCharacter') profile.character.level_ups.set(9) profile.character.experience.set(450) profile.character.stat_points[ark.StatMap.Health].set(9) profile.save_to_file(output_dir + 'generatedprofile.arkprofile') #",
"TODO: Create some functionality to compare the data dicts directly # to see",
"'data/Servers/Server01/' files = os.listdir(path) for file in files: if '.arkprofile' in file: try:",
"% file assert False assert True @pytest.mark.style class TestStyle: def test_pep8(self): pep8style =",
"member_id = arktypes.UInt32Property(value=owner_id) tribe.members_ids.value.append(member_id) tribe.save_to_file(output_dir + 'generatedtribe.arktribe') tribe2 = ark.ArkTribe(output_dir + 'generatedtribe.arktribe') assert",
"== tribe.tribe_id.value assert tribe2.members_names.value[ 0].value == tribe.members_names.value[0].value assert tribe2.owner_id.value == tribe.owner_id.value @pytest.mark.slow class",
"profile.map_path assert profile2.unique_id.value == profile.unique_id.value assert profile2.player_name.value == profile.player_name.value assert profile2.player_id.value == profile.player_id.value",
"utils data_dir = 'data/' output_dir = 'tests/output/' class TestArkProfile: def test_write_read(self): profile =",
"assert profile2.header_size != 0 assert profile2.header_size == profile.header_size class TestArkTribe: def test_write_read(self): owner_id",
"dicts directly # to see if they are the same profile2 = ark.ArkProfile(output_dir",
"assert tribe2.members_names.value[ 0].value == tribe.members_names.value[0].value assert tribe2.owner_id.value == tribe.owner_id.value @pytest.mark.slow class TestBulkReads: def",
"= path + file profile = ark.ArkProfile(file_path) except: print 'FAILED: %s' % file",
"try: file_path = path + file profile = ark.ArkProfile(file_path) except: print 'FAILED: %s'",
"except: print 'FAILED: %s' % file assert False def test_read_tribes(self): path = 'data/Servers/Server01/'",
"file tribe = ark.ArkTribe(file_path) except: print 'FAILED: %s' % file assert False assert",
"'generatedprofile.arkprofile') assert profile2.map_name == profile.map_name assert profile2.map_path == profile.map_path assert profile2.unique_id.value == profile.unique_id.value",
"'tests/output/' class TestArkProfile: def test_write_read(self): profile = ark.ArkProfile() profile.map_name = ark.GameMapMap.the_center profile.map_path =",
"'generatedtribe.arktribe') assert tribe2.name.value == tribe.name.value assert tribe2.tribe_id.value == tribe.tribe_id.value assert tribe2.members_names.value[ 0].value ==",
"= pep8.StyleGuide() result = pep8style.check_files([ 'tests/test_ark.py', 'tests/test_arktypes.py', 'arkpy/binary.py', 'arkpy/utils.py', 'arkpy/ark.py', 'arkpy/arktypes.py', ]) assert",
"ark.ArkProfile(output_dir + 'generatedprofile.arkprofile') assert profile2.map_name == profile.map_name assert profile2.map_path == profile.map_path assert profile2.unique_id.value",
"the data dicts directly # to see if they are the same profile2",
"try: file_path = path + file tribe = ark.ArkTribe(file_path) except: print 'FAILED: %s'",
"== profile.map_name assert profile2.map_path == profile.map_path assert profile2.unique_id.value == profile.unique_id.value assert profile2.player_name.value ==",
"assert profile2.map_name == profile.map_name assert profile2.map_path == profile.map_path assert profile2.unique_id.value == profile.unique_id.value assert",
"def test_write_read(self): owner_id = utils._gen_player_id() owner_name = arktypes.StrProperty(value='Generated Owner') tribe = ark.ArkTribe() tribe.name.set('Generated",
"assert profile2.player_id.value == profile.player_id.value profile2_female = profile2.character.isFemale.value profile_female = profile.character.isFemale.value assert profile2_female ==",
"+ 'generatedtribe.arktribe') assert tribe2.name.value == tribe.name.value assert tribe2.tribe_id.value == tribe.tribe_id.value assert tribe2.members_names.value[ 0].value",
"profile2.character.stat_points[ark.StatMap.Health].value == 9 assert profile2.header_size != 0 assert profile2.header_size == profile.header_size class TestArkTribe:",
"file_path = path + file tribe = ark.ArkTribe(file_path) except: print 'FAILED: %s' %",
"== profile.player_name.value assert profile2.player_id.value == profile.player_id.value profile2_female = profile2.character.isFemale.value profile_female = profile.character.isFemale.value assert",
"0 assert profile2.header_size == profile.header_size class TestArkTribe: def test_write_read(self): owner_id = utils._gen_player_id() owner_name",
"class TestArkTribe: def test_write_read(self): owner_id = utils._gen_player_id() owner_name = arktypes.StrProperty(value='Generated Owner') tribe =",
"= path + file tribe = ark.ArkTribe(file_path) except: print 'FAILED: %s' % file",
"# TODO: Create some functionality to compare the data dicts directly # to",
"os.listdir(path) for file in files: if '.arktribe' in file: try: file_path = path",
"profile2.header_size != 0 assert profile2.header_size == profile.header_size class TestArkTribe: def test_write_read(self): owner_id =",
"= 'tests/output/' class TestArkProfile: def test_write_read(self): profile = ark.ArkProfile() profile.map_name = ark.GameMapMap.the_center profile.map_path",
"file in files: if '.arktribe' in file: try: file_path = path + file",
"tribe = ark.ArkTribe(file_path) except: print 'FAILED: %s' % file assert False assert True",
"= ark.GameMapMap.the_center_path profile.unique_id.set('11111111111111111') profile.player_name.set('<NAME>') profile.player_id.set(utils._gen_player_id()) profile.first_spawned.set(True) profile.character.name.set('GeneratedCharacter') profile.character.level_ups.set(9) profile.character.experience.set(450) profile.character.stat_points[ark.StatMap.Health].set(9) profile.save_to_file(output_dir + 'generatedprofile.arkprofile')",
"= profile2.character.isFemale.value profile_female = profile.character.isFemale.value assert profile2_female == profile_female assert profile2.character.stat_points[ark.StatMap.Health].value == 9",
"tribe2 = ark.ArkTribe(output_dir + 'generatedtribe.arktribe') assert tribe2.name.value == tribe.name.value assert tribe2.tribe_id.value == tribe.tribe_id.value",
"pep8style = pep8.StyleGuide() result = pep8style.check_files([ 'tests/test_ark.py', 'tests/test_arktypes.py', 'arkpy/binary.py', 'arkpy/utils.py', 'arkpy/ark.py', 'arkpy/arktypes.py', ])",
"path = 'data/Servers/Server01/' files = os.listdir(path) for file in files: if '.arkprofile' in",
"file assert False assert True @pytest.mark.style class TestStyle: def test_pep8(self): pep8style = pep8.StyleGuide()",
"profile.player_id.set(utils._gen_player_id()) profile.first_spawned.set(True) profile.character.name.set('GeneratedCharacter') profile.character.level_ups.set(9) profile.character.experience.set(450) profile.character.stat_points[ark.StatMap.Health].set(9) profile.save_to_file(output_dir + 'generatedprofile.arkprofile') # TODO: Create some",
"profile.character.level_ups.set(9) profile.character.experience.set(450) profile.character.stat_points[ark.StatMap.Health].set(9) profile.save_to_file(output_dir + 'generatedprofile.arkprofile') # TODO: Create some functionality to compare",
"context import arktypes, ark, binary, utils data_dir = 'data/' output_dir = 'tests/output/' class",
"tribe.owner_id.set(owner_id) tribe.members_names.value.append(owner_name) member_id = arktypes.UInt32Property(value=owner_id) tribe.members_ids.value.append(member_id) tribe.save_to_file(output_dir + 'generatedtribe.arktribe') tribe2 = ark.ArkTribe(output_dir +",
"ark, binary, utils data_dir = 'data/' output_dir = 'tests/output/' class TestArkProfile: def test_write_read(self):",
"directly # to see if they are the same profile2 = ark.ArkProfile(output_dir +",
"profile.unique_id.value assert profile2.player_name.value == profile.player_name.value assert profile2.player_id.value == profile.player_id.value profile2_female = profile2.character.isFemale.value profile_female",
"= os.listdir(path) for file in files: if '.arkprofile' in file: try: file_path =",
"file: try: file_path = path + file profile = ark.ArkProfile(file_path) except: print 'FAILED:",
"compare the data dicts directly # to see if they are the same",
"file: try: file_path = path + file tribe = ark.ArkTribe(file_path) except: print 'FAILED:",
"+ 'generatedprofile.arkprofile') # TODO: Create some functionality to compare the data dicts directly",
"profile.character.experience.set(450) profile.character.stat_points[ark.StatMap.Health].set(9) profile.save_to_file(output_dir + 'generatedprofile.arkprofile') # TODO: Create some functionality to compare the",
"== tribe.owner_id.value @pytest.mark.slow class TestBulkReads: def test_read_profiles(self): path = 'data/Servers/Server01/' files = os.listdir(path)",
"profile_female assert profile2.character.stat_points[ark.StatMap.Health].value == 9 assert profile2.header_size != 0 assert profile2.header_size == profile.header_size",
"tribe2.name.value == tribe.name.value assert tribe2.tribe_id.value == tribe.tribe_id.value assert tribe2.members_names.value[ 0].value == tribe.members_names.value[0].value assert",
"= os.listdir(path) for file in files: if '.arktribe' in file: try: file_path =",
"in file: try: file_path = path + file profile = ark.ArkProfile(file_path) except: print",
"data dicts directly # to see if they are the same profile2 =",
"profile2_female == profile_female assert profile2.character.stat_points[ark.StatMap.Health].value == 9 assert profile2.header_size != 0 assert profile2.header_size",
"== profile.unique_id.value assert profile2.player_name.value == profile.player_name.value assert profile2.player_id.value == profile.player_id.value profile2_female = profile2.character.isFemale.value",
"9 assert profile2.header_size != 0 assert profile2.header_size == profile.header_size class TestArkTribe: def test_write_read(self):",
"files: if '.arkprofile' in file: try: file_path = path + file profile =",
"profile.character.isFemale.value assert profile2_female == profile_female assert profile2.character.stat_points[ark.StatMap.Health].value == 9 assert profile2.header_size != 0",
"tribe.members_ids.value.append(member_id) tribe.save_to_file(output_dir + 'generatedtribe.arktribe') tribe2 = ark.ArkTribe(output_dir + 'generatedtribe.arktribe') assert tribe2.name.value == tribe.name.value",
"== tribe.name.value assert tribe2.tribe_id.value == tribe.tribe_id.value assert tribe2.members_names.value[ 0].value == tribe.members_names.value[0].value assert tribe2.owner_id.value",
"the same profile2 = ark.ArkProfile(output_dir + 'generatedprofile.arkprofile') assert profile2.map_name == profile.map_name assert profile2.map_path",
"TestArkTribe: def test_write_read(self): owner_id = utils._gen_player_id() owner_name = arktypes.StrProperty(value='Generated Owner') tribe = ark.ArkTribe()",
"'.arktribe' in file: try: file_path = path + file tribe = ark.ArkTribe(file_path) except:",
"pytest import pep8 import random import os from context import arktypes, ark, binary,",
"test_pep8(self): pep8style = pep8.StyleGuide() result = pep8style.check_files([ 'tests/test_ark.py', 'tests/test_arktypes.py', 'arkpy/binary.py', 'arkpy/utils.py', 'arkpy/ark.py', 'arkpy/arktypes.py',",
"from context import arktypes, ark, binary, utils data_dir = 'data/' output_dir = 'tests/output/'",
"assert profile2_female == profile_female assert profile2.character.stat_points[ark.StatMap.Health].value == 9 assert profile2.header_size != 0 assert",
"profile2.character.isFemale.value profile_female = profile.character.isFemale.value assert profile2_female == profile_female assert profile2.character.stat_points[ark.StatMap.Health].value == 9 assert",
"pep8 import random import os from context import arktypes, ark, binary, utils data_dir",
"assert tribe2.tribe_id.value == tribe.tribe_id.value assert tribe2.members_names.value[ 0].value == tribe.members_names.value[0].value assert tribe2.owner_id.value == tribe.owner_id.value",
"class TestArkProfile: def test_write_read(self): profile = ark.ArkProfile() profile.map_name = ark.GameMapMap.the_center profile.map_path = ark.GameMapMap.the_center_path",
"profile2.map_name == profile.map_name assert profile2.map_path == profile.map_path assert profile2.unique_id.value == profile.unique_id.value assert profile2.player_name.value",
"if '.arktribe' in file: try: file_path = path + file tribe = ark.ArkTribe(file_path)",
"= ark.GameMapMap.the_center profile.map_path = ark.GameMapMap.the_center_path profile.unique_id.set('11111111111111111') profile.player_name.set('<NAME>') profile.player_id.set(utils._gen_player_id()) profile.first_spawned.set(True) profile.character.name.set('GeneratedCharacter') profile.character.level_ups.set(9) profile.character.experience.set(450) profile.character.stat_points[ark.StatMap.Health].set(9)",
"= pep8style.check_files([ 'tests/test_ark.py', 'tests/test_arktypes.py', 'arkpy/binary.py', 'arkpy/utils.py', 'arkpy/ark.py', 'arkpy/arktypes.py', ]) assert result.total_errors == 0",
"def test_read_profiles(self): path = 'data/Servers/Server01/' files = os.listdir(path) for file in files: if",
"assert tribe2.owner_id.value == tribe.owner_id.value @pytest.mark.slow class TestBulkReads: def test_read_profiles(self): path = 'data/Servers/Server01/' files",
"TestBulkReads: def test_read_profiles(self): path = 'data/Servers/Server01/' files = os.listdir(path) for file in files:",
"%s' % file assert False assert True @pytest.mark.style class TestStyle: def test_pep8(self): pep8style",
"profile2.player_id.value == profile.player_id.value profile2_female = profile2.character.isFemale.value profile_female = profile.character.isFemale.value assert profile2_female == profile_female",
"def test_read_tribes(self): path = 'data/Servers/Server01/' files = os.listdir(path) for file in files: if",
"= 'data/Servers/Server01/' files = os.listdir(path) for file in files: if '.arkprofile' in file:",
"tribe2.tribe_id.value == tribe.tribe_id.value assert tribe2.members_names.value[ 0].value == tribe.members_names.value[0].value assert tribe2.owner_id.value == tribe.owner_id.value @pytest.mark.slow",
"profile = ark.ArkProfile() profile.map_name = ark.GameMapMap.the_center profile.map_path = ark.GameMapMap.the_center_path profile.unique_id.set('11111111111111111') profile.player_name.set('<NAME>') profile.player_id.set(utils._gen_player_id()) profile.first_spawned.set(True)",
"profile2.player_name.value == profile.player_name.value assert profile2.player_id.value == profile.player_id.value profile2_female = profile2.character.isFemale.value profile_female = profile.character.isFemale.value",
"in file: try: file_path = path + file tribe = ark.ArkTribe(file_path) except: print",
"= ark.ArkProfile() profile.map_name = ark.GameMapMap.the_center profile.map_path = ark.GameMapMap.the_center_path profile.unique_id.set('11111111111111111') profile.player_name.set('<NAME>') profile.player_id.set(utils._gen_player_id()) profile.first_spawned.set(True) profile.character.name.set('GeneratedCharacter')",
"@pytest.mark.slow class TestBulkReads: def test_read_profiles(self): path = 'data/Servers/Server01/' files = os.listdir(path) for file",
"ark.ArkTribe() tribe.name.set('Generated Tribe') tribe.tribe_id.set(utils._gen_tribe_id()) tribe.owner_id.set(owner_id) tribe.members_names.value.append(owner_name) member_id = arktypes.UInt32Property(value=owner_id) tribe.members_ids.value.append(member_id) tribe.save_to_file(output_dir + 'generatedtribe.arktribe')",
"profile.first_spawned.set(True) profile.character.name.set('GeneratedCharacter') profile.character.level_ups.set(9) profile.character.experience.set(450) profile.character.stat_points[ark.StatMap.Health].set(9) profile.save_to_file(output_dir + 'generatedprofile.arkprofile') # TODO: Create some functionality",
"tribe.tribe_id.set(utils._gen_tribe_id()) tribe.owner_id.set(owner_id) tribe.members_names.value.append(owner_name) member_id = arktypes.UInt32Property(value=owner_id) tribe.members_ids.value.append(member_id) tribe.save_to_file(output_dir + 'generatedtribe.arktribe') tribe2 = ark.ArkTribe(output_dir",
"assert profile2.map_path == profile.map_path assert profile2.unique_id.value == profile.unique_id.value assert profile2.player_name.value == profile.player_name.value assert",
"import os from context import arktypes, ark, binary, utils data_dir = 'data/' output_dir",
"data_dir = 'data/' output_dir = 'tests/output/' class TestArkProfile: def test_write_read(self): profile = ark.ArkProfile()",
"class TestBulkReads: def test_read_profiles(self): path = 'data/Servers/Server01/' files = os.listdir(path) for file in",
"# to see if they are the same profile2 = ark.ArkProfile(output_dir + 'generatedprofile.arkprofile')",
"files = os.listdir(path) for file in files: if '.arkprofile' in file: try: file_path",
"profile.map_name = ark.GameMapMap.the_center profile.map_path = ark.GameMapMap.the_center_path profile.unique_id.set('11111111111111111') profile.player_name.set('<NAME>') profile.player_id.set(utils._gen_player_id()) profile.first_spawned.set(True) profile.character.name.set('GeneratedCharacter') profile.character.level_ups.set(9) profile.character.experience.set(450)",
"== profile.player_id.value profile2_female = profile2.character.isFemale.value profile_female = profile.character.isFemale.value assert profile2_female == profile_female assert",
"== tribe.members_names.value[0].value assert tribe2.owner_id.value == tribe.owner_id.value @pytest.mark.slow class TestBulkReads: def test_read_profiles(self): path =",
"binary, utils data_dir = 'data/' output_dir = 'tests/output/' class TestArkProfile: def test_write_read(self): profile",
"os from context import arktypes, ark, binary, utils data_dir = 'data/' output_dir =",
"= ark.ArkTribe(output_dir + 'generatedtribe.arktribe') assert tribe2.name.value == tribe.name.value assert tribe2.tribe_id.value == tribe.tribe_id.value assert",
"assert False def test_read_tribes(self): path = 'data/Servers/Server01/' files = os.listdir(path) for file in",
"'data/' output_dir = 'tests/output/' class TestArkProfile: def test_write_read(self): profile = ark.ArkProfile() profile.map_name =",
"profile.character.stat_points[ark.StatMap.Health].set(9) profile.save_to_file(output_dir + 'generatedprofile.arkprofile') # TODO: Create some functionality to compare the data",
"TestArkProfile: def test_write_read(self): profile = ark.ArkProfile() profile.map_name = ark.GameMapMap.the_center profile.map_path = ark.GameMapMap.the_center_path profile.unique_id.set('11111111111111111')",
"Owner') tribe = ark.ArkTribe() tribe.name.set('Generated Tribe') tribe.tribe_id.set(utils._gen_tribe_id()) tribe.owner_id.set(owner_id) tribe.members_names.value.append(owner_name) member_id = arktypes.UInt32Property(value=owner_id) tribe.members_ids.value.append(member_id)",
"profile2.map_path == profile.map_path assert profile2.unique_id.value == profile.unique_id.value assert profile2.player_name.value == profile.player_name.value assert profile2.player_id.value",
"+ 'generatedtribe.arktribe') tribe2 = ark.ArkTribe(output_dir + 'generatedtribe.arktribe') assert tribe2.name.value == tribe.name.value assert tribe2.tribe_id.value",
"are the same profile2 = ark.ArkProfile(output_dir + 'generatedprofile.arkprofile') assert profile2.map_name == profile.map_name assert",
"tribe = ark.ArkTribe() tribe.name.set('Generated Tribe') tribe.tribe_id.set(utils._gen_tribe_id()) tribe.owner_id.set(owner_id) tribe.members_names.value.append(owner_name) member_id = arktypes.UInt32Property(value=owner_id) tribe.members_ids.value.append(member_id) tribe.save_to_file(output_dir",
"tribe2.owner_id.value == tribe.owner_id.value @pytest.mark.slow class TestBulkReads: def test_read_profiles(self): path = 'data/Servers/Server01/' files =",
"test_read_profiles(self): path = 'data/Servers/Server01/' files = os.listdir(path) for file in files: if '.arkprofile'",
"path = 'data/Servers/Server01/' files = os.listdir(path) for file in files: if '.arktribe' in",
"output_dir = 'tests/output/' class TestArkProfile: def test_write_read(self): profile = ark.ArkProfile() profile.map_name = ark.GameMapMap.the_center",
"assert profile2.header_size == profile.header_size class TestArkTribe: def test_write_read(self): owner_id = utils._gen_player_id() owner_name =",
"False assert True @pytest.mark.style class TestStyle: def test_pep8(self): pep8style = pep8.StyleGuide() result =",
"utils._gen_player_id() owner_name = arktypes.StrProperty(value='Generated Owner') tribe = ark.ArkTribe() tribe.name.set('Generated Tribe') tribe.tribe_id.set(utils._gen_tribe_id()) tribe.owner_id.set(owner_id) tribe.members_names.value.append(owner_name)",
"== 9 assert profile2.header_size != 0 assert profile2.header_size == profile.header_size class TestArkTribe: def",
"see if they are the same profile2 = ark.ArkProfile(output_dir + 'generatedprofile.arkprofile') assert profile2.map_name",
"functionality to compare the data dicts directly # to see if they are",
"in files: if '.arktribe' in file: try: file_path = path + file tribe",
"tribe.owner_id.value @pytest.mark.slow class TestBulkReads: def test_read_profiles(self): path = 'data/Servers/Server01/' files = os.listdir(path) for",
"= ark.ArkTribe(file_path) except: print 'FAILED: %s' % file assert False assert True @pytest.mark.style",
"= profile.character.isFemale.value assert profile2_female == profile_female assert profile2.character.stat_points[ark.StatMap.Health].value == 9 assert profile2.header_size !=",
"True @pytest.mark.style class TestStyle: def test_pep8(self): pep8style = pep8.StyleGuide() result = pep8style.check_files([ 'tests/test_ark.py',",
"owner_id = utils._gen_player_id() owner_name = arktypes.StrProperty(value='Generated Owner') tribe = ark.ArkTribe() tribe.name.set('Generated Tribe') tribe.tribe_id.set(utils._gen_tribe_id())",
"+ file tribe = ark.ArkTribe(file_path) except: print 'FAILED: %s' % file assert False",
"in files: if '.arkprofile' in file: try: file_path = path + file profile",
"ark.ArkTribe(file_path) except: print 'FAILED: %s' % file assert False assert True @pytest.mark.style class",
"False def test_read_tribes(self): path = 'data/Servers/Server01/' files = os.listdir(path) for file in files:",
"== profile.map_path assert profile2.unique_id.value == profile.unique_id.value assert profile2.player_name.value == profile.player_name.value assert profile2.player_id.value ==",
"= ark.ArkProfile(file_path) except: print 'FAILED: %s' % file assert False def test_read_tribes(self): path",
"to compare the data dicts directly # to see if they are the",
"same profile2 = ark.ArkProfile(output_dir + 'generatedprofile.arkprofile') assert profile2.map_name == profile.map_name assert profile2.map_path ==",
"ark.GameMapMap.the_center profile.map_path = ark.GameMapMap.the_center_path profile.unique_id.set('11111111111111111') profile.player_name.set('<NAME>') profile.player_id.set(utils._gen_player_id()) profile.first_spawned.set(True) profile.character.name.set('GeneratedCharacter') profile.character.level_ups.set(9) profile.character.experience.set(450) profile.character.stat_points[ark.StatMap.Health].set(9) profile.save_to_file(output_dir",
"ark.ArkProfile() profile.map_name = ark.GameMapMap.the_center profile.map_path = ark.GameMapMap.the_center_path profile.unique_id.set('11111111111111111') profile.player_name.set('<NAME>') profile.player_id.set(utils._gen_player_id()) profile.first_spawned.set(True) profile.character.name.set('GeneratedCharacter') profile.character.level_ups.set(9)",
"profile.map_name assert profile2.map_path == profile.map_path assert profile2.unique_id.value == profile.unique_id.value assert profile2.player_name.value == profile.player_name.value",
"arktypes.UInt32Property(value=owner_id) tribe.members_ids.value.append(member_id) tribe.save_to_file(output_dir + 'generatedtribe.arktribe') tribe2 = ark.ArkTribe(output_dir + 'generatedtribe.arktribe') assert tribe2.name.value ==",
"import random import os from context import arktypes, ark, binary, utils data_dir =",
"assert profile2.unique_id.value == profile.unique_id.value assert profile2.player_name.value == profile.player_name.value assert profile2.player_id.value == profile.player_id.value profile2_female",
"except: print 'FAILED: %s' % file assert False assert True @pytest.mark.style class TestStyle:",
"= 'data/Servers/Server01/' files = os.listdir(path) for file in files: if '.arktribe' in file:",
"test_read_tribes(self): path = 'data/Servers/Server01/' files = os.listdir(path) for file in files: if '.arktribe'",
"assert tribe2.name.value == tribe.name.value assert tribe2.tribe_id.value == tribe.tribe_id.value assert tribe2.members_names.value[ 0].value == tribe.members_names.value[0].value",
"profile.unique_id.set('11111111111111111') profile.player_name.set('<NAME>') profile.player_id.set(utils._gen_player_id()) profile.first_spawned.set(True) profile.character.name.set('GeneratedCharacter') profile.character.level_ups.set(9) profile.character.experience.set(450) profile.character.stat_points[ark.StatMap.Health].set(9) profile.save_to_file(output_dir + 'generatedprofile.arkprofile') # TODO:",
"test_write_read(self): profile = ark.ArkProfile() profile.map_name = ark.GameMapMap.the_center profile.map_path = ark.GameMapMap.the_center_path profile.unique_id.set('11111111111111111') profile.player_name.set('<NAME>') profile.player_id.set(utils._gen_player_id())",
"== profile_female assert profile2.character.stat_points[ark.StatMap.Health].value == 9 assert profile2.header_size != 0 assert profile2.header_size ==",
"% file assert False def test_read_tribes(self): path = 'data/Servers/Server01/' files = os.listdir(path) for",
"Tribe') tribe.tribe_id.set(utils._gen_tribe_id()) tribe.owner_id.set(owner_id) tribe.members_names.value.append(owner_name) member_id = arktypes.UInt32Property(value=owner_id) tribe.members_ids.value.append(member_id) tribe.save_to_file(output_dir + 'generatedtribe.arktribe') tribe2 =",
"some functionality to compare the data dicts directly # to see if they",
"profile.character.name.set('GeneratedCharacter') profile.character.level_ups.set(9) profile.character.experience.set(450) profile.character.stat_points[ark.StatMap.Health].set(9) profile.save_to_file(output_dir + 'generatedprofile.arkprofile') # TODO: Create some functionality to",
"tribe.name.value assert tribe2.tribe_id.value == tribe.tribe_id.value assert tribe2.members_names.value[ 0].value == tribe.members_names.value[0].value assert tribe2.owner_id.value ==",
"tribe2.members_names.value[ 0].value == tribe.members_names.value[0].value assert tribe2.owner_id.value == tribe.owner_id.value @pytest.mark.slow class TestBulkReads: def test_read_profiles(self):",
"ark.ArkTribe(output_dir + 'generatedtribe.arktribe') assert tribe2.name.value == tribe.name.value assert tribe2.tribe_id.value == tribe.tribe_id.value assert tribe2.members_names.value["
] |
[
"onadata.koboform import context_processors # remove this file when all servers are using new",
"<reponame>BuildAMovement/whistler-kobocat<filename>onadata/kobocat/__init__.py from onadata.koboform import context_processors # remove this file when all servers are",
"remove this file when all servers are using new settings print \"\"\" context_processors",
"all servers are using new settings print \"\"\" context_processors setting must be changed",
"using new settings print \"\"\" context_processors setting must be changed from kobocat.context_processors to",
"from onadata.koboform import context_processors # remove this file when all servers are using",
"new settings print \"\"\" context_processors setting must be changed from kobocat.context_processors to koboform.context_processors",
"settings print \"\"\" context_processors setting must be changed from kobocat.context_processors to koboform.context_processors \"\"\"",
"# remove this file when all servers are using new settings print \"\"\"",
"this file when all servers are using new settings print \"\"\" context_processors setting",
"import context_processors # remove this file when all servers are using new settings",
"file when all servers are using new settings print \"\"\" context_processors setting must",
"when all servers are using new settings print \"\"\" context_processors setting must be",
"context_processors # remove this file when all servers are using new settings print",
"servers are using new settings print \"\"\" context_processors setting must be changed from",
"are using new settings print \"\"\" context_processors setting must be changed from kobocat.context_processors"
] |
[
"# - # ## [Step 3](https://www.arpm.co/lab/redirect.php?permalink=s_checklist_scenariobased_step04-implementation-step03): Projection of risk drivers # + x_proj",
"drivers # + x_proj = np.zeros((j_, m_ + 1, d_)) dx_proj = np.zeros((j_,",
"np.shape(epsi) # next step models db_invariants_nextstep = pd.read_csv(path + 'db_invariants_nextstep.csv') # parameters for",
"'1.4' # jupytext_version: 1.1.5 # kernelspec: # display_name: Python 3 # language: python",
"information db_riskdrivers_tools = pd.read_csv(path + 'db_riskdrivers_tools.csv') d_ = int(db_riskdrivers_tools.d_.dropna()) d_credit = int(db_riskdrivers_tools.d_credit.dropna()) n_stocks",
"# project t-copula standardized invariants scenarios u_proj = tstu.cdf(epsi_tilde_proj[:, i], nu_copula) epsi_proj[:, m,",
":, d_plot - 1], lw=1) f, xp = histogram_sp(x_proj[:, -1, d_plot - 1],",
"project_trans_matrix from arpym.tools import histogram_sp, add_logo # - # ## [Input parameters](https://www.arpm.co/lab/redirect.php?permalink=s_checklist_scenariobased_step04-parameters) #",
"distribution db_estimation_parametric = pd.read_csv(path + 'db_estimation_parametric.csv', index_col=0) # estimated probabilities for nonparametric distributions",
"72.0, 720.0 / 72.0), dpi=72.0) plt.sca(ax[0]) for j in ind_j_plot_GE: f5 = plt.plot(np.arange(m_",
".3, .3], edgecolor='k') plt.title('Projected path: ' + risk_drivers_names[d_plot - 1], fontweight='bold', fontsize=20) plt.xlabel('t",
"db_riskdrivers_series.iloc[:, d_plot - 1], lw=1) # plot projected series for j in range(num_plot):",
"risk drivers modeled as GARCH(1,1) elif db_invariants_nextstep.iloc[0, d] == 'GARCH(1,1)': sig2_garch[:, m, d]",
"db_estimation_credit_copula.nu_credit[0] # - # ## [Step 1](https://www.arpm.co/lab/redirect.php?permalink=s_checklist_scenariobased_step04-implementation-step01): Determine number of projection steps and",
"10, height=xp[1] - xp[0], left=t_ + 1 + m_, facecolor=[.3, .3, .3], edgecolor='k')",
"-1, 0]): ind_j_plot_GE = np.append(ind_j_plot_GE, j) break ind_j_plot_JPM = np.zeros(1) ind_j_plot_JPM[0] = 0",
"ax[0].set_yticklabels(['', 'AAA', 'AA', 'A', 'BBB', 'BB', 'B', 'CCC', 'D', '']) plt.gca().invert_yaxis() plt.sca(ax[1]) for",
"simulate_markov_chain_multiv, \\ simulate_t, project_trans_matrix from arpym.tools import histogram_sp, add_logo # - # ##",
"int(db_riskdrivers_tools.d_implvol.dropna()) n_bonds = int(db_riskdrivers_tools.n_bonds.dropna()) i_bonds = n_bonds * 4 # 4 NS parameters",
"int(db_riskdrivers_tools.d_.dropna()) d_credit = int(db_riskdrivers_tools.d_credit.dropna()) n_stocks = int(db_riskdrivers_tools.n_stocks.dropna()) d_implvol = int(db_riskdrivers_tools.d_implvol.dropna()) n_bonds = int(db_riskdrivers_tools.n_bonds.dropna())",
"estimated annual credit transition matrix p_credit = pd.read_csv(path + 'db_invariants_p_credit.csv').values.reshape(c_ + 1, c_",
"for m in range(m_): # copula scenarios # simulate standardized invariants scenarios for",
"= db_estimation_parametric.loc['mu', str(i)] sig2_marg = db_estimation_parametric.loc['sig2', str(i)] nu_marg = db_estimation_parametric.loc['nu', str(i)] epsi_proj[:, m,",
"- 1], lw=1) f, xp = histogram_sp(x_proj[:, -1, d_plot - 1], k_=10 *",
"# format_name: light # format_version: '1.4' # jupytext_version: 1.1.5 # kernelspec: # display_name:",
"1], lw=1) f, xp = histogram_sp(x_proj[:, -1, d_plot - 1], k_=10 * np.log(j_))",
"f5 = plt.plot(np.arange(m_ + 1), ratings_proj[int(j), :, 0] + 1) plt.title('Projected rating GE',",
"20) # market risk driver path fig1 = plt.figure(figsize=(1280.0 / 72.0, 720.0 /",
"'AAA', 'AA', 'A', 'BBB', 'BB', 'B', 'CCC', 'D', '']) plt.gca().invert_yaxis() plt.sca(ax[1]) for j",
"in range(j_): if (j not in ind_j_plot_GE and ratings_proj[j, -1, 0] != ratings_proj[k,",
"plt.yticks(np.arange(10), fontsize=14) ax[1].set_yticklabels(['', 'AAA', 'AA', 'A', 'BBB', 'BB', 'B', 'CCC', 'D', '']) plt.gca().invert_yaxis()",
"modeled parametrically (estimated as Student t distributed) for i in ind_parametric: # project",
"sig2_garch = np.zeros((j_, m_ + 1, d_)) a_garch = db_invariants_param.loc['a'].values b_garch = db_invariants_param.loc['b'].values",
"+ # compute the daily credit transition matrix p_credit_daily = project_trans_matrix(p_credit, 1 /",
"m, i] = quantile_sp(u_proj, epsi[:, i], p_marginal[:, i]) # invariants modeled parametrically (estimated",
"transition matrix p_credit_daily = project_trans_matrix(p_credit, 1 / 252) # project ratings ratings_proj =",
"as plt from pandas.plotting import register_matplotlib_converters register_matplotlib_converters() from arpym.statistics import quantile_sp, simulate_markov_chain_multiv, \\",
"db_estimation_parametric.loc['mu', str(i)] sig2_marg = db_estimation_parametric.loc['sig2', str(i)] nu_marg = db_estimation_parametric.loc['nu', str(i)] epsi_proj[:, m, i]",
"* (m_ + 1),)), 'JPM': ratings_proj[:, :, 1].reshape((j_ * (m_ + 1),))}) out.to_csv(path",
"[Step 3](https://www.arpm.co/lab/redirect.php?permalink=s_checklist_scenariobased_step04-implementation-step03): Projection of risk drivers # + x_proj = np.zeros((j_, m_ +",
"arpym.tools import histogram_sp, add_logo # - # ## [Input parameters](https://www.arpm.co/lab/redirect.php?permalink=s_checklist_scenariobased_step04-parameters) # t_now is",
"= k + 1 for j in range(j_): if (j not in ind_j_plot_JPM",
"'db_estimation_credit_copula.csv') rho2_credit = db_estimation_credit_copula.rho2_credit.values.reshape(2, 2) nu_credit = db_estimation_credit_copula.nu_credit[0] # - # ## [Step",
"for m in range(1, m_ + 1): for d in range(d_): # risk",
"x_proj[:, m - 1, d] + epsi_proj[:, m - 1, d] # -",
"d] = x_proj[:, m - 1, d] + dx_proj[:, m, d] # risk",
"for d in range(d_): # risk drivers modeled as random walk if db_invariants_nextstep.iloc[0,",
"j) break ind_j_plot_JPM = np.zeros(1) ind_j_plot_JPM[0] = 0 k = 0 while k",
"import quantile_sp, simulate_markov_chain_multiv, \\ simulate_t, project_trans_matrix from arpym.tools import histogram_sp, add_logo # -",
"= project_trans_matrix(p_credit, 1 / 252) # project ratings ratings_proj = simulate_markov_chain_multiv(ratings_tnow, p_credit_daily, m_,",
"pd.DataFrame({'p': pd.Series(p)}) out.to_csv(path + 'db_scenario_probs.csv', index=None) del out # - # ## Plots",
"+ 'db_invariants_nextstep.csv') # parameters for next step models db_invariants_param = pd.read_csv(path + 'db_invariants_param.csv',",
"modeled nonparametrically for i in ind_nonparametric: # project t-copula standardized invariants scenarios u_proj",
"x_proj[:, m, d] = b_ar1 * x_proj[:, m - 1, d] + epsi_proj[:,",
"i_bonds) # invariants modeled nonparametrically ind_nonparametric = list(set(range(i_)) - set(ind_parametric)) # ## [Step",
"# name: python3 # --- # # s_checklist_scenariobased_step04 [<img src=\"https://www.arpm.co/lab/icons/icon_permalink.png\" width=30 height=30 style=\"display:",
"* tstu.ppf(u_proj, nu_marg) # - # ## [Step 3](https://www.arpm.co/lab/redirect.php?permalink=s_checklist_scenariobased_step04-implementation-step03): Projection of risk drivers",
"m in range(1, m_ + 1): for d in range(d_): # risk drivers",
"+ m_, facecolor=[.3, .3, .3], edgecolor='k') plt.title('Projected path: ' + risk_drivers_names[d_plot - 1],",
"m_, rho2=rho2_credit, nu=nu_credit, j_=j_) # - # ## [Step 5](https://www.arpm.co/lab/redirect.php?permalink=s_checklist_scenariobased_step04-implementation-step05): Save databases #",
"= pd.read_csv(path + 'db_invariants_series.csv', index_col=0, parse_dates=True) epsi = db_invariants_series.values t_, i_ = np.shape(epsi)",
"-1, 1] != ratings_proj[k, -1, 1]): ind_j_plot_JPM = np.append(ind_j_plot_JPM, j) break fig2, ax",
"of credit ratings # + # compute the daily credit transition matrix p_credit_daily",
"ax[1].set_yticklabels(['', 'AAA', 'AA', 'A', 'BBB', 'BB', 'B', 'CCC', 'D', '']) plt.gca().invert_yaxis() add_logo(fig2, set_fig_size=False)",
"db_invariants_nextstep = pd.read_csv(path + 'db_invariants_nextstep.csv') # parameters for next step models db_invariants_param =",
"= '../../../databases/temporary-databases/' # Risk drivers identification # realizations of risk drivers up to",
"252) # project ratings ratings_proj = simulate_markov_chain_multiv(ratings_tnow, p_credit_daily, m_, rho2=rho2_credit, nu=nu_credit, j_=j_) #",
"probabilities out = pd.DataFrame({'p': pd.Series(p)}) out.to_csv(path + 'db_scenario_probs.csv', index=None) del out # -",
"x_proj[j, :, d_plot - 1], lw=1) f, xp = histogram_sp(x_proj[:, -1, d_plot -",
"1, c_ + 1) # Estimation # parameters for invariants modeled using Student",
"as pd from scipy.stats import t as tstu import matplotlib.pyplot as plt from",
"# number of paths to plot num_plot = min(j_, 20) # market risk",
"'db_invariants_series.csv', index_col=0, parse_dates=True) epsi = db_invariants_series.values t_, i_ = np.shape(epsi) # next step",
"m - 1, d] + epsi_proj[:, m - 1, d] # risk drivers",
"= db_invariants_param.loc['b'].values c_garch = db_invariants_param.loc['c'].values mu_garch = db_invariants_param.loc['mu'].values # risk drivers at time",
":, 1] + 1) plt.title('Projected rating JPM', fontweight='bold', fontsize=20) plt.yticks(np.arange(10), fontsize=14) ax[1].set_yticklabels(['', 'AAA',",
"## [Step 4](https://www.arpm.co/lab/redirect.php?permalink=s_checklist_scenariobased_step04-implementation-step04): Projection of credit ratings # + # compute the daily",
"# ## [Step 2](https://www.arpm.co/lab/redirect.php?permalink=s_checklist_scenariobased_step04-implementation-step02): Projection of invariants # + epsi_proj = np.zeros((j_, m_,",
"+ x_proj = np.zeros((j_, m_ + 1, d_)) dx_proj = np.zeros((j_, m_ +",
"d]) * epsi_proj[:, m - 1, d] x_proj[:, m, d] = x_proj[:, m",
"* (dx_proj[:, m - 1, d] - mu_garch[d]) ** 2 dx_proj[:, m, d]",
"m - 1, d] x_proj[:, m, d] = x_proj[:, m - 1, d]",
"step models db_garch_sig2 = pd.read_csv(path + 'db_garch_sig2.csv', index_col=0, parse_dates=True) # estimated annual credit",
"walk': x_proj[:, m, d] = x_proj[:, m - 1, d] + epsi_proj[:, m",
"in range(num_plot): f1 = plt.plot(np.arange(t_ + 1, t_ + 1 + m_ +",
"# + plt.style.use('arpm') # number of paths to plot num_plot = min(j_, 20)",
"a_garch[d] * (dx_proj[:, m - 1, d] - mu_garch[d]) ** 2 dx_proj[:, m,",
"plot # ## [Step 0](https://www.arpm.co/lab/redirect.php?permalink=s_checklist_scenariobased_step04-implementation-step00): Load data # + path = '../../../databases/temporary-databases/' #",
"probabilities p = np.ones(j_) / j_ # invariants modeled parametrically ind_parametric = np.arange(n_stocks",
"= np.datetime64(db_riskdrivers_tools.t_now[0], 'D') # Quest for invariance # values of invariants db_invariants_series =",
"scenarios # invariants modeled nonparametrically for i in ind_nonparametric: # project t-copula standardized",
"# parameters for the credit copula db_estimation_credit_copula = pd.read_csv(path + 'db_estimation_credit_copula.csv') rho2_credit =",
"db_invariants_param.loc['mu'].values # risk drivers at time t_now are the starting values for all",
"db_riskdrivers_series.iloc[-1, :] # initialize parameters for GARCH(1,1) projection d_garch = [d for d",
"invariants scenarios for copula epsi_tilde_proj = simulate_t(np.zeros(i_), rho2_copula, nu_copula, j_) # generate invariants",
"pandas.plotting import register_matplotlib_converters register_matplotlib_converters() from arpym.statistics import quantile_sp, simulate_markov_chain_multiv, \\ simulate_t, project_trans_matrix from",
"tstu.cdf(epsi_tilde_proj[:, i], nu_copula) epsi_proj[:, m, i] = quantile_sp(u_proj, epsi[:, i], p_marginal[:, i]) #",
"ind_nonparametric: # project t-copula standardized invariants scenarios u_proj = tstu.cdf(epsi_tilde_proj[:, i], nu_copula) epsi_proj[:,",
"sig2_garch[:, m - 1, d] + \\ a_garch[d] * (dx_proj[:, m - 1,",
"i_)) for m in range(m_): # copula scenarios # simulate standardized invariants scenarios",
"invariants scenarios u_proj = tstu.cdf(epsi_tilde_proj[:, i], nu_copula) mu_marg = db_estimation_parametric.loc['mu', str(i)] sig2_marg =",
"m, d] = mu_garch[d] + \\ np.sqrt(sig2_garch[:, m, d]) * epsi_proj[:, m -",
"d] # risk drivers modeled as AR(1) elif db_invariants_nextstep.iloc[0, d] == 'AR(1)': b_ar1",
"plot historical series f1 = plt.plot(np.arange(t_ + 1), db_riskdrivers_series.iloc[:, d_plot - 1], lw=1)",
":, d].reshape((j_ * (m_ + 1),)) for d in range(d_)}) out = out[list(risk_drivers_names[:d_].values)]",
"next step models db_invariants_nextstep = pd.read_csv(path + 'db_invariants_nextstep.csv') # parameters for next step",
"= db_estimation_credit_copula.rho2_credit.values.reshape(2, 2) nu_credit = db_estimation_credit_copula.nu_credit[0] # - # ## [Step 1](https://www.arpm.co/lab/redirect.php?permalink=s_checklist_scenariobased_step04-implementation-step01): Determine",
"parameters for GARCH(1,1) projection d_garch = [d for d in range(d_) if db_invariants_nextstep.iloc[0,",
"# number of scenarios d_plot = 97 # projected risk driver to plot",
"m - 1, d] # - # ## [Step 4](https://www.arpm.co/lab/redirect.php?permalink=s_checklist_scenariobased_step04-implementation-step04): Projection of credit",
"# ## [Step 5](https://www.arpm.co/lab/redirect.php?permalink=s_checklist_scenariobased_step04-implementation-step05): Save databases # + # delete big files del",
"ratings out = pd.DataFrame({'GE': ratings_proj[:, :, 0].reshape((j_ * (m_ + 1),)), 'JPM': ratings_proj[:,",
"= pd.DataFrame({'p': pd.Series(p)}) out.to_csv(path + 'db_scenario_probs.csv', index=None) del out # - # ##",
"# market risk driver path fig1 = plt.figure(figsize=(1280.0 / 72.0, 720.0 / 72.0),",
"src=\"https://www.arpm.co/lab/icons/icon_permalink.png\" width=30 height=30 style=\"display: inline;\">](https://www.arpm.co/lab/redirect.php?code=s_checklist_scenariobased_step04&codeLang=Python) # For details, see [here](https://www.arpm.co/lab/redirect.php?permalink=ex-vue-4-copmarg). # + import",
"db_riskdrivers_tools = pd.read_csv(path + 'db_riskdrivers_tools.csv') d_ = int(db_riskdrivers_tools.d_.dropna()) d_credit = int(db_riskdrivers_tools.d_credit.dropna()) n_stocks =",
"j in ind_j_plot_JPM: plt.plot(np.arange(m_ + 1), ratings_proj[int(j), :, 1] + 1) plt.title('Projected rating",
"= quantile_sp(u_proj, epsi[:, i], p_marginal[:, i]) # invariants modeled parametrically (estimated as Student",
"# parameters for invariants modeled using Student t distribution db_estimation_parametric = pd.read_csv(path +",
"JPM', fontweight='bold', fontsize=20) plt.yticks(np.arange(10), fontsize=14) ax[1].set_yticklabels(['', 'AAA', 'AA', 'A', 'BBB', 'BB', 'B', 'CCC',",
"db_estimation_nonparametric = pd.read_csv(path + 'db_estimation_nonparametric.csv', index_col=False) p_marginal = db_estimation_nonparametric.values # parameters for estimated",
"# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name:",
"d] dx_proj[:, 0, d] = x[-1, d] - x[-2, d] # project daily",
"standardized invariants scenarios u_proj = tstu.cdf(epsi_tilde_proj[:, i], nu_copula) epsi_proj[:, m, i] = quantile_sp(u_proj,",
"# invariants modeled parametrically (estimated as Student t distributed) for i in ind_parametric:",
"m_ + 1, d_)) dx_proj = np.zeros((j_, m_ + 1, d_)) sig2_garch =",
"0](https://www.arpm.co/lab/redirect.php?permalink=s_checklist_scenariobased_step04-implementation-step00): Load data # + path = '../../../databases/temporary-databases/' # Risk drivers identification #",
"pd.Series(t_hor)}) out.to_csv(path + 'db_projection_tools.csv', index=None) del out # projected scenario probabilities out =",
"ind_j_plot_GE and ratings_proj[j, -1, 0] != ratings_proj[k, -1, 0]): ind_j_plot_GE = np.append(ind_j_plot_GE, j)",
"db_invariants_param = pd.read_csv(path + 'db_invariants_param.csv', index_col=0) # parameters for GARCH(1,1) next step models",
"# generate invariants scenarios # invariants modeled nonparametrically for i in ind_nonparametric: #",
"+ import numpy as np import pandas as pd from scipy.stats import t",
"m, i] = mu_marg + np.sqrt(sig2_marg) * tstu.ppf(u_proj, nu_marg) # - # ##",
"for d in d_garch: sig2_garch[:, 0, d] = db_garch_sig2.iloc[-1, d] dx_proj[:, 0, d]",
"'db_invariants_param.csv', index_col=0) # parameters for GARCH(1,1) next step models db_garch_sig2 = pd.read_csv(path +",
"d] = x[-1, d] - x[-2, d] # project daily scenarios for m",
"ratings_proj[int(j), :, 0] + 1) plt.title('Projected rating GE', fontweight='bold', fontsize=20) plt.yticks(np.arange(10), fontsize=14) ax[0].set_yticklabels(['',",
"pandas as pd from scipy.stats import t as tstu import matplotlib.pyplot as plt",
"in d_garch: sig2_garch[:, 0, d] = db_garch_sig2.iloc[-1, d] dx_proj[:, 0, d] = x[-1,",
"= np.datetime64('2012-10-26') # the future investment horizon j_ = 5000 # number of",
"m in range(m_): # copula scenarios # simulate standardized invariants scenarios for copula",
"d_plot - 1], lw=1) # plot projected series for j in range(num_plot): f1",
"!= ratings_proj[k, -1, 1]): ind_j_plot_JPM = np.append(ind_j_plot_JPM, j) break fig2, ax = plt.subplots(2,",
"== 'AR(1)': b_ar1 = db_invariants_param.loc['b'][d] x_proj[:, m, d] = b_ar1 * x_proj[:, m",
"# Risk drivers identification # realizations of risk drivers up to and including",
"starting values for all scenarios x_proj[:, 0, :] = db_riskdrivers_series.iloc[-1, :] # initialize",
"index_col=0) # parameters for GARCH(1,1) next step models db_garch_sig2 = pd.read_csv(path + 'db_garch_sig2.csv',",
"* epsi_proj[:, m - 1, d] x_proj[:, m, d] = x_proj[:, m -",
"= pd.DataFrame({'GE': ratings_proj[:, :, 0].reshape((j_ * (m_ + 1),)), 'JPM': ratings_proj[:, :, 1].reshape((j_",
"# - # ## [Input parameters](https://www.arpm.co/lab/redirect.php?permalink=s_checklist_scenariobased_step04-parameters) # t_now is 31-Aug-2012. Set t_hor>t_now t_hor",
"projected scenario probabilities out = pd.DataFrame({'p': pd.Series(p)}) out.to_csv(path + 'db_scenario_probs.csv', index=None) del out",
"# projected credit ratings out = pd.DataFrame({'GE': ratings_proj[:, :, 0].reshape((j_ * (m_ +",
"x n_bonds c_ = int(db_riskdrivers_tools.c_.dropna()) ratings_tnow = np.array(db_riskdrivers_tools.ratings_tnow.dropna()) t_now = np.datetime64(db_riskdrivers_tools.t_now[0], 'D') #",
"# Quest for invariance # values of invariants db_invariants_series = pd.read_csv(path + 'db_invariants_series.csv',",
"ind_j_plot_JPM: plt.plot(np.arange(m_ + 1), ratings_proj[int(j), :, 1] + 1) plt.title('Projected rating JPM', fontweight='bold',",
"c_garch = db_invariants_param.loc['c'].values mu_garch = db_invariants_param.loc['mu'].values # risk drivers at time t_now are",
"[Step 5](https://www.arpm.co/lab/redirect.php?permalink=s_checklist_scenariobased_step04-implementation-step05): Save databases # + # delete big files del dx_proj, sig2_garch",
"= pd.read_csv(path + 'db_riskdrivers_series.csv', index_col=0, parse_dates=True) x = db_riskdrivers_series.values risk_drivers_names = db_riskdrivers_series.columns #",
"pd.Series(p)}) out.to_csv(path + 'db_scenario_probs.csv', index=None) del out # - # ## Plots #",
"m - 1, d] + \\ a_garch[d] * (dx_proj[:, m - 1, d]",
"# ## [Input parameters](https://www.arpm.co/lab/redirect.php?permalink=s_checklist_scenariobased_step04-parameters) # t_now is 31-Aug-2012. Set t_hor>t_now t_hor = np.datetime64('2012-10-26')",
"* x_proj[:, m - 1, d] + epsi_proj[:, m - 1, d] #",
"[Step 0](https://www.arpm.co/lab/redirect.php?permalink=s_checklist_scenariobased_step04-implementation-step00): Load data # + path = '../../../databases/temporary-databases/' # Risk drivers identification",
"db_invariants_nextstep.iloc[0, d] == 'AR(1)': b_ar1 = db_invariants_param.loc['b'][d] x_proj[:, m, d] = b_ar1 *",
"'BB', 'B', 'CCC', 'D', '']) plt.gca().invert_yaxis() plt.sca(ax[1]) for j in ind_j_plot_JPM: plt.plot(np.arange(m_ +",
"+ d_implvol, n_stocks + 1 + d_implvol + i_bonds) # invariants modeled nonparametrically",
"format_name: light # format_version: '1.4' # jupytext_version: 1.1.5 # kernelspec: # display_name: Python",
"\\ np.sqrt(sig2_garch[:, m, d]) * epsi_proj[:, m - 1, d] x_proj[:, m, d]",
"plt.style.use('arpm') # number of paths to plot num_plot = min(j_, 20) # market",
"db_estimation_nonparametric.values # parameters for estimated Student t copula db_estimation_copula = pd.read_csv(path + 'db_estimation_copula.csv')",
"2](https://www.arpm.co/lab/redirect.php?permalink=s_checklist_scenariobased_step04-implementation-step02): Projection of invariants # + epsi_proj = np.zeros((j_, m_, i_)) for m",
"'D') # Quest for invariance # values of invariants db_invariants_series = pd.read_csv(path +",
"+ 'db_invariants_param.csv', index_col=0) # parameters for GARCH(1,1) next step models db_garch_sig2 = pd.read_csv(path",
"d].reshape((j_ * (m_ + 1),)) for d in range(d_)}) out = out[list(risk_drivers_names[:d_].values)] out.to_csv(path",
"= np.zeros((j_, m_ + 1, d_)) dx_proj = np.zeros((j_, m_ + 1, d_))",
"# invariants modeled nonparametrically ind_nonparametric = list(set(range(i_)) - set(ind_parametric)) # ## [Step 2](https://www.arpm.co/lab/redirect.php?permalink=s_checklist_scenariobased_step04-implementation-step02):",
"# estimated probabilities for nonparametric distributions db_estimation_nonparametric = pd.read_csv(path + 'db_estimation_nonparametric.csv', index_col=False) p_marginal",
"np.busday_count(t_now, t_hor) # projection scenario probabilities p = np.ones(j_) / j_ # invariants",
"= pd.DataFrame({risk_drivers_names[d]: x_proj[:, :, d].reshape((j_ * (m_ + 1),)) for d in range(d_)})",
"np.log(j_)) f1 = plt.barh(xp, f / 10, height=xp[1] - xp[0], left=t_ + 1",
"1] + 1) plt.title('Projected rating JPM', fontweight='bold', fontsize=20) plt.yticks(np.arange(10), fontsize=14) ax[1].set_yticklabels(['', 'AAA', 'AA',",
"4 # 4 NS parameters x n_bonds c_ = int(db_riskdrivers_tools.c_.dropna()) ratings_tnow = np.array(db_riskdrivers_tools.ratings_tnow.dropna())",
"= int(db_riskdrivers_tools.d_credit.dropna()) n_stocks = int(db_riskdrivers_tools.n_stocks.dropna()) d_implvol = int(db_riskdrivers_tools.d_implvol.dropna()) n_bonds = int(db_riskdrivers_tools.n_bonds.dropna()) i_bonds =",
"details, see [here](https://www.arpm.co/lab/redirect.php?permalink=ex-vue-4-copmarg). # + import numpy as np import pandas as pd",
"probabilities for nonparametric distributions db_estimation_nonparametric = pd.read_csv(path + 'db_estimation_nonparametric.csv', index_col=False) p_marginal = db_estimation_nonparametric.values",
"p_marginal[:, i]) # invariants modeled parametrically (estimated as Student t distributed) for i",
"epsi = db_invariants_series.values t_, i_ = np.shape(epsi) # next step models db_invariants_nextstep =",
"horizon j_ = 5000 # number of scenarios d_plot = 97 # projected",
"db_garch_sig2 = pd.read_csv(path + 'db_garch_sig2.csv', index_col=0, parse_dates=True) # estimated annual credit transition matrix",
"# the future investment horizon j_ = 5000 # number of scenarios d_plot",
"= pd.read_csv(path + 'db_estimation_parametric.csv', index_col=0) # estimated probabilities for nonparametric distributions db_estimation_nonparametric =",
"i_ = np.shape(epsi) # next step models db_invariants_nextstep = pd.read_csv(path + 'db_invariants_nextstep.csv') #",
"scenario probabilities # number of monitoring times m_ = np.busday_count(t_now, t_hor) # projection",
"- 1, d] x_proj[:, m, d] = x_proj[:, m - 1, d] +",
"as tstu import matplotlib.pyplot as plt from pandas.plotting import register_matplotlib_converters register_matplotlib_converters() from arpym.statistics",
"## Plots # + plt.style.use('arpm') # number of paths to plot num_plot =",
"'BBB', 'BB', 'B', 'CCC', 'D', '']) plt.gca().invert_yaxis() plt.sca(ax[1]) for j in ind_j_plot_JPM: plt.plot(np.arange(m_",
"1, d] # - # ## [Step 4](https://www.arpm.co/lab/redirect.php?permalink=s_checklist_scenariobased_step04-implementation-step04): Projection of credit ratings #",
"db_riskdrivers_series.values risk_drivers_names = db_riskdrivers_series.columns # additional information db_riskdrivers_tools = pd.read_csv(path + 'db_riskdrivers_tools.csv') d_",
"j_) # generate invariants scenarios # invariants modeled nonparametrically for i in ind_nonparametric:",
"= tstu.cdf(epsi_tilde_proj[:, i], nu_copula) epsi_proj[:, m, i] = quantile_sp(u_proj, epsi[:, i], p_marginal[:, i])",
"for GARCH(1,1) next step models db_garch_sig2 = pd.read_csv(path + 'db_garch_sig2.csv', index_col=0, parse_dates=True) #",
"Risk drivers identification # realizations of risk drivers up to and including time",
"pd.DataFrame({'GE': ratings_proj[:, :, 0].reshape((j_ * (m_ + 1),)), 'JPM': ratings_proj[:, :, 1].reshape((j_ *",
"step models db_invariants_param = pd.read_csv(path + 'db_invariants_param.csv', index_col=0) # parameters for GARCH(1,1) next",
"1) plt.title('Projected rating JPM', fontweight='bold', fontsize=20) plt.yticks(np.arange(10), fontsize=14) ax[1].set_yticklabels(['', 'AAA', 'AA', 'A', 'BBB',",
"parametrically ind_parametric = np.arange(n_stocks + 1 + d_implvol, n_stocks + 1 + d_implvol",
"parameters for GARCH(1,1) next step models db_garch_sig2 = pd.read_csv(path + 'db_garch_sig2.csv', index_col=0, parse_dates=True)",
"quantile_sp, simulate_markov_chain_multiv, \\ simulate_t, project_trans_matrix from arpym.tools import histogram_sp, add_logo # - #",
"t_hor = np.datetime64('2012-10-26') # the future investment horizon j_ = 5000 # number",
"t distributed) for i in ind_parametric: # project t-copula standardized invariants scenarios u_proj",
"out.to_csv(path + 'db_projection_tools.csv', index=None) del out # projected scenario probabilities out = pd.DataFrame({'p':",
"1), ratings_proj[int(j), :, 0] + 1) plt.title('Projected rating GE', fontweight='bold', fontsize=20) plt.yticks(np.arange(10), fontsize=14)",
"Set t_hor>t_now t_hor = np.datetime64('2012-10-26') # the future investment horizon j_ = 5000",
"np.datetime64(db_riskdrivers_tools.t_now[0], 'D') # Quest for invariance # values of invariants db_invariants_series = pd.read_csv(path",
"nu_copula) epsi_proj[:, m, i] = quantile_sp(u_proj, epsi[:, i], p_marginal[:, i]) # invariants modeled",
"out.to_csv(path + 'db_projection_riskdrivers.csv', index=None) del out # projected credit ratings out = pd.DataFrame({'GE':",
"+ 1), db_riskdrivers_series.iloc[:, d_plot - 1], lw=1) # plot projected series for j",
"= b_ar1 * x_proj[:, m - 1, d] + epsi_proj[:, m - 1,",
"+ 1 + m_ + 1), x_proj[j, :, d_plot - 1], lw=1) f,",
"# next step models db_invariants_nextstep = pd.read_csv(path + 'db_invariants_nextstep.csv') # parameters for next",
"5000 # number of scenarios d_plot = 97 # projected risk driver to",
"= np.array(db_estimation_copula['rho2']).reshape(i_, i_) # parameters for the credit copula db_estimation_credit_copula = pd.read_csv(path +",
"f1 = plt.barh(xp, f / 10, height=xp[1] - xp[0], left=t_ + 1 +",
"range(d_) if db_invariants_nextstep.iloc[0, d] == 'GARCH(1,1)'] for d in d_garch: sig2_garch[:, 0, d]",
"'db_scenario_probs.csv', index=None) del out # - # ## Plots # + plt.style.use('arpm') #",
"0]): ind_j_plot_GE = np.append(ind_j_plot_GE, j) break ind_j_plot_JPM = np.zeros(1) ind_j_plot_JPM[0] = 0 k",
"+ 1, d_)) dx_proj = np.zeros((j_, m_ + 1, d_)) sig2_garch = np.zeros((j_,",
"/ 252) # project ratings ratings_proj = simulate_markov_chain_multiv(ratings_tnow, p_credit_daily, m_, rho2=rho2_credit, nu=nu_credit, j_=j_)",
"additional information db_riskdrivers_tools = pd.read_csv(path + 'db_riskdrivers_tools.csv') d_ = int(db_riskdrivers_tools.d_.dropna()) d_credit = int(db_riskdrivers_tools.d_credit.dropna())",
"= min(j_, 20) # market risk driver path fig1 = plt.figure(figsize=(1280.0 / 72.0,",
"d_implvol + i_bonds) # invariants modeled nonparametrically ind_nonparametric = list(set(range(i_)) - set(ind_parametric)) #",
"inline;\">](https://www.arpm.co/lab/redirect.php?code=s_checklist_scenariobased_step04&codeLang=Python) # For details, see [here](https://www.arpm.co/lab/redirect.php?permalink=ex-vue-4-copmarg). # + import numpy as np import",
"/ 72.0, 720.0 / 72.0), dpi=72.0) # plot historical series f1 = plt.plot(np.arange(t_",
"risk driver path fig1 = plt.figure(figsize=(1280.0 / 72.0, 720.0 / 72.0), dpi=72.0) #",
"# invariants modeled parametrically ind_parametric = np.arange(n_stocks + 1 + d_implvol, n_stocks +",
"# s_checklist_scenariobased_step04 [<img src=\"https://www.arpm.co/lab/icons/icon_permalink.png\" width=30 height=30 style=\"display: inline;\">](https://www.arpm.co/lab/redirect.php?code=s_checklist_scenariobased_step04&codeLang=Python) # For details, see [here](https://www.arpm.co/lab/redirect.php?permalink=ex-vue-4-copmarg).",
"del dx_proj, sig2_garch # projected risk drivers out = pd.DataFrame({risk_drivers_names[d]: x_proj[:, :, d].reshape((j_",
"1 / 252) # project ratings ratings_proj = simulate_markov_chain_multiv(ratings_tnow, p_credit_daily, m_, rho2=rho2_credit, nu=nu_credit,",
"including time t_now db_riskdrivers_series = pd.read_csv(path + 'db_riskdrivers_series.csv', index_col=0, parse_dates=True) x = db_riskdrivers_series.values",
"# kernelspec: # display_name: Python 3 # language: python # name: python3 #",
"rho2_copula, nu_copula, j_) # generate invariants scenarios # invariants modeled nonparametrically for i",
"- 1], lw=1) # plot projected series for j in range(num_plot): f1 =",
"0 while k < num_plot: k = k + 1 for j in",
"language: python # name: python3 # --- # # s_checklist_scenariobased_step04 [<img src=\"https://www.arpm.co/lab/icons/icon_permalink.png\" width=30",
"fontsize=14) ax[0].set_yticklabels(['', 'AAA', 'AA', 'A', 'BBB', 'BB', 'B', 'CCC', 'D', '']) plt.gca().invert_yaxis() plt.sca(ax[1])",
"# delete big files del dx_proj, sig2_garch # projected risk drivers out =",
"# For details, see [here](https://www.arpm.co/lab/redirect.php?permalink=ex-vue-4-copmarg). # + import numpy as np import pandas",
"plt.plot(np.arange(m_ + 1), ratings_proj[int(j), :, 1] + 1) plt.title('Projected rating JPM', fontweight='bold', fontsize=20)",
"in range(d_)}) out = out[list(risk_drivers_names[:d_].values)] out.to_csv(path + 'db_projection_riskdrivers.csv', index=None) del out # projected",
"db_estimation_parametric.loc['nu', str(i)] epsi_proj[:, m, i] = mu_marg + np.sqrt(sig2_marg) * tstu.ppf(u_proj, nu_marg) #",
"(j not in ind_j_plot_JPM and ratings_proj[j, -1, 1] != ratings_proj[k, -1, 1]): ind_j_plot_JPM",
":, 1].reshape((j_ * (m_ + 1),))}) out.to_csv(path + 'db_projection_ratings.csv', index=None) del out #",
"1 + m_ + 1), x_proj[j, :, d_plot - 1], lw=1) f, xp",
"= db_invariants_series.values t_, i_ = np.shape(epsi) # next step models db_invariants_nextstep = pd.read_csv(path",
"monitoring times m_ = np.busday_count(t_now, t_hor) # projection scenario probabilities p = np.ones(j_)",
"mu_garch[d]) ** 2 dx_proj[:, m, d] = mu_garch[d] + \\ np.sqrt(sig2_garch[:, m, d])",
"+ 1): for d in range(d_): # risk drivers modeled as random walk",
"# realizations of risk drivers up to and including time t_now db_riskdrivers_series =",
"f1 = plt.plot(np.arange(t_ + 1, t_ + 1 + m_ + 1), x_proj[j,",
"!= ratings_proj[k, -1, 0]): ind_j_plot_GE = np.append(ind_j_plot_GE, j) break ind_j_plot_JPM = np.zeros(1) ind_j_plot_JPM[0]",
"# projected risk driver to plot # ## [Step 0](https://www.arpm.co/lab/redirect.php?permalink=s_checklist_scenariobased_step04-implementation-step00): Load data #",
"of monitoring times m_ = np.busday_count(t_now, t_hor) # projection scenario probabilities p =",
"= plt.subplots(2, 1, figsize=(1280.0 / 72.0, 720.0 / 72.0), dpi=72.0) plt.sca(ax[0]) for j",
"if db_invariants_nextstep.iloc[0, d] == 'Random walk': x_proj[:, m, d] = x_proj[:, m -",
"x[-1, d] - x[-2, d] # project daily scenarios for m in range(1,",
"scipy.stats import t as tstu import matplotlib.pyplot as plt from pandas.plotting import register_matplotlib_converters",
"copula scenarios # simulate standardized invariants scenarios for copula epsi_tilde_proj = simulate_t(np.zeros(i_), rho2_copula,",
"[<img src=\"https://www.arpm.co/lab/icons/icon_permalink.png\" width=30 height=30 style=\"display: inline;\">](https://www.arpm.co/lab/redirect.php?code=s_checklist_scenariobased_step04&codeLang=Python) # For details, see [here](https://www.arpm.co/lab/redirect.php?permalink=ex-vue-4-copmarg). # +",
"invariants modeled parametrically ind_parametric = np.arange(n_stocks + 1 + d_implvol, n_stocks + 1",
"epsi[:, i], p_marginal[:, i]) # invariants modeled parametrically (estimated as Student t distributed)",
"in range(d_) if db_invariants_nextstep.iloc[0, d] == 'GARCH(1,1)'] for d in d_garch: sig2_garch[:, 0,",
"elif db_invariants_nextstep.iloc[0, d] == 'AR(1)': b_ar1 = db_invariants_param.loc['b'][d] x_proj[:, m, d] = b_ar1",
"out = out[list(risk_drivers_names[:d_].values)] out.to_csv(path + 'db_projection_riskdrivers.csv', index=None) del out # projected credit ratings",
"range(d_): # risk drivers modeled as random walk if db_invariants_nextstep.iloc[0, d] == 'Random",
"python # name: python3 # --- # # s_checklist_scenariobased_step04 [<img src=\"https://www.arpm.co/lab/icons/icon_permalink.png\" width=30 height=30",
"(m_ + 1),)), 'JPM': ratings_proj[:, :, 1].reshape((j_ * (m_ + 1),))}) out.to_csv(path +",
"height=xp[1] - xp[0], left=t_ + 1 + m_, facecolor=[.3, .3, .3], edgecolor='k') plt.title('Projected",
"# plot historical series f1 = plt.plot(np.arange(t_ + 1), db_riskdrivers_series.iloc[:, d_plot - 1],",
"jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version:",
"int(db_estimation_copula['nu'].iloc[0]) rho2_copula = np.array(db_estimation_copula['rho2']).reshape(i_, i_) # parameters for the credit copula db_estimation_credit_copula =",
"0].reshape((j_ * (m_ + 1),)), 'JPM': ratings_proj[:, :, 1].reshape((j_ * (m_ + 1),))})",
"risk drivers up to and including time t_now db_riskdrivers_series = pd.read_csv(path + 'db_riskdrivers_series.csv',",
"drivers out = pd.DataFrame({risk_drivers_names[d]: x_proj[:, :, d].reshape((j_ * (m_ + 1),)) for d",
"ratings_proj[k, -1, 1]): ind_j_plot_JPM = np.append(ind_j_plot_JPM, j) break fig2, ax = plt.subplots(2, 1,",
"[Step 2](https://www.arpm.co/lab/redirect.php?permalink=s_checklist_scenariobased_step04-implementation-step02): Projection of invariants # + epsi_proj = np.zeros((j_, m_, i_)) for",
"+ 'db_estimation_copula.csv') nu_copula = int(db_estimation_copula['nu'].iloc[0]) rho2_copula = np.array(db_estimation_copula['rho2']).reshape(i_, i_) # parameters for the",
"quantile_sp(u_proj, epsi[:, i], p_marginal[:, i]) # invariants modeled parametrically (estimated as Student t",
"values of invariants db_invariants_series = pd.read_csv(path + 'db_invariants_series.csv', index_col=0, parse_dates=True) epsi = db_invariants_series.values",
"+ 1),)), 'JPM': ratings_proj[:, :, 1].reshape((j_ * (m_ + 1),))}) out.to_csv(path + 'db_projection_ratings.csv',",
"the future investment horizon j_ = 5000 # number of scenarios d_plot =",
"pd.read_csv(path + 'db_estimation_credit_copula.csv') rho2_credit = db_estimation_credit_copula.rho2_credit.values.reshape(2, 2) nu_credit = db_estimation_credit_copula.nu_credit[0] # - #",
"# initialize parameters for GARCH(1,1) projection d_garch = [d for d in range(d_)",
"# plot projected ratings # select paths with rating changes ind_j_plot_GE = np.zeros(1)",
"annual credit transition matrix p_credit = pd.read_csv(path + 'db_invariants_p_credit.csv').values.reshape(c_ + 1, c_ +",
"m_ + 1, d_)) sig2_garch = np.zeros((j_, m_ + 1, d_)) a_garch =",
"models db_invariants_nextstep = pd.read_csv(path + 'db_invariants_nextstep.csv') # parameters for next step models db_invariants_param",
"dx_proj[:, m, d] # risk drivers modeled as AR(1) elif db_invariants_nextstep.iloc[0, d] ==",
"index=None) del out # projected scenario probabilities out = pd.DataFrame({'p': pd.Series(p)}) out.to_csv(path +",
"for i in ind_nonparametric: # project t-copula standardized invariants scenarios u_proj = tstu.cdf(epsi_tilde_proj[:,",
"+ 1, d_)) sig2_garch = np.zeros((j_, m_ + 1, d_)) a_garch = db_invariants_param.loc['a'].values",
"+ 1) # Estimation # parameters for invariants modeled using Student t distribution",
"models db_garch_sig2 = pd.read_csv(path + 'db_garch_sig2.csv', index_col=0, parse_dates=True) # estimated annual credit transition",
"mu_marg + np.sqrt(sig2_marg) * tstu.ppf(u_proj, nu_marg) # - # ## [Step 3](https://www.arpm.co/lab/redirect.php?permalink=s_checklist_scenariobased_step04-implementation-step03): Projection",
"# # s_checklist_scenariobased_step04 [<img src=\"https://www.arpm.co/lab/icons/icon_permalink.png\" width=30 height=30 style=\"display: inline;\">](https://www.arpm.co/lab/redirect.php?code=s_checklist_scenariobased_step04&codeLang=Python) # For details, see",
"'db_invariants_nextstep.csv') # parameters for next step models db_invariants_param = pd.read_csv(path + 'db_invariants_param.csv', index_col=0)",
"min(j_, 20) # market risk driver path fig1 = plt.figure(figsize=(1280.0 / 72.0, 720.0",
"n_stocks + 1 + d_implvol + i_bonds) # invariants modeled nonparametrically ind_nonparametric =",
"0, :] = db_riskdrivers_series.iloc[-1, :] # initialize parameters for GARCH(1,1) projection d_garch =",
"'db_riskdrivers_tools.csv') d_ = int(db_riskdrivers_tools.d_.dropna()) d_credit = int(db_riskdrivers_tools.d_credit.dropna()) n_stocks = int(db_riskdrivers_tools.n_stocks.dropna()) d_implvol = int(db_riskdrivers_tools.d_implvol.dropna())",
"credit ratings # + # compute the daily credit transition matrix p_credit_daily =",
"- 1, d] + dx_proj[:, m, d] # risk drivers modeled as AR(1)",
"range(1, m_ + 1): for d in range(d_): # risk drivers modeled as",
"d] == 'GARCH(1,1)': sig2_garch[:, m, d] = c_garch[d] + \\ b_garch[d] * sig2_garch[:,",
"range(num_plot): f1 = plt.plot(np.arange(t_ + 1, t_ + 1 + m_ + 1),",
"= mu_marg + np.sqrt(sig2_marg) * tstu.ppf(u_proj, nu_marg) # - # ## [Step 3](https://www.arpm.co/lab/redirect.php?permalink=s_checklist_scenariobased_step04-implementation-step03):",
"j_=j_) # - # ## [Step 5](https://www.arpm.co/lab/redirect.php?permalink=s_checklist_scenariobased_step04-implementation-step05): Save databases # + # delete",
"= np.append(ind_j_plot_GE, j) break ind_j_plot_JPM = np.zeros(1) ind_j_plot_JPM[0] = 0 k = 0",
"d] # project daily scenarios for m in range(1, m_ + 1): for",
"x_proj[:, m, d] = x_proj[:, m - 1, d] + dx_proj[:, m, d]",
"format_version: '1.4' # jupytext_version: 1.1.5 # kernelspec: # display_name: Python 3 # language:",
"## [Step 0](https://www.arpm.co/lab/redirect.php?permalink=s_checklist_scenariobased_step04-implementation-step00): Load data # + path = '../../../databases/temporary-databases/' # Risk drivers",
"identification # realizations of risk drivers up to and including time t_now db_riskdrivers_series",
"'GARCH(1,1)'] for d in d_garch: sig2_garch[:, 0, d] = db_garch_sig2.iloc[-1, d] dx_proj[:, 0,",
"(m_ + 1),)) for d in range(d_)}) out = out[list(risk_drivers_names[:d_].values)] out.to_csv(path + 'db_projection_riskdrivers.csv',",
"fontweight='bold', fontsize=20) plt.xlabel('t (days)', fontsize=17) plt.xticks(fontsize=14) plt.yticks(fontsize=14) add_logo(fig1, set_fig_size=False) fig1.tight_layout() # plot projected",
"probabilities # number of monitoring times m_ = np.busday_count(t_now, t_hor) # projection scenario",
"< num_plot: k = k + 1 for j in range(j_): if (j",
"- 1], fontweight='bold', fontsize=20) plt.xlabel('t (days)', fontsize=17) plt.xticks(fontsize=14) plt.yticks(fontsize=14) add_logo(fig1, set_fig_size=False) fig1.tight_layout() #",
"dx_proj[:, m, d] = mu_garch[d] + \\ np.sqrt(sig2_garch[:, m, d]) * epsi_proj[:, m",
"of risk drivers # + x_proj = np.zeros((j_, m_ + 1, d_)) dx_proj",
"path fig1 = plt.figure(figsize=(1280.0 / 72.0, 720.0 / 72.0), dpi=72.0) # plot historical",
"jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.4' #",
"historical series f1 = plt.plot(np.arange(t_ + 1), db_riskdrivers_series.iloc[:, d_plot - 1], lw=1) #",
"j in range(j_): if (j not in ind_j_plot_GE and ratings_proj[j, -1, 0] !=",
"ind_j_plot_GE = np.append(ind_j_plot_GE, j) break ind_j_plot_JPM = np.zeros(1) ind_j_plot_JPM[0] = 0 k =",
"as random walk if db_invariants_nextstep.iloc[0, d] == 'Random walk': x_proj[:, m, d] =",
"= pd.read_csv(path + 'db_estimation_nonparametric.csv', index_col=False) p_marginal = db_estimation_nonparametric.values # parameters for estimated Student",
"estimated probabilities for nonparametric distributions db_estimation_nonparametric = pd.read_csv(path + 'db_estimation_nonparametric.csv', index_col=False) p_marginal =",
"# parameters for GARCH(1,1) next step models db_garch_sig2 = pd.read_csv(path + 'db_garch_sig2.csv', index_col=0,",
"light # format_version: '1.4' # jupytext_version: 1.1.5 # kernelspec: # display_name: Python 3",
"m - 1, d] - mu_garch[d]) ** 2 dx_proj[:, m, d] = mu_garch[d]",
"# number of scenarios and future investment horizon out = pd.DataFrame({'j_': pd.Series(j_), 't_hor':",
"from pandas.plotting import register_matplotlib_converters register_matplotlib_converters() from arpym.statistics import quantile_sp, simulate_markov_chain_multiv, \\ simulate_t, project_trans_matrix",
"pd.read_csv(path + 'db_riskdrivers_series.csv', index_col=0, parse_dates=True) x = db_riskdrivers_series.values risk_drivers_names = db_riskdrivers_series.columns # additional",
"= db_invariants_param.loc['c'].values mu_garch = db_invariants_param.loc['mu'].values # risk drivers at time t_now are the",
"+ 1 for j in range(j_): if (j not in ind_j_plot_GE and ratings_proj[j,",
"modeled as random walk if db_invariants_nextstep.iloc[0, d] == 'Random walk': x_proj[:, m, d]",
"while k < num_plot: k = k + 1 for j in range(j_):",
"series for j in range(num_plot): f1 = plt.plot(np.arange(t_ + 1, t_ + 1",
"== 'GARCH(1,1)'] for d in d_garch: sig2_garch[:, 0, d] = db_garch_sig2.iloc[-1, d] dx_proj[:,",
"nonparametric distributions db_estimation_nonparametric = pd.read_csv(path + 'db_estimation_nonparametric.csv', index_col=False) p_marginal = db_estimation_nonparametric.values # parameters",
"files del dx_proj, sig2_garch # projected risk drivers out = pd.DataFrame({risk_drivers_names[d]: x_proj[:, :,",
"ratings_proj[j, -1, 1] != ratings_proj[k, -1, 1]): ind_j_plot_JPM = np.append(ind_j_plot_JPM, j) break fig2,",
"out.to_csv(path + 'db_scenario_probs.csv', index=None) del out # - # ## Plots # +",
"ax = plt.subplots(2, 1, figsize=(1280.0 / 72.0, 720.0 / 72.0), dpi=72.0) plt.sca(ax[0]) for",
"simulate standardized invariants scenarios for copula epsi_tilde_proj = simulate_t(np.zeros(i_), rho2_copula, nu_copula, j_) #",
"index_col=0, parse_dates=True) # estimated annual credit transition matrix p_credit = pd.read_csv(path + 'db_invariants_p_credit.csv').values.reshape(c_",
"s_checklist_scenariobased_step04 [<img src=\"https://www.arpm.co/lab/icons/icon_permalink.png\" width=30 height=30 style=\"display: inline;\">](https://www.arpm.co/lab/redirect.php?code=s_checklist_scenariobased_step04&codeLang=Python) # For details, see [here](https://www.arpm.co/lab/redirect.php?permalink=ex-vue-4-copmarg). #",
"using Student t distribution db_estimation_parametric = pd.read_csv(path + 'db_estimation_parametric.csv', index_col=0) # estimated probabilities",
"db_estimation_parametric.loc['sig2', str(i)] nu_marg = db_estimation_parametric.loc['nu', str(i)] epsi_proj[:, m, i] = mu_marg + np.sqrt(sig2_marg)",
"nu=nu_credit, j_=j_) # - # ## [Step 5](https://www.arpm.co/lab/redirect.php?permalink=s_checklist_scenariobased_step04-implementation-step05): Save databases # + #",
"plot num_plot = min(j_, 20) # market risk driver path fig1 = plt.figure(figsize=(1280.0",
"ind_parametric = np.arange(n_stocks + 1 + d_implvol, n_stocks + 1 + d_implvol +",
"xp = histogram_sp(x_proj[:, -1, d_plot - 1], k_=10 * np.log(j_)) f1 = plt.barh(xp,",
"driver path fig1 = plt.figure(figsize=(1280.0 / 72.0, 720.0 / 72.0), dpi=72.0) # plot",
"k_=10 * np.log(j_)) f1 = plt.barh(xp, f / 10, height=xp[1] - xp[0], left=t_",
"del out # - # ## Plots # + plt.style.use('arpm') # number of",
"rating GE', fontweight='bold', fontsize=20) plt.yticks(np.arange(10), fontsize=14) ax[0].set_yticklabels(['', 'AAA', 'AA', 'A', 'BBB', 'BB', 'B',",
"parameters](https://www.arpm.co/lab/redirect.php?permalink=s_checklist_scenariobased_step04-parameters) # t_now is 31-Aug-2012. Set t_hor>t_now t_hor = np.datetime64('2012-10-26') # the future",
"j_ = 5000 # number of scenarios d_plot = 97 # projected risk",
"from arpym.statistics import quantile_sp, simulate_markov_chain_multiv, \\ simulate_t, project_trans_matrix from arpym.tools import histogram_sp, add_logo",
"m_, i_)) for m in range(m_): # copula scenarios # simulate standardized invariants",
"# - # ## [Step 4](https://www.arpm.co/lab/redirect.php?permalink=s_checklist_scenariobased_step04-implementation-step04): Projection of credit ratings # + #",
"j_ # invariants modeled parametrically ind_parametric = np.arange(n_stocks + 1 + d_implvol, n_stocks",
"and scenario probabilities # number of monitoring times m_ = np.busday_count(t_now, t_hor) #",
"= db_riskdrivers_series.columns # additional information db_riskdrivers_tools = pd.read_csv(path + 'db_riskdrivers_tools.csv') d_ = int(db_riskdrivers_tools.d_.dropna())",
"# - # ## Plots # + plt.style.use('arpm') # number of paths to",
"projected series for j in range(num_plot): f1 = plt.plot(np.arange(t_ + 1, t_ +",
"invariants scenarios # invariants modeled nonparametrically for i in ind_nonparametric: # project t-copula",
"k + 1 for j in range(j_): if (j not in ind_j_plot_JPM and",
"0, d] = db_garch_sig2.iloc[-1, d] dx_proj[:, 0, d] = x[-1, d] - x[-2,",
"models db_invariants_param = pd.read_csv(path + 'db_invariants_param.csv', index_col=0) # parameters for GARCH(1,1) next step",
"= int(db_estimation_copula['nu'].iloc[0]) rho2_copula = np.array(db_estimation_copula['rho2']).reshape(i_, i_) # parameters for the credit copula db_estimation_credit_copula",
"1), x_proj[j, :, d_plot - 1], lw=1) f, xp = histogram_sp(x_proj[:, -1, d_plot",
"range(m_): # copula scenarios # simulate standardized invariants scenarios for copula epsi_tilde_proj =",
"'db_estimation_nonparametric.csv', index_col=False) p_marginal = db_estimation_nonparametric.values # parameters for estimated Student t copula db_estimation_copula",
"plt.yticks(fontsize=14) add_logo(fig1, set_fig_size=False) fig1.tight_layout() # plot projected ratings # select paths with rating",
"fontweight='bold', fontsize=20) plt.yticks(np.arange(10), fontsize=14) ax[0].set_yticklabels(['', 'AAA', 'AA', 'A', 'BBB', 'BB', 'B', 'CCC', 'D',",
"rating changes ind_j_plot_GE = np.zeros(1) ind_j_plot_GE[0] = 0 k = 0 while k",
"risk drivers modeled as AR(1) elif db_invariants_nextstep.iloc[0, d] == 'AR(1)': b_ar1 = db_invariants_param.loc['b'][d]",
"fontweight='bold', fontsize=20) plt.yticks(np.arange(10), fontsize=14) ax[1].set_yticklabels(['', 'AAA', 'AA', 'A', 'BBB', 'BB', 'B', 'CCC', 'D',",
"1 for j in range(j_): if (j not in ind_j_plot_JPM and ratings_proj[j, -1,",
"1), db_riskdrivers_series.iloc[:, d_plot - 1], lw=1) # plot projected series for j in",
"d] = c_garch[d] + \\ b_garch[d] * sig2_garch[:, m - 1, d] +",
"investment horizon out = pd.DataFrame({'j_': pd.Series(j_), 't_hor': pd.Series(t_hor)}) out.to_csv(path + 'db_projection_tools.csv', index=None) del",
"nu_copula = int(db_estimation_copula['nu'].iloc[0]) rho2_copula = np.array(db_estimation_copula['rho2']).reshape(i_, i_) # parameters for the credit copula",
"changes ind_j_plot_GE = np.zeros(1) ind_j_plot_GE[0] = 0 k = 0 while k <",
"db_invariants_param.loc['a'].values b_garch = db_invariants_param.loc['b'].values c_garch = db_invariants_param.loc['c'].values mu_garch = db_invariants_param.loc['mu'].values # risk drivers",
"i], nu_copula) mu_marg = db_estimation_parametric.loc['mu', str(i)] sig2_marg = db_estimation_parametric.loc['sig2', str(i)] nu_marg = db_estimation_parametric.loc['nu',",
"# + path = '../../../databases/temporary-databases/' # Risk drivers identification # realizations of risk",
"# additional information db_riskdrivers_tools = pd.read_csv(path + 'db_riskdrivers_tools.csv') d_ = int(db_riskdrivers_tools.d_.dropna()) d_credit =",
"invariants # + epsi_proj = np.zeros((j_, m_, i_)) for m in range(m_): #",
"mu_garch = db_invariants_param.loc['mu'].values # risk drivers at time t_now are the starting values",
"# language: python # name: python3 # --- # # s_checklist_scenariobased_step04 [<img src=\"https://www.arpm.co/lab/icons/icon_permalink.png\"",
"= [d for d in range(d_) if db_invariants_nextstep.iloc[0, d] == 'GARCH(1,1)'] for d",
"del out # projected credit ratings out = pd.DataFrame({'GE': ratings_proj[:, :, 0].reshape((j_ *",
"## [Step 3](https://www.arpm.co/lab/redirect.php?permalink=s_checklist_scenariobased_step04-implementation-step03): Projection of risk drivers # + x_proj = np.zeros((j_, m_",
"if (j not in ind_j_plot_JPM and ratings_proj[j, -1, 1] != ratings_proj[k, -1, 1]):",
"and ratings_proj[j, -1, 0] != ratings_proj[k, -1, 0]): ind_j_plot_GE = np.append(ind_j_plot_GE, j) break",
"t_ + 1 + m_ + 1), x_proj[j, :, d_plot - 1], lw=1)",
"+ 'db_riskdrivers_series.csv', index_col=0, parse_dates=True) x = db_riskdrivers_series.values risk_drivers_names = db_riskdrivers_series.columns # additional information",
"in ind_nonparametric: # project t-copula standardized invariants scenarios u_proj = tstu.cdf(epsi_tilde_proj[:, i], nu_copula)",
"np.zeros((j_, m_ + 1, d_)) sig2_garch = np.zeros((j_, m_ + 1, d_)) a_garch",
"- x[-2, d] # project daily scenarios for m in range(1, m_ +",
"1, d] + dx_proj[:, m, d] # risk drivers modeled as AR(1) elif",
"1),)) for d in range(d_)}) out = out[list(risk_drivers_names[:d_].values)] out.to_csv(path + 'db_projection_riskdrivers.csv', index=None) del",
"invariants modeled parametrically (estimated as Student t distributed) for i in ind_parametric: #",
"* (m_ + 1),))}) out.to_csv(path + 'db_projection_ratings.csv', index=None) del out # number of",
"number of paths to plot num_plot = min(j_, 20) # market risk driver",
"f, xp = histogram_sp(x_proj[:, -1, d_plot - 1], k_=10 * np.log(j_)) f1 =",
"facecolor=[.3, .3, .3], edgecolor='k') plt.title('Projected path: ' + risk_drivers_names[d_plot - 1], fontweight='bold', fontsize=20)",
"simulate_t(np.zeros(i_), rho2_copula, nu_copula, j_) # generate invariants scenarios # invariants modeled nonparametrically for",
"--- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light",
"'JPM': ratings_proj[:, :, 1].reshape((j_ * (m_ + 1),))}) out.to_csv(path + 'db_projection_ratings.csv', index=None) del",
"b_ar1 = db_invariants_param.loc['b'][d] x_proj[:, m, d] = b_ar1 * x_proj[:, m - 1,",
"fig1.tight_layout() # plot projected ratings # select paths with rating changes ind_j_plot_GE =",
"distributed) for i in ind_parametric: # project t-copula standardized invariants scenarios u_proj =",
"Projection of risk drivers # + x_proj = np.zeros((j_, m_ + 1, d_))",
"t_now are the starting values for all scenarios x_proj[:, 0, :] = db_riskdrivers_series.iloc[-1,",
"Quest for invariance # values of invariants db_invariants_series = pd.read_csv(path + 'db_invariants_series.csv', index_col=0,",
"figsize=(1280.0 / 72.0, 720.0 / 72.0), dpi=72.0) plt.sca(ax[0]) for j in ind_j_plot_GE: f5",
"from scipy.stats import t as tstu import matplotlib.pyplot as plt from pandas.plotting import",
"np.append(ind_j_plot_GE, j) break ind_j_plot_JPM = np.zeros(1) ind_j_plot_JPM[0] = 0 k = 0 while",
"generate invariants scenarios # invariants modeled nonparametrically for i in ind_nonparametric: # project",
"m - 1, d] + epsi_proj[:, m - 1, d] # - #",
"# risk drivers modeled as AR(1) elif db_invariants_nextstep.iloc[0, d] == 'AR(1)': b_ar1 =",
"pd.read_csv(path + 'db_invariants_param.csv', index_col=0) # parameters for GARCH(1,1) next step models db_garch_sig2 =",
"rating JPM', fontweight='bold', fontsize=20) plt.yticks(np.arange(10), fontsize=14) ax[1].set_yticklabels(['', 'AAA', 'AA', 'A', 'BBB', 'BB', 'B',",
"parameters for invariants modeled using Student t distribution db_estimation_parametric = pd.read_csv(path + 'db_estimation_parametric.csv',",
"[Step 4](https://www.arpm.co/lab/redirect.php?permalink=s_checklist_scenariobased_step04-implementation-step04): Projection of credit ratings # + # compute the daily credit",
"= db_riskdrivers_series.values risk_drivers_names = db_riskdrivers_series.columns # additional information db_riskdrivers_tools = pd.read_csv(path + 'db_riskdrivers_tools.csv')",
"1 + d_implvol, n_stocks + 1 + d_implvol + i_bonds) # invariants modeled",
"plt.title('Projected rating GE', fontweight='bold', fontsize=20) plt.yticks(np.arange(10), fontsize=14) ax[0].set_yticklabels(['', 'AAA', 'AA', 'A', 'BBB', 'BB',",
"= plt.barh(xp, f / 10, height=xp[1] - xp[0], left=t_ + 1 + m_,",
"# project ratings ratings_proj = simulate_markov_chain_multiv(ratings_tnow, p_credit_daily, m_, rho2=rho2_credit, nu=nu_credit, j_=j_) # -",
"np.array(db_riskdrivers_tools.ratings_tnow.dropna()) t_now = np.datetime64(db_riskdrivers_tools.t_now[0], 'D') # Quest for invariance # values of invariants",
"+ 1, c_ + 1) # Estimation # parameters for invariants modeled using",
"pd.read_csv(path + 'db_riskdrivers_tools.csv') d_ = int(db_riskdrivers_tools.d_.dropna()) d_credit = int(db_riskdrivers_tools.d_credit.dropna()) n_stocks = int(db_riskdrivers_tools.n_stocks.dropna()) d_implvol",
"1) plt.title('Projected rating GE', fontweight='bold', fontsize=20) plt.yticks(np.arange(10), fontsize=14) ax[0].set_yticklabels(['', 'AAA', 'AA', 'A', 'BBB',",
"+ 1), ratings_proj[int(j), :, 1] + 1) plt.title('Projected rating JPM', fontweight='bold', fontsize=20) plt.yticks(np.arange(10),",
"scenario probabilities p = np.ones(j_) / j_ # invariants modeled parametrically ind_parametric =",
"* sig2_garch[:, m - 1, d] + \\ a_garch[d] * (dx_proj[:, m -",
"(m_ + 1),))}) out.to_csv(path + 'db_projection_ratings.csv', index=None) del out # number of scenarios",
"range(j_): if (j not in ind_j_plot_JPM and ratings_proj[j, -1, 1] != ratings_proj[k, -1,",
"credit transition matrix p_credit = pd.read_csv(path + 'db_invariants_p_credit.csv').values.reshape(c_ + 1, c_ + 1)",
"u_proj = tstu.cdf(epsi_tilde_proj[:, i], nu_copula) mu_marg = db_estimation_parametric.loc['mu', str(i)] sig2_marg = db_estimation_parametric.loc['sig2', str(i)]",
"# compute the daily credit transition matrix p_credit_daily = project_trans_matrix(p_credit, 1 / 252)",
"for d in range(d_) if db_invariants_nextstep.iloc[0, d] == 'GARCH(1,1)'] for d in d_garch:",
"d] - x[-2, d] # project daily scenarios for m in range(1, m_",
"matplotlib.pyplot as plt from pandas.plotting import register_matplotlib_converters register_matplotlib_converters() from arpym.statistics import quantile_sp, simulate_markov_chain_multiv,",
"= list(set(range(i_)) - set(ind_parametric)) # ## [Step 2](https://www.arpm.co/lab/redirect.php?permalink=s_checklist_scenariobased_step04-implementation-step02): Projection of invariants # +",
"'db_projection_tools.csv', index=None) del out # projected scenario probabilities out = pd.DataFrame({'p': pd.Series(p)}) out.to_csv(path",
"range(d_)}) out = out[list(risk_drivers_names[:d_].values)] out.to_csv(path + 'db_projection_riskdrivers.csv', index=None) del out # projected credit",
"d] + \\ a_garch[d] * (dx_proj[:, m - 1, d] - mu_garch[d]) **",
"plot projected ratings # select paths with rating changes ind_j_plot_GE = np.zeros(1) ind_j_plot_GE[0]",
"for invariants modeled using Student t distribution db_estimation_parametric = pd.read_csv(path + 'db_estimation_parametric.csv', index_col=0)",
"index_col=0) # estimated probabilities for nonparametric distributions db_estimation_nonparametric = pd.read_csv(path + 'db_estimation_nonparametric.csv', index_col=False)",
"+ d_implvol + i_bonds) # invariants modeled nonparametrically ind_nonparametric = list(set(range(i_)) - set(ind_parametric))",
"credit copula db_estimation_credit_copula = pd.read_csv(path + 'db_estimation_credit_copula.csv') rho2_credit = db_estimation_credit_copula.rho2_credit.values.reshape(2, 2) nu_credit =",
"= int(db_riskdrivers_tools.d_implvol.dropna()) n_bonds = int(db_riskdrivers_tools.n_bonds.dropna()) i_bonds = n_bonds * 4 # 4 NS",
"x_proj[:, m - 1, d] + dx_proj[:, m, d] # risk drivers modeled",
"i] = quantile_sp(u_proj, epsi[:, i], p_marginal[:, i]) # invariants modeled parametrically (estimated as",
"# text_representation: # extension: .py # format_name: light # format_version: '1.4' # jupytext_version:",
"epsi_proj[:, m, i] = mu_marg + np.sqrt(sig2_marg) * tstu.ppf(u_proj, nu_marg) # - #",
"c_garch[d] + \\ b_garch[d] * sig2_garch[:, m - 1, d] + \\ a_garch[d]",
"= db_estimation_parametric.loc['sig2', str(i)] nu_marg = db_estimation_parametric.loc['nu', str(i)] epsi_proj[:, m, i] = mu_marg +",
"+ 1, t_ + 1 + m_ + 1), x_proj[j, :, d_plot -",
"fontsize=14) ax[1].set_yticklabels(['', 'AAA', 'AA', 'A', 'BBB', 'BB', 'B', 'CCC', 'D', '']) plt.gca().invert_yaxis() add_logo(fig2,",
"= 5000 # number of scenarios d_plot = 97 # projected risk driver",
"1, d] # risk drivers modeled as GARCH(1,1) elif db_invariants_nextstep.iloc[0, d] == 'GARCH(1,1)':",
"'Random walk': x_proj[:, m, d] = x_proj[:, m - 1, d] + epsi_proj[:,",
"\\ a_garch[d] * (dx_proj[:, m - 1, d] - mu_garch[d]) ** 2 dx_proj[:,",
"standardized invariants scenarios u_proj = tstu.cdf(epsi_tilde_proj[:, i], nu_copula) mu_marg = db_estimation_parametric.loc['mu', str(i)] sig2_marg",
"with rating changes ind_j_plot_GE = np.zeros(1) ind_j_plot_GE[0] = 0 k = 0 while",
"-1, 1]): ind_j_plot_JPM = np.append(ind_j_plot_JPM, j) break fig2, ax = plt.subplots(2, 1, figsize=(1280.0",
"plt.plot(np.arange(t_ + 1), db_riskdrivers_series.iloc[:, d_plot - 1], lw=1) # plot projected series for",
"t as tstu import matplotlib.pyplot as plt from pandas.plotting import register_matplotlib_converters register_matplotlib_converters() from",
"number of projection steps and scenario probabilities # number of monitoring times m_",
":] # initialize parameters for GARCH(1,1) projection d_garch = [d for d in",
"index_col=0, parse_dates=True) x = db_riskdrivers_series.values risk_drivers_names = db_riskdrivers_series.columns # additional information db_riskdrivers_tools =",
"t_now = np.datetime64(db_riskdrivers_tools.t_now[0], 'D') # Quest for invariance # values of invariants db_invariants_series",
"copula db_estimation_credit_copula = pd.read_csv(path + 'db_estimation_credit_copula.csv') rho2_credit = db_estimation_credit_copula.rho2_credit.values.reshape(2, 2) nu_credit = db_estimation_credit_copula.nu_credit[0]",
"drivers up to and including time t_now db_riskdrivers_series = pd.read_csv(path + 'db_riskdrivers_series.csv', index_col=0,",
"risk driver to plot # ## [Step 0](https://www.arpm.co/lab/redirect.php?permalink=s_checklist_scenariobased_step04-implementation-step00): Load data # + path",
"k + 1 for j in range(j_): if (j not in ind_j_plot_GE and",
"nu_copula) mu_marg = db_estimation_parametric.loc['mu', str(i)] sig2_marg = db_estimation_parametric.loc['sig2', str(i)] nu_marg = db_estimation_parametric.loc['nu', str(i)]",
"jupytext_version: 1.1.5 # kernelspec: # display_name: Python 3 # language: python # name:",
"\\ simulate_t, project_trans_matrix from arpym.tools import histogram_sp, add_logo # - # ## [Input",
"j in range(j_): if (j not in ind_j_plot_JPM and ratings_proj[j, -1, 1] !=",
"1](https://www.arpm.co/lab/redirect.php?permalink=s_checklist_scenariobased_step04-implementation-step01): Determine number of projection steps and scenario probabilities # number of monitoring",
"str(i)] epsi_proj[:, m, i] = mu_marg + np.sqrt(sig2_marg) * tstu.ppf(u_proj, nu_marg) # -",
"j in range(num_plot): f1 = plt.plot(np.arange(t_ + 1, t_ + 1 + m_",
"compute the daily credit transition matrix p_credit_daily = project_trans_matrix(p_credit, 1 / 252) #",
"np.zeros(1) ind_j_plot_JPM[0] = 0 k = 0 while k < num_plot: k =",
"if db_invariants_nextstep.iloc[0, d] == 'GARCH(1,1)'] for d in d_garch: sig2_garch[:, 0, d] =",
"steps and scenario probabilities # number of monitoring times m_ = np.busday_count(t_now, t_hor)",
"series f1 = plt.plot(np.arange(t_ + 1), db_riskdrivers_series.iloc[:, d_plot - 1], lw=1) # plot",
"np.datetime64('2012-10-26') # the future investment horizon j_ = 5000 # number of scenarios",
"parse_dates=True) # estimated annual credit transition matrix p_credit = pd.read_csv(path + 'db_invariants_p_credit.csv').values.reshape(c_ +",
"db_garch_sig2.iloc[-1, d] dx_proj[:, 0, d] = x[-1, d] - x[-2, d] # project",
"project_trans_matrix(p_credit, 1 / 252) # project ratings ratings_proj = simulate_markov_chain_multiv(ratings_tnow, p_credit_daily, m_, rho2=rho2_credit,",
"t_now db_riskdrivers_series = pd.read_csv(path + 'db_riskdrivers_series.csv', index_col=0, parse_dates=True) x = db_riskdrivers_series.values risk_drivers_names =",
"- 1, d] # risk drivers modeled as GARCH(1,1) elif db_invariants_nextstep.iloc[0, d] ==",
"- # ## Plots # + plt.style.use('arpm') # number of paths to plot",
"= x_proj[:, m - 1, d] + epsi_proj[:, m - 1, d] #",
"# ## Plots # + plt.style.use('arpm') # number of paths to plot num_plot",
"import register_matplotlib_converters register_matplotlib_converters() from arpym.statistics import quantile_sp, simulate_markov_chain_multiv, \\ simulate_t, project_trans_matrix from arpym.tools",
"- # ## [Input parameters](https://www.arpm.co/lab/redirect.php?permalink=s_checklist_scenariobased_step04-parameters) # t_now is 31-Aug-2012. Set t_hor>t_now t_hor =",
"of paths to plot num_plot = min(j_, 20) # market risk driver path",
"1, d_)) dx_proj = np.zeros((j_, m_ + 1, d_)) sig2_garch = np.zeros((j_, m_",
"of invariants # + epsi_proj = np.zeros((j_, m_, i_)) for m in range(m_):",
"matrix p_credit = pd.read_csv(path + 'db_invariants_p_credit.csv').values.reshape(c_ + 1, c_ + 1) # Estimation",
"np.zeros(1) ind_j_plot_GE[0] = 0 k = 0 while k < num_plot: k =",
"dx_proj, sig2_garch # projected risk drivers out = pd.DataFrame({risk_drivers_names[d]: x_proj[:, :, d].reshape((j_ *",
"- 1, d] - mu_garch[d]) ** 2 dx_proj[:, m, d] = mu_garch[d] +",
"+ 'db_invariants_series.csv', index_col=0, parse_dates=True) epsi = db_invariants_series.values t_, i_ = np.shape(epsi) # next",
"db_estimation_parametric = pd.read_csv(path + 'db_estimation_parametric.csv', index_col=0) # estimated probabilities for nonparametric distributions db_estimation_nonparametric",
"modeled parametrically ind_parametric = np.arange(n_stocks + 1 + d_implvol, n_stocks + 1 +",
"4 NS parameters x n_bonds c_ = int(db_riskdrivers_tools.c_.dropna()) ratings_tnow = np.array(db_riskdrivers_tools.ratings_tnow.dropna()) t_now =",
"future investment horizon out = pd.DataFrame({'j_': pd.Series(j_), 't_hor': pd.Series(t_hor)}) out.to_csv(path + 'db_projection_tools.csv', index=None)",
"invariance # values of invariants db_invariants_series = pd.read_csv(path + 'db_invariants_series.csv', index_col=0, parse_dates=True) epsi",
"1, d] + epsi_proj[:, m - 1, d] # risk drivers modeled as",
"ratings_proj[j, -1, 0] != ratings_proj[k, -1, 0]): ind_j_plot_GE = np.append(ind_j_plot_GE, j) break ind_j_plot_JPM",
"# + # compute the daily credit transition matrix p_credit_daily = project_trans_matrix(p_credit, 1",
"Projection of invariants # + epsi_proj = np.zeros((j_, m_, i_)) for m in",
"projected risk driver to plot # ## [Step 0](https://www.arpm.co/lab/redirect.php?permalink=s_checklist_scenariobased_step04-implementation-step00): Load data # +",
"1, d] x_proj[:, m, d] = x_proj[:, m - 1, d] + dx_proj[:,",
"d] = mu_garch[d] + \\ np.sqrt(sig2_garch[:, m, d]) * epsi_proj[:, m - 1,",
"modeled nonparametrically ind_nonparametric = list(set(range(i_)) - set(ind_parametric)) # ## [Step 2](https://www.arpm.co/lab/redirect.php?permalink=s_checklist_scenariobased_step04-implementation-step02): Projection of",
"- 1, d] # - # ## [Step 4](https://www.arpm.co/lab/redirect.php?permalink=s_checklist_scenariobased_step04-implementation-step04): Projection of credit ratings",
"+ 'db_estimation_nonparametric.csv', index_col=False) p_marginal = db_estimation_nonparametric.values # parameters for estimated Student t copula",
"4](https://www.arpm.co/lab/redirect.php?permalink=s_checklist_scenariobased_step04-implementation-step04): Projection of credit ratings # + # compute the daily credit transition",
"1, d] - mu_garch[d]) ** 2 dx_proj[:, m, d] = mu_garch[d] + \\",
"path: ' + risk_drivers_names[d_plot - 1], fontweight='bold', fontsize=20) plt.xlabel('t (days)', fontsize=17) plt.xticks(fontsize=14) plt.yticks(fontsize=14)",
"For details, see [here](https://www.arpm.co/lab/redirect.php?permalink=ex-vue-4-copmarg). # + import numpy as np import pandas as",
"dpi=72.0) # plot historical series f1 = plt.plot(np.arange(t_ + 1), db_riskdrivers_series.iloc[:, d_plot -",
"= np.zeros((j_, m_ + 1, d_)) sig2_garch = np.zeros((j_, m_ + 1, d_))",
"1, d_)) a_garch = db_invariants_param.loc['a'].values b_garch = db_invariants_param.loc['b'].values c_garch = db_invariants_param.loc['c'].values mu_garch =",
"AR(1) elif db_invariants_nextstep.iloc[0, d] == 'AR(1)': b_ar1 = db_invariants_param.loc['b'][d] x_proj[:, m, d] =",
"# format_version: '1.4' # jupytext_version: 1.1.5 # kernelspec: # display_name: Python 3 #",
"display_name: Python 3 # language: python # name: python3 # --- # #",
"# - # ## [Step 1](https://www.arpm.co/lab/redirect.php?permalink=s_checklist_scenariobased_step04-implementation-step01): Determine number of projection steps and scenario",
"GARCH(1,1) projection d_garch = [d for d in range(d_) if db_invariants_nextstep.iloc[0, d] ==",
"plt.figure(figsize=(1280.0 / 72.0, 720.0 / 72.0), dpi=72.0) # plot historical series f1 =",
"project t-copula standardized invariants scenarios u_proj = tstu.cdf(epsi_tilde_proj[:, i], nu_copula) mu_marg = db_estimation_parametric.loc['mu',",
"for j in range(num_plot): f1 = plt.plot(np.arange(t_ + 1, t_ + 1 +",
"= db_garch_sig2.iloc[-1, d] dx_proj[:, 0, d] = x[-1, d] - x[-2, d] #",
"invariants modeled using Student t distribution db_estimation_parametric = pd.read_csv(path + 'db_estimation_parametric.csv', index_col=0) #",
"Projection of credit ratings # + # compute the daily credit transition matrix",
"\\ b_garch[d] * sig2_garch[:, m - 1, d] + \\ a_garch[d] * (dx_proj[:,",
"+ 'db_projection_riskdrivers.csv', index=None) del out # projected credit ratings out = pd.DataFrame({'GE': ratings_proj[:,",
"ratings_proj[k, -1, 0]): ind_j_plot_GE = np.append(ind_j_plot_GE, j) break ind_j_plot_JPM = np.zeros(1) ind_j_plot_JPM[0] =",
"db_invariants_series = pd.read_csv(path + 'db_invariants_series.csv', index_col=0, parse_dates=True) epsi = db_invariants_series.values t_, i_ =",
"[d for d in range(d_) if db_invariants_nextstep.iloc[0, d] == 'GARCH(1,1)'] for d in",
"next step models db_garch_sig2 = pd.read_csv(path + 'db_garch_sig2.csv', index_col=0, parse_dates=True) # estimated annual",
"Estimation # parameters for invariants modeled using Student t distribution db_estimation_parametric = pd.read_csv(path",
"elif db_invariants_nextstep.iloc[0, d] == 'GARCH(1,1)': sig2_garch[:, m, d] = c_garch[d] + \\ b_garch[d]",
"+ # delete big files del dx_proj, sig2_garch # projected risk drivers out",
"ind_j_plot_JPM and ratings_proj[j, -1, 1] != ratings_proj[k, -1, 1]): ind_j_plot_JPM = np.append(ind_j_plot_JPM, j)",
"out[list(risk_drivers_names[:d_].values)] out.to_csv(path + 'db_projection_riskdrivers.csv', index=None) del out # projected credit ratings out =",
"nonparametrically for i in ind_nonparametric: # project t-copula standardized invariants scenarios u_proj =",
"plt.xticks(fontsize=14) plt.yticks(fontsize=14) add_logo(fig1, set_fig_size=False) fig1.tight_layout() # plot projected ratings # select paths with",
"str(i)] sig2_marg = db_estimation_parametric.loc['sig2', str(i)] nu_marg = db_estimation_parametric.loc['nu', str(i)] epsi_proj[:, m, i] =",
"style=\"display: inline;\">](https://www.arpm.co/lab/redirect.php?code=s_checklist_scenariobased_step04&codeLang=Python) # For details, see [here](https://www.arpm.co/lab/redirect.php?permalink=ex-vue-4-copmarg). # + import numpy as np",
"+ 'db_garch_sig2.csv', index_col=0, parse_dates=True) # estimated annual credit transition matrix p_credit = pd.read_csv(path",
"fig1 = plt.figure(figsize=(1280.0 / 72.0, 720.0 / 72.0), dpi=72.0) # plot historical series",
"## [Input parameters](https://www.arpm.co/lab/redirect.php?permalink=s_checklist_scenariobased_step04-parameters) # t_now is 31-Aug-2012. Set t_hor>t_now t_hor = np.datetime64('2012-10-26') #",
"- 1, d] + \\ a_garch[d] * (dx_proj[:, m - 1, d] -",
"# display_name: Python 3 # language: python # name: python3 # --- #",
"# values of invariants db_invariants_series = pd.read_csv(path + 'db_invariants_series.csv', index_col=0, parse_dates=True) epsi =",
":, 0] + 1) plt.title('Projected rating GE', fontweight='bold', fontsize=20) plt.yticks(np.arange(10), fontsize=14) ax[0].set_yticklabels(['', 'AAA',",
"matrix p_credit_daily = project_trans_matrix(p_credit, 1 / 252) # project ratings ratings_proj = simulate_markov_chain_multiv(ratings_tnow,",
"credit transition matrix p_credit_daily = project_trans_matrix(p_credit, 1 / 252) # project ratings ratings_proj",
"Load data # + path = '../../../databases/temporary-databases/' # Risk drivers identification # realizations",
"1 for j in range(j_): if (j not in ind_j_plot_GE and ratings_proj[j, -1,",
"[Input parameters](https://www.arpm.co/lab/redirect.php?permalink=s_checklist_scenariobased_step04-parameters) # t_now is 31-Aug-2012. Set t_hor>t_now t_hor = np.datetime64('2012-10-26') # the",
"all scenarios x_proj[:, 0, :] = db_riskdrivers_series.iloc[-1, :] # initialize parameters for GARCH(1,1)",
"plt.gca().invert_yaxis() plt.sca(ax[1]) for j in ind_j_plot_JPM: plt.plot(np.arange(m_ + 1), ratings_proj[int(j), :, 1] +",
"d] - mu_garch[d]) ** 2 dx_proj[:, m, d] = mu_garch[d] + \\ np.sqrt(sig2_garch[:,",
"drivers modeled as random walk if db_invariants_nextstep.iloc[0, d] == 'Random walk': x_proj[:, m,",
"d] + dx_proj[:, m, d] # risk drivers modeled as AR(1) elif db_invariants_nextstep.iloc[0,",
"parse_dates=True) epsi = db_invariants_series.values t_, i_ = np.shape(epsi) # next step models db_invariants_nextstep",
"d] = b_ar1 * x_proj[:, m - 1, d] + epsi_proj[:, m -",
"* 4 # 4 NS parameters x n_bonds c_ = int(db_riskdrivers_tools.c_.dropna()) ratings_tnow =",
"p_credit = pd.read_csv(path + 'db_invariants_p_credit.csv').values.reshape(c_ + 1, c_ + 1) # Estimation #",
"import matplotlib.pyplot as plt from pandas.plotting import register_matplotlib_converters register_matplotlib_converters() from arpym.statistics import quantile_sp,",
"'db_invariants_p_credit.csv').values.reshape(c_ + 1, c_ + 1) # Estimation # parameters for invariants modeled",
"i_) # parameters for the credit copula db_estimation_credit_copula = pd.read_csv(path + 'db_estimation_credit_copula.csv') rho2_credit",
"text_representation: # extension: .py # format_name: light # format_version: '1.4' # jupytext_version: 1.1.5",
"number of monitoring times m_ = np.busday_count(t_now, t_hor) # projection scenario probabilities p",
"out # number of scenarios and future investment horizon out = pd.DataFrame({'j_': pd.Series(j_),",
"sig2_garch[:, m, d] = c_garch[d] + \\ b_garch[d] * sig2_garch[:, m - 1,",
"xp[0], left=t_ + 1 + m_, facecolor=[.3, .3, .3], edgecolor='k') plt.title('Projected path: '",
"fontsize=17) plt.xticks(fontsize=14) plt.yticks(fontsize=14) add_logo(fig1, set_fig_size=False) fig1.tight_layout() # plot projected ratings # select paths",
"f1 = plt.plot(np.arange(t_ + 1), db_riskdrivers_series.iloc[:, d_plot - 1], lw=1) # plot projected",
"97 # projected risk driver to plot # ## [Step 0](https://www.arpm.co/lab/redirect.php?permalink=s_checklist_scenariobased_step04-implementation-step00): Load data",
"d_plot = 97 # projected risk driver to plot # ## [Step 0](https://www.arpm.co/lab/redirect.php?permalink=s_checklist_scenariobased_step04-implementation-step00):",
"m_ + 1), x_proj[j, :, d_plot - 1], lw=1) f, xp = histogram_sp(x_proj[:,",
"# 4 NS parameters x n_bonds c_ = int(db_riskdrivers_tools.c_.dropna()) ratings_tnow = np.array(db_riskdrivers_tools.ratings_tnow.dropna()) t_now",
"modeled using Student t distribution db_estimation_parametric = pd.read_csv(path + 'db_estimation_parametric.csv', index_col=0) # estimated",
"# --- # # s_checklist_scenariobased_step04 [<img src=\"https://www.arpm.co/lab/icons/icon_permalink.png\" width=30 height=30 style=\"display: inline;\">](https://www.arpm.co/lab/redirect.php?code=s_checklist_scenariobased_step04&codeLang=Python) # For",
"Plots # + plt.style.use('arpm') # number of paths to plot num_plot = min(j_,",
"Save databases # + # delete big files del dx_proj, sig2_garch # projected",
".3], edgecolor='k') plt.title('Projected path: ' + risk_drivers_names[d_plot - 1], fontweight='bold', fontsize=20) plt.xlabel('t (days)',",
"NS parameters x n_bonds c_ = int(db_riskdrivers_tools.c_.dropna()) ratings_tnow = np.array(db_riskdrivers_tools.ratings_tnow.dropna()) t_now = np.datetime64(db_riskdrivers_tools.t_now[0],",
"m_, facecolor=[.3, .3, .3], edgecolor='k') plt.title('Projected path: ' + risk_drivers_names[d_plot - 1], fontweight='bold',",
"# - # ## [Step 5](https://www.arpm.co/lab/redirect.php?permalink=s_checklist_scenariobased_step04-implementation-step05): Save databases # + # delete big",
"(estimated as Student t distributed) for i in ind_parametric: # project t-copula standardized",
"# + epsi_proj = np.zeros((j_, m_, i_)) for m in range(m_): # copula",
"= 0 k = 0 while k < num_plot: k = k +",
"height=30 style=\"display: inline;\">](https://www.arpm.co/lab/redirect.php?code=s_checklist_scenariobased_step04&codeLang=Python) # For details, see [here](https://www.arpm.co/lab/redirect.php?permalink=ex-vue-4-copmarg). # + import numpy as",
"times m_ = np.busday_count(t_now, t_hor) # projection scenario probabilities p = np.ones(j_) /",
"# jupytext_version: 1.1.5 # kernelspec: # display_name: Python 3 # language: python #",
"# project daily scenarios for m in range(1, m_ + 1): for d",
"histogram_sp, add_logo # - # ## [Input parameters](https://www.arpm.co/lab/redirect.php?permalink=s_checklist_scenariobased_step04-parameters) # t_now is 31-Aug-2012. Set",
"standardized invariants scenarios for copula epsi_tilde_proj = simulate_t(np.zeros(i_), rho2_copula, nu_copula, j_) # generate",
"time t_now are the starting values for all scenarios x_proj[:, 0, :] =",
"= db_invariants_param.loc['b'][d] x_proj[:, m, d] = b_ar1 * x_proj[:, m - 1, d]",
"p_credit_daily = project_trans_matrix(p_credit, 1 / 252) # project ratings ratings_proj = simulate_markov_chain_multiv(ratings_tnow, p_credit_daily,",
"width=30 height=30 style=\"display: inline;\">](https://www.arpm.co/lab/redirect.php?code=s_checklist_scenariobased_step04&codeLang=Python) # For details, see [here](https://www.arpm.co/lab/redirect.php?permalink=ex-vue-4-copmarg). # + import numpy",
"n_bonds = int(db_riskdrivers_tools.n_bonds.dropna()) i_bonds = n_bonds * 4 # 4 NS parameters x",
"out # projected credit ratings out = pd.DataFrame({'GE': ratings_proj[:, :, 0].reshape((j_ * (m_",
"72.0, 720.0 / 72.0), dpi=72.0) # plot historical series f1 = plt.plot(np.arange(t_ +",
"= histogram_sp(x_proj[:, -1, d_plot - 1], k_=10 * np.log(j_)) f1 = plt.barh(xp, f",
"scenarios u_proj = tstu.cdf(epsi_tilde_proj[:, i], nu_copula) mu_marg = db_estimation_parametric.loc['mu', str(i)] sig2_marg = db_estimation_parametric.loc['sig2',",
"= 97 # projected risk driver to plot # ## [Step 0](https://www.arpm.co/lab/redirect.php?permalink=s_checklist_scenariobased_step04-implementation-step00): Load",
"dx_proj = np.zeros((j_, m_ + 1, d_)) sig2_garch = np.zeros((j_, m_ + 1,",
"step models db_invariants_nextstep = pd.read_csv(path + 'db_invariants_nextstep.csv') # parameters for next step models",
"n_bonds c_ = int(db_riskdrivers_tools.c_.dropna()) ratings_tnow = np.array(db_riskdrivers_tools.ratings_tnow.dropna()) t_now = np.datetime64(db_riskdrivers_tools.t_now[0], 'D') # Quest",
"+ epsi_proj[:, m - 1, d] # - # ## [Step 4](https://www.arpm.co/lab/redirect.php?permalink=s_checklist_scenariobased_step04-implementation-step04): Projection",
"= tstu.cdf(epsi_tilde_proj[:, i], nu_copula) mu_marg = db_estimation_parametric.loc['mu', str(i)] sig2_marg = db_estimation_parametric.loc['sig2', str(i)] nu_marg",
"scenarios and future investment horizon out = pd.DataFrame({'j_': pd.Series(j_), 't_hor': pd.Series(t_hor)}) out.to_csv(path +",
"= np.zeros(1) ind_j_plot_GE[0] = 0 k = 0 while k < num_plot: k",
"plt.subplots(2, 1, figsize=(1280.0 / 72.0, 720.0 / 72.0), dpi=72.0) plt.sca(ax[0]) for j in",
"'']) plt.gca().invert_yaxis() plt.sca(ax[1]) for j in ind_j_plot_JPM: plt.plot(np.arange(m_ + 1), ratings_proj[int(j), :, 1]",
"for invariance # values of invariants db_invariants_series = pd.read_csv(path + 'db_invariants_series.csv', index_col=0, parse_dates=True)",
"0 k = 0 while k < num_plot: k = k + 1",
"+ \\ a_garch[d] * (dx_proj[:, m - 1, d] - mu_garch[d]) ** 2",
"+ m_ + 1), x_proj[j, :, d_plot - 1], lw=1) f, xp =",
"python3 # --- # # s_checklist_scenariobased_step04 [<img src=\"https://www.arpm.co/lab/icons/icon_permalink.png\" width=30 height=30 style=\"display: inline;\">](https://www.arpm.co/lab/redirect.php?code=s_checklist_scenariobased_step04&codeLang=Python) #",
"np.sqrt(sig2_marg) * tstu.ppf(u_proj, nu_marg) # - # ## [Step 3](https://www.arpm.co/lab/redirect.php?permalink=s_checklist_scenariobased_step04-implementation-step03): Projection of risk",
"* np.log(j_)) f1 = plt.barh(xp, f / 10, height=xp[1] - xp[0], left=t_ +",
"np.zeros((j_, m_ + 1, d_)) dx_proj = np.zeros((j_, m_ + 1, d_)) sig2_garch",
"= np.arange(n_stocks + 1 + d_implvol, n_stocks + 1 + d_implvol + i_bonds)",
"+ \\ b_garch[d] * sig2_garch[:, m - 1, d] + \\ a_garch[d] *",
"pd.read_csv(path + 'db_invariants_series.csv', index_col=0, parse_dates=True) epsi = db_invariants_series.values t_, i_ = np.shape(epsi) #",
"as Student t distributed) for i in ind_parametric: # project t-copula standardized invariants",
"(dx_proj[:, m - 1, d] - mu_garch[d]) ** 2 dx_proj[:, m, d] =",
"data # + path = '../../../databases/temporary-databases/' # Risk drivers identification # realizations of",
"for i in ind_parametric: # project t-copula standardized invariants scenarios u_proj = tstu.cdf(epsi_tilde_proj[:,",
"i] = mu_marg + np.sqrt(sig2_marg) * tstu.ppf(u_proj, nu_marg) # - # ## [Step",
"d_plot - 1], lw=1) f, xp = histogram_sp(x_proj[:, -1, d_plot - 1], k_=10",
"+ 1 + d_implvol + i_bonds) # invariants modeled nonparametrically ind_nonparametric = list(set(range(i_))",
"= np.ones(j_) / j_ # invariants modeled parametrically ind_parametric = np.arange(n_stocks + 1",
"walk if db_invariants_nextstep.iloc[0, d] == 'Random walk': x_proj[:, m, d] = x_proj[:, m",
"n_stocks = int(db_riskdrivers_tools.n_stocks.dropna()) d_implvol = int(db_riskdrivers_tools.d_implvol.dropna()) n_bonds = int(db_riskdrivers_tools.n_bonds.dropna()) i_bonds = n_bonds *",
"plt.title('Projected rating JPM', fontweight='bold', fontsize=20) plt.yticks(np.arange(10), fontsize=14) ax[1].set_yticklabels(['', 'AAA', 'AA', 'A', 'BBB', 'BB',",
"parameters for next step models db_invariants_param = pd.read_csv(path + 'db_invariants_param.csv', index_col=0) # parameters",
"## [Step 5](https://www.arpm.co/lab/redirect.php?permalink=s_checklist_scenariobased_step04-implementation-step05): Save databases # + # delete big files del dx_proj,",
"np.arange(n_stocks + 1 + d_implvol, n_stocks + 1 + d_implvol + i_bonds) #",
"Student t distribution db_estimation_parametric = pd.read_csv(path + 'db_estimation_parametric.csv', index_col=0) # estimated probabilities for",
"mu_garch[d] + \\ np.sqrt(sig2_garch[:, m, d]) * epsi_proj[:, m - 1, d] x_proj[:,",
"copula epsi_tilde_proj = simulate_t(np.zeros(i_), rho2_copula, nu_copula, j_) # generate invariants scenarios # invariants",
"big files del dx_proj, sig2_garch # projected risk drivers out = pd.DataFrame({risk_drivers_names[d]: x_proj[:,",
"c_ = int(db_riskdrivers_tools.c_.dropna()) ratings_tnow = np.array(db_riskdrivers_tools.ratings_tnow.dropna()) t_now = np.datetime64(db_riskdrivers_tools.t_now[0], 'D') # Quest for",
"p = np.ones(j_) / j_ # invariants modeled parametrically ind_parametric = np.arange(n_stocks +",
"fontsize=20) plt.yticks(np.arange(10), fontsize=14) ax[0].set_yticklabels(['', 'AAA', 'AA', 'A', 'BBB', 'BB', 'B', 'CCC', 'D', ''])",
"driver to plot # ## [Step 0](https://www.arpm.co/lab/redirect.php?permalink=s_checklist_scenariobased_step04-implementation-step00): Load data # + path =",
"distributions db_estimation_nonparametric = pd.read_csv(path + 'db_estimation_nonparametric.csv', index_col=False) p_marginal = db_estimation_nonparametric.values # parameters for",
"x_proj = np.zeros((j_, m_ + 1, d_)) dx_proj = np.zeros((j_, m_ + 1,",
"np import pandas as pd from scipy.stats import t as tstu import matplotlib.pyplot",
"modeled as AR(1) elif db_invariants_nextstep.iloc[0, d] == 'AR(1)': b_ar1 = db_invariants_param.loc['b'][d] x_proj[:, m,",
"sig2_marg = db_estimation_parametric.loc['sig2', str(i)] nu_marg = db_estimation_parametric.loc['nu', str(i)] epsi_proj[:, m, i] = mu_marg",
"db_invariants_nextstep.iloc[0, d] == 'Random walk': x_proj[:, m, d] = x_proj[:, m - 1,",
"# plot projected series for j in range(num_plot): f1 = plt.plot(np.arange(t_ + 1,",
"plt.plot(np.arange(t_ + 1, t_ + 1 + m_ + 1), x_proj[j, :, d_plot",
"in ind_j_plot_GE: f5 = plt.plot(np.arange(m_ + 1), ratings_proj[int(j), :, 0] + 1) plt.title('Projected",
"projection steps and scenario probabilities # number of monitoring times m_ = np.busday_count(t_now,",
"ratings # select paths with rating changes ind_j_plot_GE = np.zeros(1) ind_j_plot_GE[0] = 0",
"# invariants modeled nonparametrically for i in ind_nonparametric: # project t-copula standardized invariants",
"add_logo(fig1, set_fig_size=False) fig1.tight_layout() # plot projected ratings # select paths with rating changes",
"j) break fig2, ax = plt.subplots(2, 1, figsize=(1280.0 / 72.0, 720.0 / 72.0),",
"+ dx_proj[:, m, d] # risk drivers modeled as AR(1) elif db_invariants_nextstep.iloc[0, d]",
"to and including time t_now db_riskdrivers_series = pd.read_csv(path + 'db_riskdrivers_series.csv', index_col=0, parse_dates=True) x",
"to plot # ## [Step 0](https://www.arpm.co/lab/redirect.php?permalink=s_checklist_scenariobased_step04-implementation-step00): Load data # + path = '../../../databases/temporary-databases/'",
"import t as tstu import matplotlib.pyplot as plt from pandas.plotting import register_matplotlib_converters register_matplotlib_converters()",
"lw=1) f, xp = histogram_sp(x_proj[:, -1, d_plot - 1], k_=10 * np.log(j_)) f1",
"tstu.ppf(u_proj, nu_marg) # - # ## [Step 3](https://www.arpm.co/lab/redirect.php?permalink=s_checklist_scenariobased_step04-implementation-step03): Projection of risk drivers #",
"ratings_proj[int(j), :, 1] + 1) plt.title('Projected rating JPM', fontweight='bold', fontsize=20) plt.yticks(np.arange(10), fontsize=14) ax[1].set_yticklabels(['',",
"k < num_plot: k = k + 1 for j in range(j_): if",
"sig2_garch # projected risk drivers out = pd.DataFrame({risk_drivers_names[d]: x_proj[:, :, d].reshape((j_ * (m_",
"1, figsize=(1280.0 / 72.0, 720.0 / 72.0), dpi=72.0) plt.sca(ax[0]) for j in ind_j_plot_GE:",
"i in ind_nonparametric: # project t-copula standardized invariants scenarios u_proj = tstu.cdf(epsi_tilde_proj[:, i],",
"# + import numpy as np import pandas as pd from scipy.stats import",
"1], lw=1) # plot projected series for j in range(num_plot): f1 = plt.plot(np.arange(t_",
"add_logo # - # ## [Input parameters](https://www.arpm.co/lab/redirect.php?permalink=s_checklist_scenariobased_step04-parameters) # t_now is 31-Aug-2012. Set t_hor>t_now",
"of invariants db_invariants_series = pd.read_csv(path + 'db_invariants_series.csv', index_col=0, parse_dates=True) epsi = db_invariants_series.values t_,",
"see [here](https://www.arpm.co/lab/redirect.php?permalink=ex-vue-4-copmarg). # + import numpy as np import pandas as pd from",
"number of scenarios d_plot = 97 # projected risk driver to plot #",
"b_garch[d] * sig2_garch[:, m - 1, d] + \\ a_garch[d] * (dx_proj[:, m",
"as GARCH(1,1) elif db_invariants_nextstep.iloc[0, d] == 'GARCH(1,1)': sig2_garch[:, m, d] = c_garch[d] +",
"invariants modeled nonparametrically ind_nonparametric = list(set(range(i_)) - set(ind_parametric)) # ## [Step 2](https://www.arpm.co/lab/redirect.php?permalink=s_checklist_scenariobased_step04-implementation-step02): Projection",
"= out[list(risk_drivers_names[:d_].values)] out.to_csv(path + 'db_projection_riskdrivers.csv', index=None) del out # projected credit ratings out",
"daily credit transition matrix p_credit_daily = project_trans_matrix(p_credit, 1 / 252) # project ratings",
"paths to plot num_plot = min(j_, 20) # market risk driver path fig1",
"'db_garch_sig2.csv', index_col=0, parse_dates=True) # estimated annual credit transition matrix p_credit = pd.read_csv(path +",
"== 'Random walk': x_proj[:, m, d] = x_proj[:, m - 1, d] +",
"- # ## [Step 3](https://www.arpm.co/lab/redirect.php?permalink=s_checklist_scenariobased_step04-implementation-step03): Projection of risk drivers # + x_proj =",
"'t_hor': pd.Series(t_hor)}) out.to_csv(path + 'db_projection_tools.csv', index=None) del out # projected scenario probabilities out",
"= plt.plot(np.arange(t_ + 1, t_ + 1 + m_ + 1), x_proj[j, :,",
"ind_j_plot_JPM = np.append(ind_j_plot_JPM, j) break fig2, ax = plt.subplots(2, 1, figsize=(1280.0 / 72.0,",
"# risk drivers modeled as GARCH(1,1) elif db_invariants_nextstep.iloc[0, d] == 'GARCH(1,1)': sig2_garch[:, m,",
"2 dx_proj[:, m, d] = mu_garch[d] + \\ np.sqrt(sig2_garch[:, m, d]) * epsi_proj[:,",
"pd.DataFrame({'j_': pd.Series(j_), 't_hor': pd.Series(t_hor)}) out.to_csv(path + 'db_projection_tools.csv', index=None) del out # projected scenario",
"= np.zeros((j_, m_ + 1, d_)) a_garch = db_invariants_param.loc['a'].values b_garch = db_invariants_param.loc['b'].values c_garch",
"simulate_markov_chain_multiv(ratings_tnow, p_credit_daily, m_, rho2=rho2_credit, nu=nu_credit, j_=j_) # - # ## [Step 5](https://www.arpm.co/lab/redirect.php?permalink=s_checklist_scenariobased_step04-implementation-step05): Save",
"time t_now db_riskdrivers_series = pd.read_csv(path + 'db_riskdrivers_series.csv', index_col=0, parse_dates=True) x = db_riskdrivers_series.values risk_drivers_names",
"histogram_sp(x_proj[:, -1, d_plot - 1], k_=10 * np.log(j_)) f1 = plt.barh(xp, f /",
"ind_j_plot_JPM = np.zeros(1) ind_j_plot_JPM[0] = 0 k = 0 while k < num_plot:",
"# projected risk drivers out = pd.DataFrame({risk_drivers_names[d]: x_proj[:, :, d].reshape((j_ * (m_ +",
"num_plot = min(j_, 20) # market risk driver path fig1 = plt.figure(figsize=(1280.0 /",
"d] == 'Random walk': x_proj[:, m, d] = x_proj[:, m - 1, d]",
"1] != ratings_proj[k, -1, 1]): ind_j_plot_JPM = np.append(ind_j_plot_JPM, j) break fig2, ax =",
"databases # + # delete big files del dx_proj, sig2_garch # projected risk",
"plt.xlabel('t (days)', fontsize=17) plt.xticks(fontsize=14) plt.yticks(fontsize=14) add_logo(fig1, set_fig_size=False) fig1.tight_layout() # plot projected ratings #",
"pd.read_csv(path + 'db_estimation_nonparametric.csv', index_col=False) p_marginal = db_estimation_nonparametric.values # parameters for estimated Student t",
"pd.read_csv(path + 'db_estimation_copula.csv') nu_copula = int(db_estimation_copula['nu'].iloc[0]) rho2_copula = np.array(db_estimation_copula['rho2']).reshape(i_, i_) # parameters for",
"scenario probabilities out = pd.DataFrame({'p': pd.Series(p)}) out.to_csv(path + 'db_scenario_probs.csv', index=None) del out #",
"ratings_proj[:, :, 0].reshape((j_ * (m_ + 1),)), 'JPM': ratings_proj[:, :, 1].reshape((j_ * (m_",
"fontsize=20) plt.xlabel('t (days)', fontsize=17) plt.xticks(fontsize=14) plt.yticks(fontsize=14) add_logo(fig1, set_fig_size=False) fig1.tight_layout() # plot projected ratings",
"fig2, ax = plt.subplots(2, 1, figsize=(1280.0 / 72.0, 720.0 / 72.0), dpi=72.0) plt.sca(ax[0])",
"of scenarios d_plot = 97 # projected risk driver to plot # ##",
"p_marginal = db_estimation_nonparametric.values # parameters for estimated Student t copula db_estimation_copula = pd.read_csv(path",
"m - 1, d] # risk drivers modeled as GARCH(1,1) elif db_invariants_nextstep.iloc[0, d]",
"dx_proj[:, 0, d] = x[-1, d] - x[-2, d] # project daily scenarios",
"1) # Estimation # parameters for invariants modeled using Student t distribution db_estimation_parametric",
"+ plt.style.use('arpm') # number of paths to plot num_plot = min(j_, 20) #",
"/ 10, height=xp[1] - xp[0], left=t_ + 1 + m_, facecolor=[.3, .3, .3],",
"(j not in ind_j_plot_GE and ratings_proj[j, -1, 0] != ratings_proj[k, -1, 0]): ind_j_plot_GE",
"1), ratings_proj[int(j), :, 1] + 1) plt.title('Projected rating JPM', fontweight='bold', fontsize=20) plt.yticks(np.arange(10), fontsize=14)",
"# Estimation # parameters for invariants modeled using Student t distribution db_estimation_parametric =",
"t distribution db_estimation_parametric = pd.read_csv(path + 'db_estimation_parametric.csv', index_col=0) # estimated probabilities for nonparametric",
"'db_projection_riskdrivers.csv', index=None) del out # projected credit ratings out = pd.DataFrame({'GE': ratings_proj[:, :,",
"of projection steps and scenario probabilities # number of monitoring times m_ =",
"drivers at time t_now are the starting values for all scenarios x_proj[:, 0,",
"= c_garch[d] + \\ b_garch[d] * sig2_garch[:, m - 1, d] + \\",
"name: python3 # --- # # s_checklist_scenariobased_step04 [<img src=\"https://www.arpm.co/lab/icons/icon_permalink.png\" width=30 height=30 style=\"display: inline;\">](https://www.arpm.co/lab/redirect.php?code=s_checklist_scenariobased_step04&codeLang=Python)",
"= pd.read_csv(path + 'db_estimation_copula.csv') nu_copula = int(db_estimation_copula['nu'].iloc[0]) rho2_copula = np.array(db_estimation_copula['rho2']).reshape(i_, i_) # parameters",
"'db_estimation_parametric.csv', index_col=0) # estimated probabilities for nonparametric distributions db_estimation_nonparametric = pd.read_csv(path + 'db_estimation_nonparametric.csv',",
"scenarios for copula epsi_tilde_proj = simulate_t(np.zeros(i_), rho2_copula, nu_copula, j_) # generate invariants scenarios",
"for next step models db_invariants_param = pd.read_csv(path + 'db_invariants_param.csv', index_col=0) # parameters for",
"str(i)] nu_marg = db_estimation_parametric.loc['nu', str(i)] epsi_proj[:, m, i] = mu_marg + np.sqrt(sig2_marg) *",
"x_proj[:, 0, :] = db_riskdrivers_series.iloc[-1, :] # initialize parameters for GARCH(1,1) projection d_garch",
"set_fig_size=False) fig1.tight_layout() # plot projected ratings # select paths with rating changes ind_j_plot_GE",
"j in ind_j_plot_GE: f5 = plt.plot(np.arange(m_ + 1), ratings_proj[int(j), :, 0] + 1)",
"scenarios d_plot = 97 # projected risk driver to plot # ## [Step",
"in ind_j_plot_JPM: plt.plot(np.arange(m_ + 1), ratings_proj[int(j), :, 1] + 1) plt.title('Projected rating JPM',",
"# ## [Step 1](https://www.arpm.co/lab/redirect.php?permalink=s_checklist_scenariobased_step04-implementation-step01): Determine number of projection steps and scenario probabilities #",
"1 + m_, facecolor=[.3, .3, .3], edgecolor='k') plt.title('Projected path: ' + risk_drivers_names[d_plot -",
"+ 'db_projection_ratings.csv', index=None) del out # number of scenarios and future investment horizon",
"0] != ratings_proj[k, -1, 0]): ind_j_plot_GE = np.append(ind_j_plot_GE, j) break ind_j_plot_JPM = np.zeros(1)",
"'../../../databases/temporary-databases/' # Risk drivers identification # realizations of risk drivers up to and",
"and ratings_proj[j, -1, 1] != ratings_proj[k, -1, 1]): ind_j_plot_JPM = np.append(ind_j_plot_JPM, j) break",
"'GARCH(1,1)': sig2_garch[:, m, d] = c_garch[d] + \\ b_garch[d] * sig2_garch[:, m -",
"d] x_proj[:, m, d] = x_proj[:, m - 1, d] + dx_proj[:, m,",
"= plt.plot(np.arange(m_ + 1), ratings_proj[int(j), :, 0] + 1) plt.title('Projected rating GE', fontweight='bold',",
"register_matplotlib_converters() from arpym.statistics import quantile_sp, simulate_markov_chain_multiv, \\ simulate_t, project_trans_matrix from arpym.tools import histogram_sp,",
".py # format_name: light # format_version: '1.4' # jupytext_version: 1.1.5 # kernelspec: #",
"db_estimation_credit_copula = pd.read_csv(path + 'db_estimation_credit_copula.csv') rho2_credit = db_estimation_credit_copula.rho2_credit.values.reshape(2, 2) nu_credit = db_estimation_credit_copula.nu_credit[0] #",
"for GARCH(1,1) projection d_garch = [d for d in range(d_) if db_invariants_nextstep.iloc[0, d]",
"in range(m_): # copula scenarios # simulate standardized invariants scenarios for copula epsi_tilde_proj",
"Python 3 # language: python # name: python3 # --- # # s_checklist_scenariobased_step04",
"= int(db_riskdrivers_tools.n_stocks.dropna()) d_implvol = int(db_riskdrivers_tools.d_implvol.dropna()) n_bonds = int(db_riskdrivers_tools.n_bonds.dropna()) i_bonds = n_bonds * 4",
"# project t-copula standardized invariants scenarios u_proj = tstu.cdf(epsi_tilde_proj[:, i], nu_copula) mu_marg =",
"d in range(d_): # risk drivers modeled as random walk if db_invariants_nextstep.iloc[0, d]",
"= n_bonds * 4 # 4 NS parameters x n_bonds c_ = int(db_riskdrivers_tools.c_.dropna())",
"= db_invariants_param.loc['a'].values b_garch = db_invariants_param.loc['b'].values c_garch = db_invariants_param.loc['c'].values mu_garch = db_invariants_param.loc['mu'].values # risk",
"daily scenarios for m in range(1, m_ + 1): for d in range(d_):",
"= np.zeros((j_, m_, i_)) for m in range(m_): # copula scenarios # simulate",
"realizations of risk drivers up to and including time t_now db_riskdrivers_series = pd.read_csv(path",
"db_invariants_param.loc['b'][d] x_proj[:, m, d] = b_ar1 * x_proj[:, m - 1, d] +",
"edgecolor='k') plt.title('Projected path: ' + risk_drivers_names[d_plot - 1], fontweight='bold', fontsize=20) plt.xlabel('t (days)', fontsize=17)",
"list(set(range(i_)) - set(ind_parametric)) # ## [Step 2](https://www.arpm.co/lab/redirect.php?permalink=s_checklist_scenariobased_step04-implementation-step02): Projection of invariants # + epsi_proj",
"the starting values for all scenarios x_proj[:, 0, :] = db_riskdrivers_series.iloc[-1, :] #",
"plt from pandas.plotting import register_matplotlib_converters register_matplotlib_converters() from arpym.statistics import quantile_sp, simulate_markov_chain_multiv, \\ simulate_t,",
"db_invariants_nextstep.iloc[0, d] == 'GARCH(1,1)': sig2_garch[:, m, d] = c_garch[d] + \\ b_garch[d] *",
"3](https://www.arpm.co/lab/redirect.php?permalink=s_checklist_scenariobased_step04-implementation-step03): Projection of risk drivers # + x_proj = np.zeros((j_, m_ + 1,",
"out = pd.DataFrame({'j_': pd.Series(j_), 't_hor': pd.Series(t_hor)}) out.to_csv(path + 'db_projection_tools.csv', index=None) del out #",
"project ratings ratings_proj = simulate_markov_chain_multiv(ratings_tnow, p_credit_daily, m_, rho2=rho2_credit, nu=nu_credit, j_=j_) # - #",
"b_garch = db_invariants_param.loc['b'].values c_garch = db_invariants_param.loc['c'].values mu_garch = db_invariants_param.loc['mu'].values # risk drivers at",
"parameters x n_bonds c_ = int(db_riskdrivers_tools.c_.dropna()) ratings_tnow = np.array(db_riskdrivers_tools.ratings_tnow.dropna()) t_now = np.datetime64(db_riskdrivers_tools.t_now[0], 'D')",
"[here](https://www.arpm.co/lab/redirect.php?permalink=ex-vue-4-copmarg). # + import numpy as np import pandas as pd from scipy.stats",
"simulate_t, project_trans_matrix from arpym.tools import histogram_sp, add_logo # - # ## [Input parameters](https://www.arpm.co/lab/redirect.php?permalink=s_checklist_scenariobased_step04-parameters)",
"values for all scenarios x_proj[:, 0, :] = db_riskdrivers_series.iloc[-1, :] # initialize parameters",
"** 2 dx_proj[:, m, d] = mu_garch[d] + \\ np.sqrt(sig2_garch[:, m, d]) *",
"# parameters for estimated Student t copula db_estimation_copula = pd.read_csv(path + 'db_estimation_copula.csv') nu_copula",
"= x_proj[:, m - 1, d] + dx_proj[:, m, d] # risk drivers",
"+ 1 + m_, facecolor=[.3, .3, .3], edgecolor='k') plt.title('Projected path: ' + risk_drivers_names[d_plot",
"72.0), dpi=72.0) # plot historical series f1 = plt.plot(np.arange(t_ + 1), db_riskdrivers_series.iloc[:, d_plot",
"(days)', fontsize=17) plt.xticks(fontsize=14) plt.yticks(fontsize=14) add_logo(fig1, set_fig_size=False) fig1.tight_layout() # plot projected ratings # select",
"GE', fontweight='bold', fontsize=20) plt.yticks(np.arange(10), fontsize=14) ax[0].set_yticklabels(['', 'AAA', 'AA', 'A', 'BBB', 'BB', 'B', 'CCC',",
"nu_copula, j_) # generate invariants scenarios # invariants modeled nonparametrically for i in",
"m, d] = x_proj[:, m - 1, d] + dx_proj[:, m, d] #",
"the daily credit transition matrix p_credit_daily = project_trans_matrix(p_credit, 1 / 252) # project",
"num_plot: k = k + 1 for j in range(j_): if (j not",
"invariants db_invariants_series = pd.read_csv(path + 'db_invariants_series.csv', index_col=0, parse_dates=True) epsi = db_invariants_series.values t_, i_",
"m, d]) * epsi_proj[:, m - 1, d] x_proj[:, m, d] = x_proj[:,",
"i]) # invariants modeled parametrically (estimated as Student t distributed) for i in",
"= db_invariants_param.loc['mu'].values # risk drivers at time t_now are the starting values for",
"d_implvol, n_stocks + 1 + d_implvol + i_bonds) # invariants modeled nonparametrically ind_nonparametric",
"credit ratings out = pd.DataFrame({'GE': ratings_proj[:, :, 0].reshape((j_ * (m_ + 1),)), 'JPM':",
"+ 1),))}) out.to_csv(path + 'db_projection_ratings.csv', index=None) del out # number of scenarios and",
"+ 1), ratings_proj[int(j), :, 0] + 1) plt.title('Projected rating GE', fontweight='bold', fontsize=20) plt.yticks(np.arange(10),",
"ind_parametric: # project t-copula standardized invariants scenarios u_proj = tstu.cdf(epsi_tilde_proj[:, i], nu_copula) mu_marg",
"= np.shape(epsi) # next step models db_invariants_nextstep = pd.read_csv(path + 'db_invariants_nextstep.csv') # parameters",
"projection d_garch = [d for d in range(d_) if db_invariants_nextstep.iloc[0, d] == 'GARCH(1,1)']",
"+ \\ np.sqrt(sig2_garch[:, m, d]) * epsi_proj[:, m - 1, d] x_proj[:, m,",
"/ 72.0), dpi=72.0) plt.sca(ax[0]) for j in ind_j_plot_GE: f5 = plt.plot(np.arange(m_ + 1),",
"plt.title('Projected path: ' + risk_drivers_names[d_plot - 1], fontweight='bold', fontsize=20) plt.xlabel('t (days)', fontsize=17) plt.xticks(fontsize=14)",
"= x[-1, d] - x[-2, d] # project daily scenarios for m in",
"Student t copula db_estimation_copula = pd.read_csv(path + 'db_estimation_copula.csv') nu_copula = int(db_estimation_copula['nu'].iloc[0]) rho2_copula =",
"1], fontweight='bold', fontsize=20) plt.xlabel('t (days)', fontsize=17) plt.xticks(fontsize=14) plt.yticks(fontsize=14) add_logo(fig1, set_fig_size=False) fig1.tight_layout() # plot",
"+ path = '../../../databases/temporary-databases/' # Risk drivers identification # realizations of risk drivers",
"0, d] = x[-1, d] - x[-2, d] # project daily scenarios for",
"t_now is 31-Aug-2012. Set t_hor>t_now t_hor = np.datetime64('2012-10-26') # the future investment horizon",
"= pd.read_csv(path + 'db_estimation_credit_copula.csv') rho2_credit = db_estimation_credit_copula.rho2_credit.values.reshape(2, 2) nu_credit = db_estimation_credit_copula.nu_credit[0] # -",
"epsi_proj[:, m, i] = quantile_sp(u_proj, epsi[:, i], p_marginal[:, i]) # invariants modeled parametrically",
"1, d_)) sig2_garch = np.zeros((j_, m_ + 1, d_)) a_garch = db_invariants_param.loc['a'].values b_garch",
"t_, i_ = np.shape(epsi) # next step models db_invariants_nextstep = pd.read_csv(path + 'db_invariants_nextstep.csv')",
"+ 1, d_)) a_garch = db_invariants_param.loc['a'].values b_garch = db_invariants_param.loc['b'].values c_garch = db_invariants_param.loc['c'].values mu_garch",
"index=None) del out # projected credit ratings out = pd.DataFrame({'GE': ratings_proj[:, :, 0].reshape((j_",
"db_estimation_copula = pd.read_csv(path + 'db_estimation_copula.csv') nu_copula = int(db_estimation_copula['nu'].iloc[0]) rho2_copula = np.array(db_estimation_copula['rho2']).reshape(i_, i_) #",
"investment horizon j_ = 5000 # number of scenarios d_plot = 97 #",
"modeled as GARCH(1,1) elif db_invariants_nextstep.iloc[0, d] == 'GARCH(1,1)': sig2_garch[:, m, d] = c_garch[d]",
"ratings_proj[:, :, 1].reshape((j_ * (m_ + 1),))}) out.to_csv(path + 'db_projection_ratings.csv', index=None) del out",
"d] + epsi_proj[:, m - 1, d] # - # ## [Step 4](https://www.arpm.co/lab/redirect.php?permalink=s_checklist_scenariobased_step04-implementation-step04):",
"in range(1, m_ + 1): for d in range(d_): # risk drivers modeled",
"tstu import matplotlib.pyplot as plt from pandas.plotting import register_matplotlib_converters register_matplotlib_converters() from arpym.statistics import",
"- # ## [Step 1](https://www.arpm.co/lab/redirect.php?permalink=s_checklist_scenariobased_step04-implementation-step01): Determine number of projection steps and scenario probabilities",
"projection scenario probabilities p = np.ones(j_) / j_ # invariants modeled parametrically ind_parametric",
"for d in range(d_)}) out = out[list(risk_drivers_names[:d_].values)] out.to_csv(path + 'db_projection_riskdrivers.csv', index=None) del out",
"== 'GARCH(1,1)': sig2_garch[:, m, d] = c_garch[d] + \\ b_garch[d] * sig2_garch[:, m",
"# projected scenario probabilities out = pd.DataFrame({'p': pd.Series(p)}) out.to_csv(path + 'db_scenario_probs.csv', index=None) del",
"paths with rating changes ind_j_plot_GE = np.zeros(1) ind_j_plot_GE[0] = 0 k = 0",
"- 1, d] + epsi_proj[:, m - 1, d] # risk drivers modeled",
"1]): ind_j_plot_JPM = np.append(ind_j_plot_JPM, j) break fig2, ax = plt.subplots(2, 1, figsize=(1280.0 /",
"epsi_proj[:, m - 1, d] x_proj[:, m, d] = x_proj[:, m - 1,",
"m_ + 1): for d in range(d_): # risk drivers modeled as random",
"m_ + 1, d_)) a_garch = db_invariants_param.loc['a'].values b_garch = db_invariants_param.loc['b'].values c_garch = db_invariants_param.loc['c'].values",
"72.0), dpi=72.0) plt.sca(ax[0]) for j in ind_j_plot_GE: f5 = plt.plot(np.arange(m_ + 1), ratings_proj[int(j),",
"pd.Series(j_), 't_hor': pd.Series(t_hor)}) out.to_csv(path + 'db_projection_tools.csv', index=None) del out # projected scenario probabilities",
"plt.sca(ax[1]) for j in ind_j_plot_JPM: plt.plot(np.arange(m_ + 1), ratings_proj[int(j), :, 1] + 1)",
"# copula scenarios # simulate standardized invariants scenarios for copula epsi_tilde_proj = simulate_t(np.zeros(i_),",
"numpy as np import pandas as pd from scipy.stats import t as tstu",
"risk_drivers_names[d_plot - 1], fontweight='bold', fontsize=20) plt.xlabel('t (days)', fontsize=17) plt.xticks(fontsize=14) plt.yticks(fontsize=14) add_logo(fig1, set_fig_size=False) fig1.tight_layout()",
"rho2_credit = db_estimation_credit_copula.rho2_credit.values.reshape(2, 2) nu_credit = db_estimation_credit_copula.nu_credit[0] # - # ## [Step 1](https://www.arpm.co/lab/redirect.php?permalink=s_checklist_scenariobased_step04-implementation-step01):",
"'db_estimation_copula.csv') nu_copula = int(db_estimation_copula['nu'].iloc[0]) rho2_copula = np.array(db_estimation_copula['rho2']).reshape(i_, i_) # parameters for the credit",
"scenarios # simulate standardized invariants scenarios for copula epsi_tilde_proj = simulate_t(np.zeros(i_), rho2_copula, nu_copula,",
"+ np.sqrt(sig2_marg) * tstu.ppf(u_proj, nu_marg) # - # ## [Step 3](https://www.arpm.co/lab/redirect.php?permalink=s_checklist_scenariobased_step04-implementation-step03): Projection of",
"project t-copula standardized invariants scenarios u_proj = tstu.cdf(epsi_tilde_proj[:, i], nu_copula) epsi_proj[:, m, i]",
"for j in ind_j_plot_JPM: plt.plot(np.arange(m_ + 1), ratings_proj[int(j), :, 1] + 1) plt.title('Projected",
"for j in ind_j_plot_GE: f5 = plt.plot(np.arange(m_ + 1), ratings_proj[int(j), :, 0] +",
"+ 1),)) for d in range(d_)}) out = out[list(risk_drivers_names[:d_].values)] out.to_csv(path + 'db_projection_riskdrivers.csv', index=None)",
"drivers modeled as AR(1) elif db_invariants_nextstep.iloc[0, d] == 'AR(1)': b_ar1 = db_invariants_param.loc['b'][d] x_proj[:,",
"+ epsi_proj = np.zeros((j_, m_, i_)) for m in range(m_): # copula scenarios",
"= mu_garch[d] + \\ np.sqrt(sig2_garch[:, m, d]) * epsi_proj[:, m - 1, d]",
"risk drivers out = pd.DataFrame({risk_drivers_names[d]: x_proj[:, :, d].reshape((j_ * (m_ + 1),)) for",
"not in ind_j_plot_JPM and ratings_proj[j, -1, 1] != ratings_proj[k, -1, 1]): ind_j_plot_JPM =",
"t-copula standardized invariants scenarios u_proj = tstu.cdf(epsi_tilde_proj[:, i], nu_copula) epsi_proj[:, m, i] =",
"d] + epsi_proj[:, m - 1, d] # risk drivers modeled as GARCH(1,1)",
"mu_marg = db_estimation_parametric.loc['mu', str(i)] sig2_marg = db_estimation_parametric.loc['sig2', str(i)] nu_marg = db_estimation_parametric.loc['nu', str(i)] epsi_proj[:,",
"nu_credit = db_estimation_credit_copula.nu_credit[0] # - # ## [Step 1](https://www.arpm.co/lab/redirect.php?permalink=s_checklist_scenariobased_step04-implementation-step01): Determine number of projection",
"d] = db_garch_sig2.iloc[-1, d] dx_proj[:, 0, d] = x[-1, d] - x[-2, d]",
"+ 'db_estimation_credit_copula.csv') rho2_credit = db_estimation_credit_copula.rho2_credit.values.reshape(2, 2) nu_credit = db_estimation_credit_copula.nu_credit[0] # - # ##",
"# extension: .py # format_name: light # format_version: '1.4' # jupytext_version: 1.1.5 #",
"db_invariants_series.values t_, i_ = np.shape(epsi) # next step models db_invariants_nextstep = pd.read_csv(path +",
"in range(d_): # risk drivers modeled as random walk if db_invariants_nextstep.iloc[0, d] ==",
"path = '../../../databases/temporary-databases/' # Risk drivers identification # realizations of risk drivers up",
"= np.array(db_riskdrivers_tools.ratings_tnow.dropna()) t_now = np.datetime64(db_riskdrivers_tools.t_now[0], 'D') # Quest for invariance # values of",
"5](https://www.arpm.co/lab/redirect.php?permalink=s_checklist_scenariobased_step04-implementation-step05): Save databases # + # delete big files del dx_proj, sig2_garch #",
"k = 0 while k < num_plot: k = k + 1 for",
"register_matplotlib_converters register_matplotlib_converters() from arpym.statistics import quantile_sp, simulate_markov_chain_multiv, \\ simulate_t, project_trans_matrix from arpym.tools import",
"np.sqrt(sig2_garch[:, m, d]) * epsi_proj[:, m - 1, d] x_proj[:, m, d] =",
"3 # language: python # name: python3 # --- # # s_checklist_scenariobased_step04 [<img",
"= np.busday_count(t_now, t_hor) # projection scenario probabilities p = np.ones(j_) / j_ #",
"in ind_parametric: # project t-copula standardized invariants scenarios u_proj = tstu.cdf(epsi_tilde_proj[:, i], nu_copula)",
"--- # # s_checklist_scenariobased_step04 [<img src=\"https://www.arpm.co/lab/icons/icon_permalink.png\" width=30 height=30 style=\"display: inline;\">](https://www.arpm.co/lab/redirect.php?code=s_checklist_scenariobased_step04&codeLang=Python) # For details,",
"nu_marg = db_estimation_parametric.loc['nu', str(i)] epsi_proj[:, m, i] = mu_marg + np.sqrt(sig2_marg) * tstu.ppf(u_proj,",
":, 0].reshape((j_ * (m_ + 1),)), 'JPM': ratings_proj[:, :, 1].reshape((j_ * (m_ +",
"ratings ratings_proj = simulate_markov_chain_multiv(ratings_tnow, p_credit_daily, m_, rho2=rho2_credit, nu=nu_credit, j_=j_) # - # ##",
"of scenarios and future investment horizon out = pd.DataFrame({'j_': pd.Series(j_), 't_hor': pd.Series(t_hor)}) out.to_csv(path",
"'AA', 'A', 'BBB', 'BB', 'B', 'CCC', 'D', '']) plt.gca().invert_yaxis() plt.sca(ax[1]) for j in",
"d_ = int(db_riskdrivers_tools.d_.dropna()) d_credit = int(db_riskdrivers_tools.d_credit.dropna()) n_stocks = int(db_riskdrivers_tools.n_stocks.dropna()) d_implvol = int(db_riskdrivers_tools.d_implvol.dropna()) n_bonds",
"'B', 'CCC', 'D', '']) plt.gca().invert_yaxis() plt.sca(ax[1]) for j in ind_j_plot_JPM: plt.plot(np.arange(m_ + 1),",
"drivers modeled as GARCH(1,1) elif db_invariants_nextstep.iloc[0, d] == 'GARCH(1,1)': sig2_garch[:, m, d] =",
"+ 'db_scenario_probs.csv', index=None) del out # - # ## Plots # + plt.style.use('arpm')",
"and future investment horizon out = pd.DataFrame({'j_': pd.Series(j_), 't_hor': pd.Series(t_hor)}) out.to_csv(path + 'db_projection_tools.csv',",
"- # ## [Step 5](https://www.arpm.co/lab/redirect.php?permalink=s_checklist_scenariobased_step04-implementation-step05): Save databases # + # delete big files",
"ind_j_plot_GE = np.zeros(1) ind_j_plot_GE[0] = 0 k = 0 while k < num_plot:",
"1.1.5 # kernelspec: # display_name: Python 3 # language: python # name: python3",
"d_plot - 1], k_=10 * np.log(j_)) f1 = plt.barh(xp, f / 10, height=xp[1]",
"'AAA', 'AA', 'A', 'BBB', 'BB', 'B', 'CCC', 'D', '']) plt.gca().invert_yaxis() add_logo(fig2, set_fig_size=False) fig2.tight_layout()",
"- mu_garch[d]) ** 2 dx_proj[:, m, d] = mu_garch[d] + \\ np.sqrt(sig2_garch[:, m,",
"pd.read_csv(path + 'db_invariants_p_credit.csv').values.reshape(c_ + 1, c_ + 1) # Estimation # parameters for",
"from arpym.tools import histogram_sp, add_logo # - # ## [Input parameters](https://www.arpm.co/lab/redirect.php?permalink=s_checklist_scenariobased_step04-parameters) # t_now",
"d_garch: sig2_garch[:, 0, d] = db_garch_sig2.iloc[-1, d] dx_proj[:, 0, d] = x[-1, d]",
"d_implvol = int(db_riskdrivers_tools.d_implvol.dropna()) n_bonds = int(db_riskdrivers_tools.n_bonds.dropna()) i_bonds = n_bonds * 4 # 4",
"# number of monitoring times m_ = np.busday_count(t_now, t_hor) # projection scenario probabilities",
"# jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.4'",
"import pandas as pd from scipy.stats import t as tstu import matplotlib.pyplot as",
"db_invariants_param.loc['c'].values mu_garch = db_invariants_param.loc['mu'].values # risk drivers at time t_now are the starting",
"# parameters for next step models db_invariants_param = pd.read_csv(path + 'db_invariants_param.csv', index_col=0) #",
"+ epsi_proj[:, m - 1, d] # risk drivers modeled as GARCH(1,1) elif",
"m, d] = c_garch[d] + \\ b_garch[d] * sig2_garch[:, m - 1, d]",
"d_garch = [d for d in range(d_) if db_invariants_nextstep.iloc[0, d] == 'GARCH(1,1)'] for",
"nu_marg) # - # ## [Step 3](https://www.arpm.co/lab/redirect.php?permalink=s_checklist_scenariobased_step04-implementation-step03): Projection of risk drivers # +",
"ind_j_plot_JPM[0] = 0 k = 0 while k < num_plot: k = k",
"ind_nonparametric = list(set(range(i_)) - set(ind_parametric)) # ## [Step 2](https://www.arpm.co/lab/redirect.php?permalink=s_checklist_scenariobased_step04-implementation-step02): Projection of invariants #",
"a_garch = db_invariants_param.loc['a'].values b_garch = db_invariants_param.loc['b'].values c_garch = db_invariants_param.loc['c'].values mu_garch = db_invariants_param.loc['mu'].values #",
"# t_now is 31-Aug-2012. Set t_hor>t_now t_hor = np.datetime64('2012-10-26') # the future investment",
"index=None) del out # - # ## Plots # + plt.style.use('arpm') # number",
"pd from scipy.stats import t as tstu import matplotlib.pyplot as plt from pandas.plotting",
"pd.read_csv(path + 'db_garch_sig2.csv', index_col=0, parse_dates=True) # estimated annual credit transition matrix p_credit =",
"+ 1), x_proj[j, :, d_plot - 1], lw=1) f, xp = histogram_sp(x_proj[:, -1,",
"c_ + 1) # Estimation # parameters for invariants modeled using Student t",
"next step models db_invariants_param = pd.read_csv(path + 'db_invariants_param.csv', index_col=0) # parameters for GARCH(1,1)",
"for all scenarios x_proj[:, 0, :] = db_riskdrivers_series.iloc[-1, :] # initialize parameters for",
"ratings_proj = simulate_markov_chain_multiv(ratings_tnow, p_credit_daily, m_, rho2=rho2_credit, nu=nu_credit, j_=j_) # - # ## [Step",
":] = db_riskdrivers_series.iloc[-1, :] # initialize parameters for GARCH(1,1) projection d_garch = [d",
"for estimated Student t copula db_estimation_copula = pd.read_csv(path + 'db_estimation_copula.csv') nu_copula = int(db_estimation_copula['nu'].iloc[0])",
"t_hor) # projection scenario probabilities p = np.ones(j_) / j_ # invariants modeled",
"- # ## [Step 4](https://www.arpm.co/lab/redirect.php?permalink=s_checklist_scenariobased_step04-implementation-step04): Projection of credit ratings # + # compute",
"select paths with rating changes ind_j_plot_GE = np.zeros(1) ind_j_plot_GE[0] = 0 k =",
"d in range(d_) if db_invariants_nextstep.iloc[0, d] == 'GARCH(1,1)'] for d in d_garch: sig2_garch[:,",
"d] # - # ## [Step 4](https://www.arpm.co/lab/redirect.php?permalink=s_checklist_scenariobased_step04-implementation-step04): Projection of credit ratings # +",
"plt.barh(xp, f / 10, height=xp[1] - xp[0], left=t_ + 1 + m_, facecolor=[.3,",
"pd.DataFrame({risk_drivers_names[d]: x_proj[:, :, d].reshape((j_ * (m_ + 1),)) for d in range(d_)}) out",
"lw=1) # plot projected series for j in range(num_plot): f1 = plt.plot(np.arange(t_ +",
"out = pd.DataFrame({'GE': ratings_proj[:, :, 0].reshape((j_ * (m_ + 1),)), 'JPM': ratings_proj[:, :,",
"plt.plot(np.arange(m_ + 1), ratings_proj[int(j), :, 0] + 1) plt.title('Projected rating GE', fontweight='bold', fontsize=20)",
"ind_j_plot_GE[0] = 0 k = 0 while k < num_plot: k = k",
"f / 10, height=xp[1] - xp[0], left=t_ + 1 + m_, facecolor=[.3, .3,",
"np.array(db_estimation_copula['rho2']).reshape(i_, i_) # parameters for the credit copula db_estimation_credit_copula = pd.read_csv(path + 'db_estimation_credit_copula.csv')",
"d in range(d_)}) out = out[list(risk_drivers_names[:d_].values)] out.to_csv(path + 'db_projection_riskdrivers.csv', index=None) del out #",
"/ j_ # invariants modeled parametrically ind_parametric = np.arange(n_stocks + 1 + d_implvol,",
"parameters for estimated Student t copula db_estimation_copula = pd.read_csv(path + 'db_estimation_copula.csv') nu_copula =",
"+ risk_drivers_names[d_plot - 1], fontweight='bold', fontsize=20) plt.xlabel('t (days)', fontsize=17) plt.xticks(fontsize=14) plt.yticks(fontsize=14) add_logo(fig1, set_fig_size=False)",
"import histogram_sp, add_logo # - # ## [Input parameters](https://www.arpm.co/lab/redirect.php?permalink=s_checklist_scenariobased_step04-parameters) # t_now is 31-Aug-2012.",
"sig2_garch[:, 0, d] = db_garch_sig2.iloc[-1, d] dx_proj[:, 0, d] = x[-1, d] -",
"del out # number of scenarios and future investment horizon out = pd.DataFrame({'j_':",
"2) nu_credit = db_estimation_credit_copula.nu_credit[0] # - # ## [Step 1](https://www.arpm.co/lab/redirect.php?permalink=s_checklist_scenariobased_step04-implementation-step01): Determine number of",
"i], p_marginal[:, i]) # invariants modeled parametrically (estimated as Student t distributed) for",
"= int(db_riskdrivers_tools.d_.dropna()) d_credit = int(db_riskdrivers_tools.d_credit.dropna()) n_stocks = int(db_riskdrivers_tools.n_stocks.dropna()) d_implvol = int(db_riskdrivers_tools.d_implvol.dropna()) n_bonds =",
"# + # delete big files del dx_proj, sig2_garch # projected risk drivers",
"risk_drivers_names = db_riskdrivers_series.columns # additional information db_riskdrivers_tools = pd.read_csv(path + 'db_riskdrivers_tools.csv') d_ =",
"pd.read_csv(path + 'db_invariants_nextstep.csv') # parameters for next step models db_invariants_param = pd.read_csv(path +",
"# risk drivers modeled as random walk if db_invariants_nextstep.iloc[0, d] == 'Random walk':",
"b_ar1 * x_proj[:, m - 1, d] + epsi_proj[:, m - 1, d]",
"in range(j_): if (j not in ind_j_plot_JPM and ratings_proj[j, -1, 1] != ratings_proj[k,",
"extension: .py # format_name: light # format_version: '1.4' # jupytext_version: 1.1.5 # kernelspec:",
"risk drivers at time t_now are the starting values for all scenarios x_proj[:,",
"1, d] + \\ a_garch[d] * (dx_proj[:, m - 1, d] - mu_garch[d])",
"1, d] + epsi_proj[:, m - 1, d] # - # ## [Step",
"# projection scenario probabilities p = np.ones(j_) / j_ # invariants modeled parametrically",
"t copula db_estimation_copula = pd.read_csv(path + 'db_estimation_copula.csv') nu_copula = int(db_estimation_copula['nu'].iloc[0]) rho2_copula = np.array(db_estimation_copula['rho2']).reshape(i_,",
"x = db_riskdrivers_series.values risk_drivers_names = db_riskdrivers_series.columns # additional information db_riskdrivers_tools = pd.read_csv(path +",
"1, t_ + 1 + m_ + 1), x_proj[j, :, d_plot - 1],",
"+ 1 + d_implvol, n_stocks + 1 + d_implvol + i_bonds) # invariants",
"m_ = np.busday_count(t_now, t_hor) # projection scenario probabilities p = np.ones(j_) / j_",
"scenarios for m in range(1, m_ + 1): for d in range(d_): #",
"initialize parameters for GARCH(1,1) projection d_garch = [d for d in range(d_) if",
"parameters for the credit copula db_estimation_credit_copula = pd.read_csv(path + 'db_estimation_credit_copula.csv') rho2_credit = db_estimation_credit_copula.rho2_credit.values.reshape(2,",
"x_proj[:, m, d] = x_proj[:, m - 1, d] + epsi_proj[:, m -",
"epsi_proj[:, m - 1, d] # risk drivers modeled as GARCH(1,1) elif db_invariants_nextstep.iloc[0,",
"out = pd.DataFrame({'p': pd.Series(p)}) out.to_csv(path + 'db_scenario_probs.csv', index=None) del out # - #",
"- xp[0], left=t_ + 1 + m_, facecolor=[.3, .3, .3], edgecolor='k') plt.title('Projected path:",
"= int(db_riskdrivers_tools.n_bonds.dropna()) i_bonds = n_bonds * 4 # 4 NS parameters x n_bonds",
"= plt.plot(np.arange(t_ + 1), db_riskdrivers_series.iloc[:, d_plot - 1], lw=1) # plot projected series",
"m, d] = b_ar1 * x_proj[:, m - 1, d] + epsi_proj[:, m",
"int(db_riskdrivers_tools.c_.dropna()) ratings_tnow = np.array(db_riskdrivers_tools.ratings_tnow.dropna()) t_now = np.datetime64(db_riskdrivers_tools.t_now[0], 'D') # Quest for invariance #",
"for j in range(j_): if (j not in ind_j_plot_GE and ratings_proj[j, -1, 0]",
"1 + d_implvol + i_bonds) # invariants modeled nonparametrically ind_nonparametric = list(set(range(i_)) -",
"* (m_ + 1),)) for d in range(d_)}) out = out[list(risk_drivers_names[:d_].values)] out.to_csv(path +",
"[Step 1](https://www.arpm.co/lab/redirect.php?permalink=s_checklist_scenariobased_step04-implementation-step01): Determine number of projection steps and scenario probabilities # number of",
"720.0 / 72.0), dpi=72.0) plt.sca(ax[0]) for j in ind_j_plot_GE: f5 = plt.plot(np.arange(m_ +",
"estimated Student t copula db_estimation_copula = pd.read_csv(path + 'db_estimation_copula.csv') nu_copula = int(db_estimation_copula['nu'].iloc[0]) rho2_copula",
"not in ind_j_plot_GE and ratings_proj[j, -1, 0] != ratings_proj[k, -1, 0]): ind_j_plot_GE =",
"d_)) dx_proj = np.zeros((j_, m_ + 1, d_)) sig2_garch = np.zeros((j_, m_ +",
"0] + 1) plt.title('Projected rating GE', fontweight='bold', fontsize=20) plt.yticks(np.arange(10), fontsize=14) ax[0].set_yticklabels(['', 'AAA', 'AA',",
"plt.yticks(np.arange(10), fontsize=14) ax[0].set_yticklabels(['', 'AAA', 'AA', 'A', 'BBB', 'BB', 'B', 'CCC', 'D', '']) plt.gca().invert_yaxis()",
"in ind_j_plot_JPM and ratings_proj[j, -1, 1] != ratings_proj[k, -1, 1]): ind_j_plot_JPM = np.append(ind_j_plot_JPM,",
"db_riskdrivers_series.columns # additional information db_riskdrivers_tools = pd.read_csv(path + 'db_riskdrivers_tools.csv') d_ = int(db_riskdrivers_tools.d_.dropna()) d_credit",
"+ 1) plt.title('Projected rating JPM', fontweight='bold', fontsize=20) plt.yticks(np.arange(10), fontsize=14) ax[1].set_yticklabels(['', 'AAA', 'AA', 'A',",
"np.zeros((j_, m_, i_)) for m in range(m_): # copula scenarios # simulate standardized",
"copula db_estimation_copula = pd.read_csv(path + 'db_estimation_copula.csv') nu_copula = int(db_estimation_copula['nu'].iloc[0]) rho2_copula = np.array(db_estimation_copula['rho2']).reshape(i_, i_)",
"+ 'db_projection_tools.csv', index=None) del out # projected scenario probabilities out = pd.DataFrame({'p': pd.Series(p)})",
"= k + 1 for j in range(j_): if (j not in ind_j_plot_GE",
"the credit copula db_estimation_credit_copula = pd.read_csv(path + 'db_estimation_credit_copula.csv') rho2_credit = db_estimation_credit_copula.rho2_credit.values.reshape(2, 2) nu_credit",
"+ 'db_riskdrivers_tools.csv') d_ = int(db_riskdrivers_tools.d_.dropna()) d_credit = int(db_riskdrivers_tools.d_credit.dropna()) n_stocks = int(db_riskdrivers_tools.n_stocks.dropna()) d_implvol =",
"up to and including time t_now db_riskdrivers_series = pd.read_csv(path + 'db_riskdrivers_series.csv', index_col=0, parse_dates=True)",
"for the credit copula db_estimation_credit_copula = pd.read_csv(path + 'db_estimation_credit_copula.csv') rho2_credit = db_estimation_credit_copula.rho2_credit.values.reshape(2, 2)",
"out # projected scenario probabilities out = pd.DataFrame({'p': pd.Series(p)}) out.to_csv(path + 'db_scenario_probs.csv', index=None)",
"and including time t_now db_riskdrivers_series = pd.read_csv(path + 'db_riskdrivers_series.csv', index_col=0, parse_dates=True) x =",
"pd.read_csv(path + 'db_estimation_parametric.csv', index_col=0) # estimated probabilities for nonparametric distributions db_estimation_nonparametric = pd.read_csv(path",
"= simulate_t(np.zeros(i_), rho2_copula, nu_copula, j_) # generate invariants scenarios # invariants modeled nonparametrically",
"projected ratings # select paths with rating changes ind_j_plot_GE = np.zeros(1) ind_j_plot_GE[0] =",
"t_hor>t_now t_hor = np.datetime64('2012-10-26') # the future investment horizon j_ = 5000 #",
"index_col=0, parse_dates=True) epsi = db_invariants_series.values t_, i_ = np.shape(epsi) # next step models",
"Student t distributed) for i in ind_parametric: # project t-copula standardized invariants scenarios",
"db_invariants_param.loc['b'].values c_garch = db_invariants_param.loc['c'].values mu_garch = db_invariants_param.loc['mu'].values # risk drivers at time t_now",
"range(j_): if (j not in ind_j_plot_GE and ratings_proj[j, -1, 0] != ratings_proj[k, -1,",
"ind_j_plot_GE: f5 = plt.plot(np.arange(m_ + 1), ratings_proj[int(j), :, 0] + 1) plt.title('Projected rating",
"x_proj[:, :, d].reshape((j_ * (m_ + 1),)) for d in range(d_)}) out =",
"+ i_bonds) # invariants modeled nonparametrically ind_nonparametric = list(set(range(i_)) - set(ind_parametric)) # ##",
"db_estimation_credit_copula.rho2_credit.values.reshape(2, 2) nu_credit = db_estimation_credit_copula.nu_credit[0] # - # ## [Step 1](https://www.arpm.co/lab/redirect.php?permalink=s_checklist_scenariobased_step04-implementation-step01): Determine number",
"of risk drivers up to and including time t_now db_riskdrivers_series = pd.read_csv(path +",
"-1, d_plot - 1], k_=10 * np.log(j_)) f1 = plt.barh(xp, f / 10,",
"31-Aug-2012. Set t_hor>t_now t_hor = np.datetime64('2012-10-26') # the future investment horizon j_ =",
"t-copula standardized invariants scenarios u_proj = tstu.cdf(epsi_tilde_proj[:, i], nu_copula) mu_marg = db_estimation_parametric.loc['mu', str(i)]",
"project daily scenarios for m in range(1, m_ + 1): for d in",
"break fig2, ax = plt.subplots(2, 1, figsize=(1280.0 / 72.0, 720.0 / 72.0), dpi=72.0)",
"int(db_riskdrivers_tools.d_credit.dropna()) n_stocks = int(db_riskdrivers_tools.n_stocks.dropna()) d_implvol = int(db_riskdrivers_tools.d_implvol.dropna()) n_bonds = int(db_riskdrivers_tools.n_bonds.dropna()) i_bonds = n_bonds",
"/ 72.0, 720.0 / 72.0), dpi=72.0) plt.sca(ax[0]) for j in ind_j_plot_GE: f5 =",
"# jupyter: # jupytext: # text_representation: # extension: .py # format_name: light #",
"drivers identification # realizations of risk drivers up to and including time t_now",
"break ind_j_plot_JPM = np.zeros(1) ind_j_plot_JPM[0] = 0 k = 0 while k <",
"rho2_copula = np.array(db_estimation_copula['rho2']).reshape(i_, i_) # parameters for the credit copula db_estimation_credit_copula = pd.read_csv(path",
"= simulate_markov_chain_multiv(ratings_tnow, p_credit_daily, m_, rho2=rho2_credit, nu=nu_credit, j_=j_) # - # ## [Step 5](https://www.arpm.co/lab/redirect.php?permalink=s_checklist_scenariobased_step04-implementation-step05):",
"plot projected series for j in range(num_plot): f1 = plt.plot(np.arange(t_ + 1, t_",
"= 0 while k < num_plot: k = k + 1 for j",
"parse_dates=True) x = db_riskdrivers_series.values risk_drivers_names = db_riskdrivers_series.columns # additional information db_riskdrivers_tools = pd.read_csv(path",
"invariants modeled nonparametrically for i in ind_nonparametric: # project t-copula standardized invariants scenarios",
"out = pd.DataFrame({risk_drivers_names[d]: x_proj[:, :, d].reshape((j_ * (m_ + 1),)) for d in",
"= pd.DataFrame({'j_': pd.Series(j_), 't_hor': pd.Series(t_hor)}) out.to_csv(path + 'db_projection_tools.csv', index=None) del out # projected",
"= np.zeros(1) ind_j_plot_JPM[0] = 0 k = 0 while k < num_plot: k",
"720.0 / 72.0), dpi=72.0) # plot historical series f1 = plt.plot(np.arange(t_ + 1),",
"'D', '']) plt.gca().invert_yaxis() plt.sca(ax[1]) for j in ind_j_plot_JPM: plt.plot(np.arange(m_ + 1), ratings_proj[int(j), :,",
"left=t_ + 1 + m_, facecolor=[.3, .3, .3], edgecolor='k') plt.title('Projected path: ' +",
"if (j not in ind_j_plot_GE and ratings_proj[j, -1, 0] != ratings_proj[k, -1, 0]):",
"transition matrix p_credit = pd.read_csv(path + 'db_invariants_p_credit.csv').values.reshape(c_ + 1, c_ + 1) #",
"epsi_tilde_proj = simulate_t(np.zeros(i_), rho2_copula, nu_copula, j_) # generate invariants scenarios # invariants modeled",
"as np import pandas as pd from scipy.stats import t as tstu import",
"+ 'db_estimation_parametric.csv', index_col=0) # estimated probabilities for nonparametric distributions db_estimation_nonparametric = pd.read_csv(path +",
"future investment horizon j_ = 5000 # number of scenarios d_plot = 97",
"= db_estimation_parametric.loc['nu', str(i)] epsi_proj[:, m, i] = mu_marg + np.sqrt(sig2_marg) * tstu.ppf(u_proj, nu_marg)",
"m - 1, d] + dx_proj[:, m, d] # risk drivers modeled as",
"p_credit_daily, m_, rho2=rho2_credit, nu=nu_credit, j_=j_) # - # ## [Step 5](https://www.arpm.co/lab/redirect.php?permalink=s_checklist_scenariobased_step04-implementation-step05): Save databases",
"horizon out = pd.DataFrame({'j_': pd.Series(j_), 't_hor': pd.Series(t_hor)}) out.to_csv(path + 'db_projection_tools.csv', index=None) del out",
"+ 1) plt.title('Projected rating GE', fontweight='bold', fontsize=20) plt.yticks(np.arange(10), fontsize=14) ax[0].set_yticklabels(['', 'AAA', 'AA', 'A',",
"'CCC', 'D', '']) plt.gca().invert_yaxis() plt.sca(ax[1]) for j in ind_j_plot_JPM: plt.plot(np.arange(m_ + 1), ratings_proj[int(j),",
"fontsize=20) plt.yticks(np.arange(10), fontsize=14) ax[1].set_yticklabels(['', 'AAA', 'AA', 'A', 'BBB', 'BB', 'B', 'CCC', 'D', ''])",
"n_bonds * 4 # 4 NS parameters x n_bonds c_ = int(db_riskdrivers_tools.c_.dropna()) ratings_tnow",
"= int(db_riskdrivers_tools.c_.dropna()) ratings_tnow = np.array(db_riskdrivers_tools.ratings_tnow.dropna()) t_now = np.datetime64(db_riskdrivers_tools.t_now[0], 'D') # Quest for invariance",
"1].reshape((j_ * (m_ + 1),))}) out.to_csv(path + 'db_projection_ratings.csv', index=None) del out # number",
"int(db_riskdrivers_tools.n_stocks.dropna()) d_implvol = int(db_riskdrivers_tools.d_implvol.dropna()) n_bonds = int(db_riskdrivers_tools.n_bonds.dropna()) i_bonds = n_bonds * 4 #",
"# estimated annual credit transition matrix p_credit = pd.read_csv(path + 'db_invariants_p_credit.csv').values.reshape(c_ + 1,",
"np.append(ind_j_plot_JPM, j) break fig2, ax = plt.subplots(2, 1, figsize=(1280.0 / 72.0, 720.0 /",
"risk drivers modeled as random walk if db_invariants_nextstep.iloc[0, d] == 'Random walk': x_proj[:,",
"# simulate standardized invariants scenarios for copula epsi_tilde_proj = simulate_t(np.zeros(i_), rho2_copula, nu_copula, j_)",
"for copula epsi_tilde_proj = simulate_t(np.zeros(i_), rho2_copula, nu_copula, j_) # generate invariants scenarios #",
"int(db_riskdrivers_tools.n_bonds.dropna()) i_bonds = n_bonds * 4 # 4 NS parameters x n_bonds c_",
"arpym.statistics import quantile_sp, simulate_markov_chain_multiv, \\ simulate_t, project_trans_matrix from arpym.tools import histogram_sp, add_logo #",
"'AR(1)': b_ar1 = db_invariants_param.loc['b'][d] x_proj[:, m, d] = b_ar1 * x_proj[:, m -",
"GARCH(1,1) elif db_invariants_nextstep.iloc[0, d] == 'GARCH(1,1)': sig2_garch[:, m, d] = c_garch[d] + \\",
"d_)) a_garch = db_invariants_param.loc['a'].values b_garch = db_invariants_param.loc['b'].values c_garch = db_invariants_param.loc['c'].values mu_garch = db_invariants_param.loc['mu'].values",
"= pd.read_csv(path + 'db_riskdrivers_tools.csv') d_ = int(db_riskdrivers_tools.d_.dropna()) d_credit = int(db_riskdrivers_tools.d_credit.dropna()) n_stocks = int(db_riskdrivers_tools.n_stocks.dropna())",
"- 1, d] + epsi_proj[:, m - 1, d] # - # ##",
"index_col=False) p_marginal = db_estimation_nonparametric.values # parameters for estimated Student t copula db_estimation_copula =",
"i], nu_copula) epsi_proj[:, m, i] = quantile_sp(u_proj, epsi[:, i], p_marginal[:, i]) # invariants",
"scenarios x_proj[:, 0, :] = db_riskdrivers_series.iloc[-1, :] # initialize parameters for GARCH(1,1) projection",
"projected risk drivers out = pd.DataFrame({risk_drivers_names[d]: x_proj[:, :, d].reshape((j_ * (m_ + 1),))",
"out.to_csv(path + 'db_projection_ratings.csv', index=None) del out # number of scenarios and future investment",
"- 1], k_=10 * np.log(j_)) f1 = plt.barh(xp, f / 10, height=xp[1] -",
"np.zeros((j_, m_ + 1, d_)) a_garch = db_invariants_param.loc['a'].values b_garch = db_invariants_param.loc['b'].values c_garch =",
"'A', 'BBB', 'BB', 'B', 'CCC', 'D', '']) plt.gca().invert_yaxis() plt.sca(ax[1]) for j in ind_j_plot_JPM:",
"to plot num_plot = min(j_, 20) # market risk driver path fig1 =",
"= plt.figure(figsize=(1280.0 / 72.0, 720.0 / 72.0), dpi=72.0) # plot historical series f1",
"# ## [Step 0](https://www.arpm.co/lab/redirect.php?permalink=s_checklist_scenariobased_step04-implementation-step00): Load data # + path = '../../../databases/temporary-databases/' # Risk",
"m, d] # risk drivers modeled as AR(1) elif db_invariants_nextstep.iloc[0, d] == 'AR(1)':",
"epsi_proj[:, m - 1, d] # - # ## [Step 4](https://www.arpm.co/lab/redirect.php?permalink=s_checklist_scenariobased_step04-implementation-step04): Projection of",
"projected credit ratings out = pd.DataFrame({'GE': ratings_proj[:, :, 0].reshape((j_ * (m_ + 1),)),",
"' + risk_drivers_names[d_plot - 1], fontweight='bold', fontsize=20) plt.xlabel('t (days)', fontsize=17) plt.xticks(fontsize=14) plt.yticks(fontsize=14) add_logo(fig1,",
"np.ones(j_) / j_ # invariants modeled parametrically ind_parametric = np.arange(n_stocks + 1 +",
"epsi_proj = np.zeros((j_, m_, i_)) for m in range(m_): # copula scenarios #",
"# risk drivers at time t_now are the starting values for all scenarios",
"= pd.read_csv(path + 'db_invariants_p_credit.csv').values.reshape(c_ + 1, c_ + 1) # Estimation # parameters",
"# + x_proj = np.zeros((j_, m_ + 1, d_)) dx_proj = np.zeros((j_, m_",
"are the starting values for all scenarios x_proj[:, 0, :] = db_riskdrivers_series.iloc[-1, :]",
"del out # projected scenario probabilities out = pd.DataFrame({'p': pd.Series(p)}) out.to_csv(path + 'db_scenario_probs.csv',",
"= pd.read_csv(path + 'db_garch_sig2.csv', index_col=0, parse_dates=True) # estimated annual credit transition matrix p_credit",
"# ## [Step 3](https://www.arpm.co/lab/redirect.php?permalink=s_checklist_scenariobased_step04-implementation-step03): Projection of risk drivers # + x_proj = np.zeros((j_,",
"1),)), 'JPM': ratings_proj[:, :, 1].reshape((j_ * (m_ + 1),))}) out.to_csv(path + 'db_projection_ratings.csv', index=None)",
"import numpy as np import pandas as pd from scipy.stats import t as",
"d_credit = int(db_riskdrivers_tools.d_credit.dropna()) n_stocks = int(db_riskdrivers_tools.n_stocks.dropna()) d_implvol = int(db_riskdrivers_tools.d_implvol.dropna()) n_bonds = int(db_riskdrivers_tools.n_bonds.dropna()) i_bonds",
"# select paths with rating changes ind_j_plot_GE = np.zeros(1) ind_j_plot_GE[0] = 0 k",
"= np.append(ind_j_plot_JPM, j) break fig2, ax = plt.subplots(2, 1, figsize=(1280.0 / 72.0, 720.0",
"= db_riskdrivers_series.iloc[-1, :] # initialize parameters for GARCH(1,1) projection d_garch = [d for",
"x[-2, d] # project daily scenarios for m in range(1, m_ + 1):",
"# ## [Step 4](https://www.arpm.co/lab/redirect.php?permalink=s_checklist_scenariobased_step04-implementation-step04): Projection of credit ratings # + # compute the",
"i_bonds = n_bonds * 4 # 4 NS parameters x n_bonds c_ =",
"dpi=72.0) plt.sca(ax[0]) for j in ind_j_plot_GE: f5 = plt.plot(np.arange(m_ + 1), ratings_proj[int(j), :,",
"= db_estimation_credit_copula.nu_credit[0] # - # ## [Step 1](https://www.arpm.co/lab/redirect.php?permalink=s_checklist_scenariobased_step04-implementation-step01): Determine number of projection steps",
"delete big files del dx_proj, sig2_garch # projected risk drivers out = pd.DataFrame({risk_drivers_names[d]:",
"## [Step 1](https://www.arpm.co/lab/redirect.php?permalink=s_checklist_scenariobased_step04-implementation-step01): Determine number of projection steps and scenario probabilities # number",
"-1, 0] != ratings_proj[k, -1, 0]): ind_j_plot_GE = np.append(ind_j_plot_GE, j) break ind_j_plot_JPM =",
"1): for d in range(d_): # risk drivers modeled as random walk if",
"GARCH(1,1) next step models db_garch_sig2 = pd.read_csv(path + 'db_garch_sig2.csv', index_col=0, parse_dates=True) # estimated",
"d] # risk drivers modeled as GARCH(1,1) elif db_invariants_nextstep.iloc[0, d] == 'GARCH(1,1)': sig2_garch[:,",
"is 31-Aug-2012. Set t_hor>t_now t_hor = np.datetime64('2012-10-26') # the future investment horizon j_",
"/ 72.0), dpi=72.0) # plot historical series f1 = plt.plot(np.arange(t_ + 1), db_riskdrivers_series.iloc[:,",
"ratings_tnow = np.array(db_riskdrivers_tools.ratings_tnow.dropna()) t_now = np.datetime64(db_riskdrivers_tools.t_now[0], 'D') # Quest for invariance # values",
"d] == 'AR(1)': b_ar1 = db_invariants_param.loc['b'][d] x_proj[:, m, d] = b_ar1 * x_proj[:,",
"- set(ind_parametric)) # ## [Step 2](https://www.arpm.co/lab/redirect.php?permalink=s_checklist_scenariobased_step04-implementation-step02): Projection of invariants # + epsi_proj =",
"rho2=rho2_credit, nu=nu_credit, j_=j_) # - # ## [Step 5](https://www.arpm.co/lab/redirect.php?permalink=s_checklist_scenariobased_step04-implementation-step05): Save databases # +",
"parametrically (estimated as Student t distributed) for i in ind_parametric: # project t-copula",
"m, d] = x_proj[:, m - 1, d] + epsi_proj[:, m - 1,",
"= pd.read_csv(path + 'db_invariants_param.csv', index_col=0) # parameters for GARCH(1,1) next step models db_garch_sig2",
"= pd.read_csv(path + 'db_invariants_nextstep.csv') # parameters for next step models db_invariants_param = pd.read_csv(path",
"x_proj[:, m - 1, d] + epsi_proj[:, m - 1, d] # risk",
"ratings # + # compute the daily credit transition matrix p_credit_daily = project_trans_matrix(p_credit,",
"index=None) del out # number of scenarios and future investment horizon out =",
"u_proj = tstu.cdf(epsi_tilde_proj[:, i], nu_copula) epsi_proj[:, m, i] = quantile_sp(u_proj, epsi[:, i], p_marginal[:,",
"d in d_garch: sig2_garch[:, 0, d] = db_garch_sig2.iloc[-1, d] dx_proj[:, 0, d] =",
"plt.sca(ax[0]) for j in ind_j_plot_GE: f5 = plt.plot(np.arange(m_ + 1), ratings_proj[int(j), :, 0]",
"number of scenarios and future investment horizon out = pd.DataFrame({'j_': pd.Series(j_), 't_hor': pd.Series(t_hor)})",
"k = k + 1 for j in range(j_): if (j not in",
"market risk driver path fig1 = plt.figure(figsize=(1280.0 / 72.0, 720.0 / 72.0), dpi=72.0)",
"Determine number of projection steps and scenario probabilities # number of monitoring times",
"for nonparametric distributions db_estimation_nonparametric = pd.read_csv(path + 'db_estimation_nonparametric.csv', index_col=False) p_marginal = db_estimation_nonparametric.values #",
"+ 1 for j in range(j_): if (j not in ind_j_plot_JPM and ratings_proj[j,",
"nonparametrically ind_nonparametric = list(set(range(i_)) - set(ind_parametric)) # ## [Step 2](https://www.arpm.co/lab/redirect.php?permalink=s_checklist_scenariobased_step04-implementation-step02): Projection of invariants",
"tstu.cdf(epsi_tilde_proj[:, i], nu_copula) mu_marg = db_estimation_parametric.loc['mu', str(i)] sig2_marg = db_estimation_parametric.loc['sig2', str(i)] nu_marg =",
"at time t_now are the starting values for all scenarios x_proj[:, 0, :]",
"d] = x_proj[:, m - 1, d] + epsi_proj[:, m - 1, d]",
"d_)) sig2_garch = np.zeros((j_, m_ + 1, d_)) a_garch = db_invariants_param.loc['a'].values b_garch =",
"'db_projection_ratings.csv', index=None) del out # number of scenarios and future investment horizon out",
"i in ind_parametric: # project t-copula standardized invariants scenarios u_proj = tstu.cdf(epsi_tilde_proj[:, i],",
"for j in range(j_): if (j not in ind_j_plot_JPM and ratings_proj[j, -1, 1]",
"scenarios u_proj = tstu.cdf(epsi_tilde_proj[:, i], nu_copula) epsi_proj[:, m, i] = quantile_sp(u_proj, epsi[:, i],",
"db_invariants_nextstep.iloc[0, d] == 'GARCH(1,1)'] for d in d_garch: sig2_garch[:, 0, d] = db_garch_sig2.iloc[-1,",
"as AR(1) elif db_invariants_nextstep.iloc[0, d] == 'AR(1)': b_ar1 = db_invariants_param.loc['b'][d] x_proj[:, m, d]",
"set(ind_parametric)) # ## [Step 2](https://www.arpm.co/lab/redirect.php?permalink=s_checklist_scenariobased_step04-implementation-step02): Projection of invariants # + epsi_proj = np.zeros((j_,",
"d] == 'GARCH(1,1)'] for d in d_garch: sig2_garch[:, 0, d] = db_garch_sig2.iloc[-1, d]",
"invariants scenarios u_proj = tstu.cdf(epsi_tilde_proj[:, i], nu_copula) epsi_proj[:, m, i] = quantile_sp(u_proj, epsi[:,",
"random walk if db_invariants_nextstep.iloc[0, d] == 'Random walk': x_proj[:, m, d] = x_proj[:,",
"1),))}) out.to_csv(path + 'db_projection_ratings.csv', index=None) del out # number of scenarios and future",
"kernelspec: # display_name: Python 3 # language: python # name: python3 # ---",
"## [Step 2](https://www.arpm.co/lab/redirect.php?permalink=s_checklist_scenariobased_step04-implementation-step02): Projection of invariants # + epsi_proj = np.zeros((j_, m_, i_))",
"risk drivers # + x_proj = np.zeros((j_, m_ + 1, d_)) dx_proj =",
"db_riskdrivers_series = pd.read_csv(path + 'db_riskdrivers_series.csv', index_col=0, parse_dates=True) x = db_riskdrivers_series.values risk_drivers_names = db_riskdrivers_series.columns",
"'db_riskdrivers_series.csv', index_col=0, parse_dates=True) x = db_riskdrivers_series.values risk_drivers_names = db_riskdrivers_series.columns # additional information db_riskdrivers_tools",
"1], k_=10 * np.log(j_)) f1 = plt.barh(xp, f / 10, height=xp[1] - xp[0],",
"in ind_j_plot_GE and ratings_proj[j, -1, 0] != ratings_proj[k, -1, 0]): ind_j_plot_GE = np.append(ind_j_plot_GE,",
"out # - # ## Plots # + plt.style.use('arpm') # number of paths",
"= db_estimation_nonparametric.values # parameters for estimated Student t copula db_estimation_copula = pd.read_csv(path +",
"+ 'db_invariants_p_credit.csv').values.reshape(c_ + 1, c_ + 1) # Estimation # parameters for invariants"
] |
[
"if there are fewer than minibatch_size images left if (batch_num + 1) *",
"loss = discrimScore.mean() + 0.2*cosSim(ynew,og_x).mean() + 1.0*discrimScore.std() + 3.0*cosSim(ynew,og_x).std() else: loss = discrimScore.mean()",
"= x.size() #Recovered latent vectors y = recovered_latents[batch_num * minibatch_size: end].to(device) #Put both",
"torch.optim as optim import torch.nn as nn import math from tqdm import tqdm",
"the protoimage vectors \"\"\" import torch import torch.optim as optim import torch.nn as",
"optim.Adam([alpha], lr = lr) cosSim = nn.CosineSimilarity() #Learning rate scheduler sched = optim.lr_scheduler.StepLR(optimizer",
"3.0, epsilon = 0.0001, minibatch_size = 16): ''' Lambda: weight for the cosine",
"if (batch_num + 1) * minibatch_size > num_samples: end = num_samples + 1",
"batch_size,_ = x.size() #Recovered latent vectors y = recovered_latents[batch_num * minibatch_size: end].to(device) #Put",
"fewer than minibatch_size images left if (batch_num + 1) * minibatch_size > num_samples:",
"discrimScore.mean() + 0.2*cosSim(ynew,og_x).mean() + 1.0*discrimScore.std() + 3.0*cosSim(ynew,og_x).std() else: loss = discrimScore.mean() + Lambda*cosSim(ynew,og_x).mean()",
"loss x = y * 1.0 y = ynew.detach() diff = y -",
"= y - x opt = optim.Adam([alpha], lr = lr) cosSim = nn.CosineSimilarity()",
"y.detach().requires_grad_(False).to(device) og_x = x * 1.0 alpha = torch.ones(batch_size,512,device=device) alpha = alpha.requires_grad_(True) #Initial",
"vectors currImgs = model.netG(ynew) #Get the discriminator score discrimScore = model.netD(currImgs,getFeature = False)",
"= (batch_num + 1) * minibatch_size #Original latent vectors x = og_latents[batch_num *",
"= opt, step_size = 200, gamma = 0.1) oldLoss = 0 for i",
"loss = discrimScore.mean() + Lambda*cosSim(ynew,og_x).mean() #Backpropagate the error loss.backward() #Take a step with",
"0.1, Lambda = 3.0, epsilon = 0.0001, minibatch_size = 16): ''' Lambda: weight",
"samples and the dimensionality num_samples, num_dims = og_latents.size() #Number of batches needed num_batches",
"import torch.nn as nn import math from tqdm import tqdm from . import",
"#Recovered latent vectors y = recovered_latents[batch_num * minibatch_size: end].to(device) #Put both on the",
"discriminator score discrimScore = model.netD(currImgs,getFeature = False) #Calculate the loss if model_type ==",
"# print('Iterations: ' + str(i)) # print('Loss: ' + str(loss)) protoLatents[batch_num * minibatch_size:",
"score discrimScore = model.netD(currImgs,getFeature = False) #Calculate the loss if model_type == 'wgangp':",
"= 3.0, epsilon = 0.0001, minibatch_size = 16): ''' Lambda: weight for the",
"Lambda = 3.0, epsilon = 0.0001, minibatch_size = 16): ''' Lambda: weight for",
"= 0.1) oldLoss = 0 for i in range(501): #Zero the gradients opt.zero_grad()",
"/ (diff.norm(dim=1).unsqueeze(1)**2)))) ynew = utils.normalize(ynew) #Get the images of the current latent vectors",
"for the protoimage latent vector...') #Get the number of samples and the dimensionality",
"Mar 4 08:24:48 2021 proto_optim.py - Find the protoimage vectors \"\"\" import torch",
"latent vector...') #Get the number of samples and the dimensionality num_samples, num_dims =",
"vector...') #Get the number of samples and the dimensionality num_samples, num_dims = og_latents.size()",
"model.netD(currImgs,getFeature = False) #Calculate the loss if model_type == 'wgangp': loss = discrimScore.mean()",
"images of the current latent vectors currImgs = model.netG(ynew) #Get the discriminator score",
"print('Searching for the protoimage latent vector...') #Get the number of samples and the",
"tqdm import tqdm from . import utils #Optimization to get the protoimages def",
"= num_samples + 1 else: end = (batch_num + 1) * minibatch_size #Original",
"minibatch_size: end].to(device) #Put both on the device x = x.detach().requires_grad_(False).to(device) y = y.detach().requires_grad_(False).to(device)",
"Thu Mar 4 08:24:48 2021 proto_optim.py - Find the protoimage vectors \"\"\" import",
"protoimage latent vector...') #Get the number of samples and the dimensionality num_samples, num_dims",
"utils.normalize(ynew) #Get the images of the current latent vectors currImgs = model.netG(ynew) #Get",
"x.size() #Recovered latent vectors y = recovered_latents[batch_num * minibatch_size: end].to(device) #Put both on",
"1.0 alpha = torch.ones(batch_size,512,device=device) alpha = alpha.requires_grad_(True) #Initial direction diff = y -",
"#Put both on the device x = x.detach().requires_grad_(False).to(device) y = y.detach().requires_grad_(False).to(device) og_x =",
"1 == 0: # print('Iterations: ' + str(i)) # print('Loss: ' + str(loss))",
"og_latents[batch_num * minibatch_size: end].to(device) batch_size,_ = x.size() #Recovered latent vectors y = recovered_latents[batch_num",
"- x #Show the progress # if i % 1 == 0: #",
"0.0001, minibatch_size = 16): ''' Lambda: weight for the cosine similarity loss (3.0",
"minibatch_size: end].to(device) batch_size,_ = x.size() #Recovered latent vectors y = recovered_latents[batch_num * minibatch_size:",
"opt.zero_grad() #Move the direction of the difference vector ynew = y + (torch.mm(alpha,diff.t()).diagonal().unsqueeze(1)",
"= model.netG(ynew) #Get the discriminator score discrimScore = model.netD(currImgs,getFeature = False) #Calculate the",
"y = recovered_latents[batch_num * minibatch_size: end].to(device) #Put both on the device x =",
"1 else: end = (batch_num + 1) * minibatch_size #Original latent vectors x",
"alpha.requires_grad_(True) #Initial direction diff = y - x opt = optim.Adam([alpha], lr =",
"cosSim = nn.CosineSimilarity() #Learning rate scheduler sched = optim.lr_scheduler.StepLR(optimizer = opt, step_size =",
"y = y.detach().requires_grad_(False).to(device) og_x = x * 1.0 alpha = torch.ones(batch_size,512,device=device) alpha =",
"both on the device x = x.detach().requires_grad_(False).to(device) y = y.detach().requires_grad_(False).to(device) og_x = x",
"proto_optim(og_latents,recovered_latents, model, model_type, device, lr = 0.1, Lambda = 3.0, epsilon = 0.0001,",
"math from tqdm import tqdm from . import utils #Optimization to get the",
"#Zero the gradients opt.zero_grad() #Move the direction of the difference vector ynew =",
"= discrimScore.mean() + 0.2*cosSim(ynew,og_x).mean() + 1.0*discrimScore.std() + 3.0*cosSim(ynew,og_x).std() else: loss = discrimScore.mean() +",
"recovered_latents[batch_num * minibatch_size: end].to(device) #Put both on the device x = x.detach().requires_grad_(False).to(device) y",
"''' Lambda: weight for the cosine similarity loss (3.0 for celeba_pgan, 5.0 for",
"vectors protoLatents = torch.zeros(num_samples,num_dims) for batch_num in tqdm(range(num_batches)): #Check if there are fewer",
"coding: utf-8 -*- \"\"\" Created on Thu Mar 4 08:24:48 2021 proto_optim.py -",
"minibatch_size images left if (batch_num + 1) * minibatch_size > num_samples: end =",
"+ 3.0*cosSim(ynew,og_x).std() else: loss = discrimScore.mean() + Lambda*cosSim(ynew,og_x).mean() #Backpropagate the error loss.backward() #Take",
"get the protoimages def proto_optim(og_latents,recovered_latents, model, model_type, device, lr = 0.1, Lambda =",
"the found protoimage latent vectors protoLatents = torch.zeros(num_samples,num_dims) for batch_num in tqdm(range(num_batches)): #Check",
"in tqdm(range(num_batches)): #Check if there are fewer than minibatch_size images left if (batch_num",
"the protoimage latent vector...') #Get the number of samples and the dimensionality num_samples,",
"x = og_latents[batch_num * minibatch_size: end].to(device) batch_size,_ = x.size() #Recovered latent vectors y",
"found protoimage latent vectors protoLatents = torch.zeros(num_samples,num_dims) for batch_num in tqdm(range(num_batches)): #Check if",
"step_size = 200, gamma = 0.1) oldLoss = 0 for i in range(501):",
"the loss if model_type == 'wgangp': loss = discrimScore.mean() + 0.2*cosSim(ynew,og_x).mean() + 1.0*discrimScore.std()",
"y * 1.0 y = ynew.detach() diff = y - x #Show the",
"= y + (torch.mm(alpha,diff.t()).diagonal().unsqueeze(1) * ((diff / (diff.norm(dim=1).unsqueeze(1)**2)))) ynew = utils.normalize(ynew) #Get the",
"og_latents.size() #Number of batches needed num_batches = int(math.ceil(num_samples/minibatch_size)) #Vector for the found protoimage",
"= optim.lr_scheduler.StepLR(optimizer = opt, step_size = 200, gamma = 0.1) oldLoss = 0",
"# -*- coding: utf-8 -*- \"\"\" Created on Thu Mar 4 08:24:48 2021",
"sched.step() #Early stopping condition if abs(loss-oldLoss) < epsilon: break else: oldLoss = loss",
"= loss x = y * 1.0 y = ynew.detach() diff = y",
"x = x.detach().requires_grad_(False).to(device) y = y.detach().requires_grad_(False).to(device) og_x = x * 1.0 alpha =",
"protoimage vectors \"\"\" import torch import torch.optim as optim import torch.nn as nn",
"10.0 for celebaHQ_pgan) ''' print('Searching for the protoimage latent vector...') #Get the number",
"batches needed num_batches = int(math.ceil(num_samples/minibatch_size)) #Vector for the found protoimage latent vectors protoLatents",
"step with the optimizer opt.step() sched.step() #Early stopping condition if abs(loss-oldLoss) < epsilon:",
"ynew = utils.normalize(ynew) #Get the images of the current latent vectors currImgs =",
"num_samples, num_dims = og_latents.size() #Number of batches needed num_batches = int(math.ceil(num_samples/minibatch_size)) #Vector for",
"i in range(501): #Zero the gradients opt.zero_grad() #Move the direction of the difference",
"Find the protoimage vectors \"\"\" import torch import torch.optim as optim import torch.nn",
"difference vector ynew = y + (torch.mm(alpha,diff.t()).diagonal().unsqueeze(1) * ((diff / (diff.norm(dim=1).unsqueeze(1)**2)))) ynew =",
"' + str(i)) # print('Loss: ' + str(loss)) protoLatents[batch_num * minibatch_size: end] =",
"images left if (batch_num + 1) * minibatch_size > num_samples: end = num_samples",
"the direction of the difference vector ynew = y + (torch.mm(alpha,diff.t()).diagonal().unsqueeze(1) * ((diff",
"= 0.1, Lambda = 3.0, epsilon = 0.0001, minibatch_size = 16): ''' Lambda:",
"#Get the discriminator score discrimScore = model.netD(currImgs,getFeature = False) #Calculate the loss if",
"''' print('Searching for the protoimage latent vector...') #Get the number of samples and",
"scheduler sched = optim.lr_scheduler.StepLR(optimizer = opt, step_size = 200, gamma = 0.1) oldLoss",
"num_batches = int(math.ceil(num_samples/minibatch_size)) #Vector for the found protoimage latent vectors protoLatents = torch.zeros(num_samples,num_dims)",
"= discrimScore.mean() + Lambda*cosSim(ynew,og_x).mean() #Backpropagate the error loss.backward() #Take a step with the",
"diff = y - x #Show the progress # if i % 1",
"(diff.norm(dim=1).unsqueeze(1)**2)))) ynew = utils.normalize(ynew) #Get the images of the current latent vectors currImgs",
"than minibatch_size images left if (batch_num + 1) * minibatch_size > num_samples: end",
"minibatch_size #Original latent vectors x = og_latents[batch_num * minibatch_size: end].to(device) batch_size,_ = x.size()",
"= 0.0001, minibatch_size = 16): ''' Lambda: weight for the cosine similarity loss",
"the gradients opt.zero_grad() #Move the direction of the difference vector ynew = y",
"i % 1 == 0: # print('Iterations: ' + str(i)) # print('Loss: '",
"= y - x #Show the progress # if i % 1 ==",
"# print('Loss: ' + str(loss)) protoLatents[batch_num * minibatch_size: end] = ynew.detach().cpu() return protoLatents",
"are fewer than minibatch_size images left if (batch_num + 1) * minibatch_size >",
"device, lr = 0.1, Lambda = 3.0, epsilon = 0.0001, minibatch_size = 16):",
"= 0 for i in range(501): #Zero the gradients opt.zero_grad() #Move the direction",
"else: end = (batch_num + 1) * minibatch_size #Original latent vectors x =",
"= recovered_latents[batch_num * minibatch_size: end].to(device) #Put both on the device x = x.detach().requires_grad_(False).to(device)",
"(batch_num + 1) * minibatch_size #Original latent vectors x = og_latents[batch_num * minibatch_size:",
"(batch_num + 1) * minibatch_size > num_samples: end = num_samples + 1 else:",
"== 0: # print('Iterations: ' + str(i)) # print('Loss: ' + str(loss)) protoLatents[batch_num",
"= False) #Calculate the loss if model_type == 'wgangp': loss = discrimScore.mean() +",
"condition if abs(loss-oldLoss) < epsilon: break else: oldLoss = loss x = y",
"as optim import torch.nn as nn import math from tqdm import tqdm from",
"+ 1) * minibatch_size #Original latent vectors x = og_latents[batch_num * minibatch_size: end].to(device)",
"current latent vectors currImgs = model.netG(ynew) #Get the discriminator score discrimScore = model.netD(currImgs,getFeature",
"#Original latent vectors x = og_latents[batch_num * minibatch_size: end].to(device) batch_size,_ = x.size() #Recovered",
"= lr) cosSim = nn.CosineSimilarity() #Learning rate scheduler sched = optim.lr_scheduler.StepLR(optimizer = opt,",
"opt, step_size = 200, gamma = 0.1) oldLoss = 0 for i in",
"nn import math from tqdm import tqdm from . import utils #Optimization to",
"needed num_batches = int(math.ceil(num_samples/minibatch_size)) #Vector for the found protoimage latent vectors protoLatents =",
"= optim.Adam([alpha], lr = lr) cosSim = nn.CosineSimilarity() #Learning rate scheduler sched =",
"range(501): #Zero the gradients opt.zero_grad() #Move the direction of the difference vector ynew",
"- Find the protoimage vectors \"\"\" import torch import torch.optim as optim import",
"from tqdm import tqdm from . import utils #Optimization to get the protoimages",
"0.2*cosSim(ynew,og_x).mean() + 1.0*discrimScore.std() + 3.0*cosSim(ynew,og_x).std() else: loss = discrimScore.mean() + Lambda*cosSim(ynew,og_x).mean() #Backpropagate the",
"= y.detach().requires_grad_(False).to(device) og_x = x * 1.0 alpha = torch.ones(batch_size,512,device=device) alpha = alpha.requires_grad_(True)",
"200, gamma = 0.1) oldLoss = 0 for i in range(501): #Zero the",
"progress # if i % 1 == 0: # print('Iterations: ' + str(i))",
"a step with the optimizer opt.step() sched.step() #Early stopping condition if abs(loss-oldLoss) <",
"+ 0.2*cosSim(ynew,og_x).mean() + 1.0*discrimScore.std() + 3.0*cosSim(ynew,og_x).std() else: loss = discrimScore.mean() + Lambda*cosSim(ynew,og_x).mean() #Backpropagate",
"as nn import math from tqdm import tqdm from . import utils #Optimization",
"0 for i in range(501): #Zero the gradients opt.zero_grad() #Move the direction of",
"og_x = x * 1.0 alpha = torch.ones(batch_size,512,device=device) alpha = alpha.requires_grad_(True) #Initial direction",
"x.detach().requires_grad_(False).to(device) y = y.detach().requires_grad_(False).to(device) og_x = x * 1.0 alpha = torch.ones(batch_size,512,device=device) alpha",
"torch.nn as nn import math from tqdm import tqdm from . import utils",
"the device x = x.detach().requires_grad_(False).to(device) y = y.detach().requires_grad_(False).to(device) og_x = x * 1.0",
"= torch.ones(batch_size,512,device=device) alpha = alpha.requires_grad_(True) #Initial direction diff = y - x opt",
"(torch.mm(alpha,diff.t()).diagonal().unsqueeze(1) * ((diff / (diff.norm(dim=1).unsqueeze(1)**2)))) ynew = utils.normalize(ynew) #Get the images of the",
"utils #Optimization to get the protoimages def proto_optim(og_latents,recovered_latents, model, model_type, device, lr =",
"protoLatents = torch.zeros(num_samples,num_dims) for batch_num in tqdm(range(num_batches)): #Check if there are fewer than",
"int(math.ceil(num_samples/minibatch_size)) #Vector for the found protoimage latent vectors protoLatents = torch.zeros(num_samples,num_dims) for batch_num",
"epsilon = 0.0001, minibatch_size = 16): ''' Lambda: weight for the cosine similarity",
"similarity loss (3.0 for celeba_pgan, 5.0 for church_pgan, 10.0 for celebaHQ_pgan) ''' print('Searching",
"break else: oldLoss = loss x = y * 1.0 y = ynew.detach()",
"#Get the images of the current latent vectors currImgs = model.netG(ynew) #Get the",
"+ (torch.mm(alpha,diff.t()).diagonal().unsqueeze(1) * ((diff / (diff.norm(dim=1).unsqueeze(1)**2)))) ynew = utils.normalize(ynew) #Get the images of",
"utf-8 -*- \"\"\" Created on Thu Mar 4 08:24:48 2021 proto_optim.py - Find",
"def proto_optim(og_latents,recovered_latents, model, model_type, device, lr = 0.1, Lambda = 3.0, epsilon =",
"loss (3.0 for celeba_pgan, 5.0 for church_pgan, 10.0 for celebaHQ_pgan) ''' print('Searching for",
"y - x #Show the progress # if i % 1 == 0:",
"# if i % 1 == 0: # print('Iterations: ' + str(i)) #",
"Created on Thu Mar 4 08:24:48 2021 proto_optim.py - Find the protoimage vectors",
"#Calculate the loss if model_type == 'wgangp': loss = discrimScore.mean() + 0.2*cosSim(ynew,og_x).mean() +",
"tqdm(range(num_batches)): #Check if there are fewer than minibatch_size images left if (batch_num +",
"= int(math.ceil(num_samples/minibatch_size)) #Vector for the found protoimage latent vectors protoLatents = torch.zeros(num_samples,num_dims) for",
"from . import utils #Optimization to get the protoimages def proto_optim(og_latents,recovered_latents, model, model_type,",
"model_type == 'wgangp': loss = discrimScore.mean() + 0.2*cosSim(ynew,og_x).mean() + 1.0*discrimScore.std() + 3.0*cosSim(ynew,og_x).std() else:",
"1) * minibatch_size > num_samples: end = num_samples + 1 else: end =",
"ynew.detach() diff = y - x #Show the progress # if i %",
"celeba_pgan, 5.0 for church_pgan, 10.0 for celebaHQ_pgan) ''' print('Searching for the protoimage latent",
"2021 proto_optim.py - Find the protoimage vectors \"\"\" import torch import torch.optim as",
"vectors y = recovered_latents[batch_num * minibatch_size: end].to(device) #Put both on the device x",
"epsilon: break else: oldLoss = loss x = y * 1.0 y =",
"currImgs = model.netG(ynew) #Get the discriminator score discrimScore = model.netD(currImgs,getFeature = False) #Calculate",
"- x opt = optim.Adam([alpha], lr = lr) cosSim = nn.CosineSimilarity() #Learning rate",
"the current latent vectors currImgs = model.netG(ynew) #Get the discriminator score discrimScore =",
"if i % 1 == 0: # print('Iterations: ' + str(i)) # print('Loss:",
"num_dims = og_latents.size() #Number of batches needed num_batches = int(math.ceil(num_samples/minibatch_size)) #Vector for the",
"end = num_samples + 1 else: end = (batch_num + 1) * minibatch_size",
"for i in range(501): #Zero the gradients opt.zero_grad() #Move the direction of the",
"if model_type == 'wgangp': loss = discrimScore.mean() + 0.2*cosSim(ynew,og_x).mean() + 1.0*discrimScore.std() + 3.0*cosSim(ynew,og_x).std()",
"-*- \"\"\" Created on Thu Mar 4 08:24:48 2021 proto_optim.py - Find the",
"cosine similarity loss (3.0 for celeba_pgan, 5.0 for church_pgan, 10.0 for celebaHQ_pgan) '''",
"0.1) oldLoss = 0 for i in range(501): #Zero the gradients opt.zero_grad() #Move",
"4 08:24:48 2021 proto_optim.py - Find the protoimage vectors \"\"\" import torch import",
"#Backpropagate the error loss.backward() #Take a step with the optimizer opt.step() sched.step() #Early",
"ynew = y + (torch.mm(alpha,diff.t()).diagonal().unsqueeze(1) * ((diff / (diff.norm(dim=1).unsqueeze(1)**2)))) ynew = utils.normalize(ynew) #Get",
"#Check if there are fewer than minibatch_size images left if (batch_num + 1)",
"gamma = 0.1) oldLoss = 0 for i in range(501): #Zero the gradients",
"((diff / (diff.norm(dim=1).unsqueeze(1)**2)))) ynew = utils.normalize(ynew) #Get the images of the current latent",
"latent vectors currImgs = model.netG(ynew) #Get the discriminator score discrimScore = model.netD(currImgs,getFeature =",
"= torch.zeros(num_samples,num_dims) for batch_num in tqdm(range(num_batches)): #Check if there are fewer than minibatch_size",
"1.0*discrimScore.std() + 3.0*cosSim(ynew,og_x).std() else: loss = discrimScore.mean() + Lambda*cosSim(ynew,og_x).mean() #Backpropagate the error loss.backward()",
"y = ynew.detach() diff = y - x #Show the progress # if",
"+ Lambda*cosSim(ynew,og_x).mean() #Backpropagate the error loss.backward() #Take a step with the optimizer opt.step()",
"else: oldLoss = loss x = y * 1.0 y = ynew.detach() diff",
"the cosine similarity loss (3.0 for celeba_pgan, 5.0 for church_pgan, 10.0 for celebaHQ_pgan)",
"model_type, device, lr = 0.1, Lambda = 3.0, epsilon = 0.0001, minibatch_size =",
"abs(loss-oldLoss) < epsilon: break else: oldLoss = loss x = y * 1.0",
"num_samples: end = num_samples + 1 else: end = (batch_num + 1) *",
"on the device x = x.detach().requires_grad_(False).to(device) y = y.detach().requires_grad_(False).to(device) og_x = x *",
"latent vectors x = og_latents[batch_num * minibatch_size: end].to(device) batch_size,_ = x.size() #Recovered latent",
"torch.ones(batch_size,512,device=device) alpha = alpha.requires_grad_(True) #Initial direction diff = y - x opt =",
"08:24:48 2021 proto_optim.py - Find the protoimage vectors \"\"\" import torch import torch.optim",
"#Early stopping condition if abs(loss-oldLoss) < epsilon: break else: oldLoss = loss x",
"== 'wgangp': loss = discrimScore.mean() + 0.2*cosSim(ynew,og_x).mean() + 1.0*discrimScore.std() + 3.0*cosSim(ynew,og_x).std() else: loss",
"+ 1.0*discrimScore.std() + 3.0*cosSim(ynew,og_x).std() else: loss = discrimScore.mean() + Lambda*cosSim(ynew,og_x).mean() #Backpropagate the error",
"for the cosine similarity loss (3.0 for celeba_pgan, 5.0 for church_pgan, 10.0 for",
"* ((diff / (diff.norm(dim=1).unsqueeze(1)**2)))) ynew = utils.normalize(ynew) #Get the images of the current",
"= x.detach().requires_grad_(False).to(device) y = y.detach().requires_grad_(False).to(device) og_x = x * 1.0 alpha = torch.ones(batch_size,512,device=device)",
"protoimages def proto_optim(og_latents,recovered_latents, model, model_type, device, lr = 0.1, Lambda = 3.0, epsilon",
"-*- coding: utf-8 -*- \"\"\" Created on Thu Mar 4 08:24:48 2021 proto_optim.py",
"= ynew.detach() diff = y - x #Show the progress # if i",
"+ 1) * minibatch_size > num_samples: end = num_samples + 1 else: end",
"= og_latents.size() #Number of batches needed num_batches = int(math.ceil(num_samples/minibatch_size)) #Vector for the found",
"for church_pgan, 10.0 for celebaHQ_pgan) ''' print('Searching for the protoimage latent vector...') #Get",
"#!/usr/bin/env python3 # -*- coding: utf-8 -*- \"\"\" Created on Thu Mar 4",
"16): ''' Lambda: weight for the cosine similarity loss (3.0 for celeba_pgan, 5.0",
"the number of samples and the dimensionality num_samples, num_dims = og_latents.size() #Number of",
"False) #Calculate the loss if model_type == 'wgangp': loss = discrimScore.mean() + 0.2*cosSim(ynew,og_x).mean()",
"= x * 1.0 alpha = torch.ones(batch_size,512,device=device) alpha = alpha.requires_grad_(True) #Initial direction diff",
"error loss.backward() #Take a step with the optimizer opt.step() sched.step() #Early stopping condition",
"* 1.0 y = ynew.detach() diff = y - x #Show the progress",
"for celeba_pgan, 5.0 for church_pgan, 10.0 for celebaHQ_pgan) ''' print('Searching for the protoimage",
"0: # print('Iterations: ' + str(i)) # print('Loss: ' + str(loss)) protoLatents[batch_num *",
"< epsilon: break else: oldLoss = loss x = y * 1.0 y",
"vector ynew = y + (torch.mm(alpha,diff.t()).diagonal().unsqueeze(1) * ((diff / (diff.norm(dim=1).unsqueeze(1)**2)))) ynew = utils.normalize(ynew)",
"* 1.0 alpha = torch.ones(batch_size,512,device=device) alpha = alpha.requires_grad_(True) #Initial direction diff = y",
"alpha = alpha.requires_grad_(True) #Initial direction diff = y - x opt = optim.Adam([alpha],",
"gradients opt.zero_grad() #Move the direction of the difference vector ynew = y +",
"oldLoss = 0 for i in range(501): #Zero the gradients opt.zero_grad() #Move the",
"end = (batch_num + 1) * minibatch_size #Original latent vectors x = og_latents[batch_num",
"print('Iterations: ' + str(i)) # print('Loss: ' + str(loss)) protoLatents[batch_num * minibatch_size: end]",
"python3 # -*- coding: utf-8 -*- \"\"\" Created on Thu Mar 4 08:24:48",
"stopping condition if abs(loss-oldLoss) < epsilon: break else: oldLoss = loss x =",
"model.netG(ynew) #Get the discriminator score discrimScore = model.netD(currImgs,getFeature = False) #Calculate the loss",
"1) * minibatch_size #Original latent vectors x = og_latents[batch_num * minibatch_size: end].to(device) batch_size,_",
"import math from tqdm import tqdm from . import utils #Optimization to get",
"optimizer opt.step() sched.step() #Early stopping condition if abs(loss-oldLoss) < epsilon: break else: oldLoss",
"loss if model_type == 'wgangp': loss = discrimScore.mean() + 0.2*cosSim(ynew,og_x).mean() + 1.0*discrimScore.std() +",
"import torch.optim as optim import torch.nn as nn import math from tqdm import",
"discrimScore = model.netD(currImgs,getFeature = False) #Calculate the loss if model_type == 'wgangp': loss",
"#Vector for the found protoimage latent vectors protoLatents = torch.zeros(num_samples,num_dims) for batch_num in",
"optim import torch.nn as nn import math from tqdm import tqdm from .",
"num_samples + 1 else: end = (batch_num + 1) * minibatch_size #Original latent",
"import torch import torch.optim as optim import torch.nn as nn import math from",
"#Initial direction diff = y - x opt = optim.Adam([alpha], lr = lr)",
"(3.0 for celeba_pgan, 5.0 for church_pgan, 10.0 for celebaHQ_pgan) ''' print('Searching for the",
"import tqdm from . import utils #Optimization to get the protoimages def proto_optim(og_latents,recovered_latents,",
"#Number of batches needed num_batches = int(math.ceil(num_samples/minibatch_size)) #Vector for the found protoimage latent",
"#Optimization to get the protoimages def proto_optim(og_latents,recovered_latents, model, model_type, device, lr = 0.1,",
"= utils.normalize(ynew) #Get the images of the current latent vectors currImgs = model.netG(ynew)",
"torch.zeros(num_samples,num_dims) for batch_num in tqdm(range(num_batches)): #Check if there are fewer than minibatch_size images",
"alpha = torch.ones(batch_size,512,device=device) alpha = alpha.requires_grad_(True) #Initial direction diff = y - x",
"latent vectors protoLatents = torch.zeros(num_samples,num_dims) for batch_num in tqdm(range(num_batches)): #Check if there are",
"if abs(loss-oldLoss) < epsilon: break else: oldLoss = loss x = y *",
"5.0 for church_pgan, 10.0 for celebaHQ_pgan) ''' print('Searching for the protoimage latent vector...')",
"* minibatch_size: end].to(device) #Put both on the device x = x.detach().requires_grad_(False).to(device) y =",
"the protoimages def proto_optim(og_latents,recovered_latents, model, model_type, device, lr = 0.1, Lambda = 3.0,",
"loss.backward() #Take a step with the optimizer opt.step() sched.step() #Early stopping condition if",
"'wgangp': loss = discrimScore.mean() + 0.2*cosSim(ynew,og_x).mean() + 1.0*discrimScore.std() + 3.0*cosSim(ynew,og_x).std() else: loss =",
"vectors x = og_latents[batch_num * minibatch_size: end].to(device) batch_size,_ = x.size() #Recovered latent vectors",
"x #Show the progress # if i % 1 == 0: # print('Iterations:",
"the dimensionality num_samples, num_dims = og_latents.size() #Number of batches needed num_batches = int(math.ceil(num_samples/minibatch_size))",
"end].to(device) batch_size,_ = x.size() #Recovered latent vectors y = recovered_latents[batch_num * minibatch_size: end].to(device)",
"of samples and the dimensionality num_samples, num_dims = og_latents.size() #Number of batches needed",
"for celebaHQ_pgan) ''' print('Searching for the protoimage latent vector...') #Get the number of",
"in range(501): #Zero the gradients opt.zero_grad() #Move the direction of the difference vector",
"there are fewer than minibatch_size images left if (batch_num + 1) * minibatch_size",
"weight for the cosine similarity loss (3.0 for celeba_pgan, 5.0 for church_pgan, 10.0",
"Lambda*cosSim(ynew,og_x).mean() #Backpropagate the error loss.backward() #Take a step with the optimizer opt.step() sched.step()",
"on Thu Mar 4 08:24:48 2021 proto_optim.py - Find the protoimage vectors \"\"\"",
"protoimage latent vectors protoLatents = torch.zeros(num_samples,num_dims) for batch_num in tqdm(range(num_batches)): #Check if there",
". import utils #Optimization to get the protoimages def proto_optim(og_latents,recovered_latents, model, model_type, device,",
"latent vectors y = recovered_latents[batch_num * minibatch_size: end].to(device) #Put both on the device",
"optim.lr_scheduler.StepLR(optimizer = opt, step_size = 200, gamma = 0.1) oldLoss = 0 for",
"of the current latent vectors currImgs = model.netG(ynew) #Get the discriminator score discrimScore",
"the discriminator score discrimScore = model.netD(currImgs,getFeature = False) #Calculate the loss if model_type",
"left if (batch_num + 1) * minibatch_size > num_samples: end = num_samples +",
"dimensionality num_samples, num_dims = og_latents.size() #Number of batches needed num_batches = int(math.ceil(num_samples/minibatch_size)) #Vector",
"+ 1 else: end = (batch_num + 1) * minibatch_size #Original latent vectors",
"opt = optim.Adam([alpha], lr = lr) cosSim = nn.CosineSimilarity() #Learning rate scheduler sched",
"lr = 0.1, Lambda = 3.0, epsilon = 0.0001, minibatch_size = 16): '''",
"with the optimizer opt.step() sched.step() #Early stopping condition if abs(loss-oldLoss) < epsilon: break",
"of batches needed num_batches = int(math.ceil(num_samples/minibatch_size)) #Vector for the found protoimage latent vectors",
"the difference vector ynew = y + (torch.mm(alpha,diff.t()).diagonal().unsqueeze(1) * ((diff / (diff.norm(dim=1).unsqueeze(1)**2)))) ynew",
"else: loss = discrimScore.mean() + Lambda*cosSim(ynew,og_x).mean() #Backpropagate the error loss.backward() #Take a step",
"vectors \"\"\" import torch import torch.optim as optim import torch.nn as nn import",
"end].to(device) #Put both on the device x = x.detach().requires_grad_(False).to(device) y = y.detach().requires_grad_(False).to(device) og_x",
"direction diff = y - x opt = optim.Adam([alpha], lr = lr) cosSim",
"model, model_type, device, lr = 0.1, Lambda = 3.0, epsilon = 0.0001, minibatch_size",
"1.0 y = ynew.detach() diff = y - x #Show the progress #",
"#Get the number of samples and the dimensionality num_samples, num_dims = og_latents.size() #Number",
"#Show the progress # if i % 1 == 0: # print('Iterations: '",
"* minibatch_size > num_samples: end = num_samples + 1 else: end = (batch_num",
"opt.step() sched.step() #Early stopping condition if abs(loss-oldLoss) < epsilon: break else: oldLoss =",
"minibatch_size = 16): ''' Lambda: weight for the cosine similarity loss (3.0 for",
"church_pgan, 10.0 for celebaHQ_pgan) ''' print('Searching for the protoimage latent vector...') #Get the",
"= og_latents[batch_num * minibatch_size: end].to(device) batch_size,_ = x.size() #Recovered latent vectors y =",
"y - x opt = optim.Adam([alpha], lr = lr) cosSim = nn.CosineSimilarity() #Learning",
"#Learning rate scheduler sched = optim.lr_scheduler.StepLR(optimizer = opt, step_size = 200, gamma =",
"device x = x.detach().requires_grad_(False).to(device) y = y.detach().requires_grad_(False).to(device) og_x = x * 1.0 alpha",
"proto_optim.py - Find the protoimage vectors \"\"\" import torch import torch.optim as optim",
"x opt = optim.Adam([alpha], lr = lr) cosSim = nn.CosineSimilarity() #Learning rate scheduler",
"the progress # if i % 1 == 0: # print('Iterations: ' +",
"= model.netD(currImgs,getFeature = False) #Calculate the loss if model_type == 'wgangp': loss =",
"= nn.CosineSimilarity() #Learning rate scheduler sched = optim.lr_scheduler.StepLR(optimizer = opt, step_size = 200,",
"x * 1.0 alpha = torch.ones(batch_size,512,device=device) alpha = alpha.requires_grad_(True) #Initial direction diff =",
"torch import torch.optim as optim import torch.nn as nn import math from tqdm",
"\"\"\" import torch import torch.optim as optim import torch.nn as nn import math",
"lr = lr) cosSim = nn.CosineSimilarity() #Learning rate scheduler sched = optim.lr_scheduler.StepLR(optimizer =",
"x = y * 1.0 y = ynew.detach() diff = y - x",
"lr) cosSim = nn.CosineSimilarity() #Learning rate scheduler sched = optim.lr_scheduler.StepLR(optimizer = opt, step_size",
"rate scheduler sched = optim.lr_scheduler.StepLR(optimizer = opt, step_size = 200, gamma = 0.1)",
"* minibatch_size #Original latent vectors x = og_latents[batch_num * minibatch_size: end].to(device) batch_size,_ =",
"diff = y - x opt = optim.Adam([alpha], lr = lr) cosSim =",
"oldLoss = loss x = y * 1.0 y = ynew.detach() diff =",
"> num_samples: end = num_samples + 1 else: end = (batch_num + 1)",
"to get the protoimages def proto_optim(og_latents,recovered_latents, model, model_type, device, lr = 0.1, Lambda",
"* minibatch_size: end].to(device) batch_size,_ = x.size() #Recovered latent vectors y = recovered_latents[batch_num *",
"= 200, gamma = 0.1) oldLoss = 0 for i in range(501): #Zero",
"Lambda: weight for the cosine similarity loss (3.0 for celeba_pgan, 5.0 for church_pgan,",
"= y * 1.0 y = ynew.detach() diff = y - x #Show",
"batch_num in tqdm(range(num_batches)): #Check if there are fewer than minibatch_size images left if",
"#Move the direction of the difference vector ynew = y + (torch.mm(alpha,diff.t()).diagonal().unsqueeze(1) *",
"the optimizer opt.step() sched.step() #Early stopping condition if abs(loss-oldLoss) < epsilon: break else:",
"import utils #Optimization to get the protoimages def proto_optim(og_latents,recovered_latents, model, model_type, device, lr",
"minibatch_size > num_samples: end = num_samples + 1 else: end = (batch_num +",
"+ str(i)) # print('Loss: ' + str(loss)) protoLatents[batch_num * minibatch_size: end] = ynew.detach().cpu()",
"#Take a step with the optimizer opt.step() sched.step() #Early stopping condition if abs(loss-oldLoss)",
"number of samples and the dimensionality num_samples, num_dims = og_latents.size() #Number of batches",
"for the found protoimage latent vectors protoLatents = torch.zeros(num_samples,num_dims) for batch_num in tqdm(range(num_batches)):",
"3.0*cosSim(ynew,og_x).std() else: loss = discrimScore.mean() + Lambda*cosSim(ynew,og_x).mean() #Backpropagate the error loss.backward() #Take a",
"% 1 == 0: # print('Iterations: ' + str(i)) # print('Loss: ' +",
"direction of the difference vector ynew = y + (torch.mm(alpha,diff.t()).diagonal().unsqueeze(1) * ((diff /",
"= alpha.requires_grad_(True) #Initial direction diff = y - x opt = optim.Adam([alpha], lr",
"and the dimensionality num_samples, num_dims = og_latents.size() #Number of batches needed num_batches =",
"y + (torch.mm(alpha,diff.t()).diagonal().unsqueeze(1) * ((diff / (diff.norm(dim=1).unsqueeze(1)**2)))) ynew = utils.normalize(ynew) #Get the images",
"nn.CosineSimilarity() #Learning rate scheduler sched = optim.lr_scheduler.StepLR(optimizer = opt, step_size = 200, gamma",
"for batch_num in tqdm(range(num_batches)): #Check if there are fewer than minibatch_size images left",
"tqdm from . import utils #Optimization to get the protoimages def proto_optim(og_latents,recovered_latents, model,",
"= 16): ''' Lambda: weight for the cosine similarity loss (3.0 for celeba_pgan,",
"the images of the current latent vectors currImgs = model.netG(ynew) #Get the discriminator",
"the error loss.backward() #Take a step with the optimizer opt.step() sched.step() #Early stopping",
"str(i)) # print('Loss: ' + str(loss)) protoLatents[batch_num * minibatch_size: end] = ynew.detach().cpu() return",
"\"\"\" Created on Thu Mar 4 08:24:48 2021 proto_optim.py - Find the protoimage",
"sched = optim.lr_scheduler.StepLR(optimizer = opt, step_size = 200, gamma = 0.1) oldLoss =",
"of the difference vector ynew = y + (torch.mm(alpha,diff.t()).diagonal().unsqueeze(1) * ((diff / (diff.norm(dim=1).unsqueeze(1)**2))))",
"celebaHQ_pgan) ''' print('Searching for the protoimage latent vector...') #Get the number of samples",
"discrimScore.mean() + Lambda*cosSim(ynew,og_x).mean() #Backpropagate the error loss.backward() #Take a step with the optimizer"
] |
[
"def start(self): temp_value = '' while True: recent_value = paste() if recent_value !=",
"self.notify = Notify() self.dest = dest self.src = src def start(self): temp_value =",
"recent_value = paste() if recent_value != temp_value: try: result = self.translate.translate(recent_value, dest=self.dest, src=self.src)",
"True: recent_value = paste() if recent_value != temp_value: try: result = self.translate.translate(recent_value, dest=self.dest,",
"Translation: def __init__(self, dest, src): self.translate = Translator() self.notify = Notify() self.dest =",
"__init__(self, dest, src): self.translate = Translator() self.notify = Notify() self.dest = dest self.src",
"= Translator() self.notify = Notify() self.dest = dest self.src = src def start(self):",
"from .notify import Notify from googletrans import Translator from time import sleep from",
"temp_value = '' while True: recent_value = paste() if recent_value != temp_value: try:",
"from xerox import paste class Translation: def __init__(self, dest, src): self.translate = Translator()",
"src): self.translate = Translator() self.notify = Notify() self.dest = dest self.src = src",
"from time import sleep from xerox import paste class Translation: def __init__(self, dest,",
"= Notify() self.dest = dest self.src = src def start(self): temp_value = ''",
"self.translate.translate(recent_value, dest=self.dest, src=self.src) self.notify.send(recent_value, result.text) except Exception as e: self.notify.send('A Problem Occurred', str(e))",
"paste() if recent_value != temp_value: try: result = self.translate.translate(recent_value, dest=self.dest, src=self.src) self.notify.send(recent_value, result.text)",
"recent_value != temp_value: try: result = self.translate.translate(recent_value, dest=self.dest, src=self.src) self.notify.send(recent_value, result.text) except Exception",
"start(self): temp_value = '' while True: recent_value = paste() if recent_value != temp_value:",
"src def start(self): temp_value = '' while True: recent_value = paste() if recent_value",
"Translator() self.notify = Notify() self.dest = dest self.src = src def start(self): temp_value",
"'' while True: recent_value = paste() if recent_value != temp_value: try: result =",
"= dest self.src = src def start(self): temp_value = '' while True: recent_value",
"import sleep from xerox import paste class Translation: def __init__(self, dest, src): self.translate",
"while True: recent_value = paste() if recent_value != temp_value: try: result = self.translate.translate(recent_value,",
"import Translator from time import sleep from xerox import paste class Translation: def",
"import paste class Translation: def __init__(self, dest, src): self.translate = Translator() self.notify =",
"time import sleep from xerox import paste class Translation: def __init__(self, dest, src):",
"temp_value: try: result = self.translate.translate(recent_value, dest=self.dest, src=self.src) self.notify.send(recent_value, result.text) except Exception as e:",
"= self.translate.translate(recent_value, dest=self.dest, src=self.src) self.notify.send(recent_value, result.text) except Exception as e: self.notify.send('A Problem Occurred',",
"= paste() if recent_value != temp_value: try: result = self.translate.translate(recent_value, dest=self.dest, src=self.src) self.notify.send(recent_value,",
"self.notify.send(recent_value, result.text) except Exception as e: self.notify.send('A Problem Occurred', str(e)) temp_value = recent_value",
"self.src = src def start(self): temp_value = '' while True: recent_value = paste()",
"googletrans import Translator from time import sleep from xerox import paste class Translation:",
"sleep from xerox import paste class Translation: def __init__(self, dest, src): self.translate =",
"def __init__(self, dest, src): self.translate = Translator() self.notify = Notify() self.dest = dest",
"try: result = self.translate.translate(recent_value, dest=self.dest, src=self.src) self.notify.send(recent_value, result.text) except Exception as e: self.notify.send('A",
"dest, src): self.translate = Translator() self.notify = Notify() self.dest = dest self.src =",
"Notify from googletrans import Translator from time import sleep from xerox import paste",
"import Notify from googletrans import Translator from time import sleep from xerox import",
"result = self.translate.translate(recent_value, dest=self.dest, src=self.src) self.notify.send(recent_value, result.text) except Exception as e: self.notify.send('A Problem",
"= '' while True: recent_value = paste() if recent_value != temp_value: try: result",
".notify import Notify from googletrans import Translator from time import sleep from xerox",
"dest=self.dest, src=self.src) self.notify.send(recent_value, result.text) except Exception as e: self.notify.send('A Problem Occurred', str(e)) temp_value",
"result.text) except Exception as e: self.notify.send('A Problem Occurred', str(e)) temp_value = recent_value sleep(2)",
"= src def start(self): temp_value = '' while True: recent_value = paste() if",
"dest self.src = src def start(self): temp_value = '' while True: recent_value =",
"!= temp_value: try: result = self.translate.translate(recent_value, dest=self.dest, src=self.src) self.notify.send(recent_value, result.text) except Exception as",
"paste class Translation: def __init__(self, dest, src): self.translate = Translator() self.notify = Notify()",
"class Translation: def __init__(self, dest, src): self.translate = Translator() self.notify = Notify() self.dest",
"self.dest = dest self.src = src def start(self): temp_value = '' while True:",
"if recent_value != temp_value: try: result = self.translate.translate(recent_value, dest=self.dest, src=self.src) self.notify.send(recent_value, result.text) except",
"Notify() self.dest = dest self.src = src def start(self): temp_value = '' while",
"self.translate = Translator() self.notify = Notify() self.dest = dest self.src = src def",
"from googletrans import Translator from time import sleep from xerox import paste class",
"xerox import paste class Translation: def __init__(self, dest, src): self.translate = Translator() self.notify",
"<reponame>emregeldegul/tfc from .notify import Notify from googletrans import Translator from time import sleep",
"Translator from time import sleep from xerox import paste class Translation: def __init__(self,",
"src=self.src) self.notify.send(recent_value, result.text) except Exception as e: self.notify.send('A Problem Occurred', str(e)) temp_value ="
] |
[
"return infos infos = read_txt(train_list_file, split_type=' ') for info in infos: txt_file, use_flag",
"读取txt文件的标注信息,格式为 xxx/a/1.png,a xxx/a/2.png,a Args: txt_path: train/valid/test data txt or json Returns: imgs:list, all",
"all data info ''' with open(txt_path, 'r', encoding='utf-8') as f: infos = list(map(lambda",
"for info in infos: txt_file, use_flag = info if int(use_flag) == 1: with",
"= fid_train.readlines() for line in lines: line = line.strip().split('\\t') keys += line[-1] infos",
"'./key.txt' fid_key = open(keys_file, 'a+', encoding='utf-8') keys = '' def read_txt(txt_path, split_type): '''",
"'' def read_txt(txt_path, split_type): ''' 读取txt文件的标注信息,格式为 xxx/a/1.png,a xxx/a/2.png,a Args: txt_path: train/valid/test data txt",
"json Returns: imgs:list, all data info ''' with open(txt_path, 'r', encoding='utf-8') as f:",
"Returns: imgs:list, all data info ''' with open(txt_path, 'r', encoding='utf-8') as f: infos",
"= info if int(use_flag) == 1: with open(txt_file, 'r', encoding='utf-8') as fid_train: lines",
"f)) return infos infos = read_txt(train_list_file, split_type=' ') for info in infos: txt_file,",
"use_flag = info if int(use_flag) == 1: with open(txt_file, 'r', encoding='utf-8') as fid_train:",
"line in lines: line = line.strip().split('\\t') keys += line[-1] infos = read_txt(test_list_file, split_type='",
"keys = '' def read_txt(txt_path, split_type): ''' 读取txt文件的标注信息,格式为 xxx/a/1.png,a xxx/a/2.png,a Args: txt_path: train/valid/test",
"lines = fid_train.readlines() for line in lines: line = line.strip().split('\\t') keys += line[-1]",
"read_txt(txt_path, split_type): ''' 读取txt文件的标注信息,格式为 xxx/a/1.png,a xxx/a/2.png,a Args: txt_path: train/valid/test data txt or json",
"int(use_flag) == 1: with open(txt_file, 'r', encoding='utf-8') as fid_train: lines = fid_train.readlines() for",
"split_type): ''' 读取txt文件的标注信息,格式为 xxx/a/1.png,a xxx/a/2.png,a Args: txt_path: train/valid/test data txt or json Returns:",
"list(map(lambda line: line.strip().split(split_type), f)) return infos infos = read_txt(train_list_file, split_type=' ') for info",
": zzf-jeff train_list_file = '../test/train_rec_05.txt' test_list_file = '../test/test_rec_05.txt' keys_file = './key.txt' fid_key =",
"txt_path: train/valid/test data txt or json Returns: imgs:list, all data info ''' with",
"@Time : 2021/5/11 11:20 # @Auto : zzf-jeff train_list_file = '../test/train_rec_05.txt' test_list_file =",
"= read_txt(test_list_file, split_type=' ') for info in infos: txt_file, use_flag = info if",
"fid_train.readlines() for line in lines: line = line.strip().split('\\t') keys += line[-1] infos =",
"1: with open(txt_file, 'r', encoding='utf-8') as fid_train: lines = fid_train.readlines() for line in",
"infos infos = read_txt(train_list_file, split_type=' ') for info in infos: txt_file, use_flag =",
"if int(use_flag) == 1: with open(txt_file, 'r', encoding='utf-8') as fid_train: lines = fid_train.readlines()",
"coding=utf-8 # @Time : 2021/5/11 11:20 # @Auto : zzf-jeff train_list_file = '../test/train_rec_05.txt'",
": 2021/5/11 11:20 # @Auto : zzf-jeff train_list_file = '../test/train_rec_05.txt' test_list_file = '../test/test_rec_05.txt'",
"split_type=' ') for info in infos: txt_file, use_flag = info if int(use_flag) ==",
"# @Time : 2021/5/11 11:20 # @Auto : zzf-jeff train_list_file = '../test/train_rec_05.txt' test_list_file",
"as f: infos = list(map(lambda line: line.strip().split(split_type), f)) return infos infos = read_txt(train_list_file,",
"info ''' with open(txt_path, 'r', encoding='utf-8') as f: infos = list(map(lambda line: line.strip().split(split_type),",
"# coding=utf-8 # @Time : 2021/5/11 11:20 # @Auto : zzf-jeff train_list_file =",
"= '../test/train_rec_05.txt' test_list_file = '../test/test_rec_05.txt' keys_file = './key.txt' fid_key = open(keys_file, 'a+', encoding='utf-8')",
"Args: txt_path: train/valid/test data txt or json Returns: imgs:list, all data info '''",
"or json Returns: imgs:list, all data info ''' with open(txt_path, 'r', encoding='utf-8') as",
"open(txt_path, 'r', encoding='utf-8') as f: infos = list(map(lambda line: line.strip().split(split_type), f)) return infos",
"read_txt(test_list_file, split_type=' ') for info in infos: txt_file, use_flag = info if int(use_flag)",
"line.strip().split('\\t') keys += line[-1] infos = read_txt(test_list_file, split_type=' ') for info in infos:",
"# @Auto : zzf-jeff train_list_file = '../test/train_rec_05.txt' test_list_file = '../test/test_rec_05.txt' keys_file = './key.txt'",
"f: infos = list(map(lambda line: line.strip().split(split_type), f)) return infos infos = read_txt(train_list_file, split_type='",
"test_list_file = '../test/test_rec_05.txt' keys_file = './key.txt' fid_key = open(keys_file, 'a+', encoding='utf-8') keys =",
"infos = read_txt(test_list_file, split_type=' ') for info in infos: txt_file, use_flag = info",
"'r', encoding='utf-8') as f: infos = list(map(lambda line: line.strip().split(split_type), f)) return infos infos",
"keys += line[-1] infos = read_txt(test_list_file, split_type=' ') for info in infos: txt_file,",
"= fid_train.readlines() for line in lines: line = line.strip().split('\\t') keys += line[-1] key",
"line.strip().split(split_type), f)) return infos infos = read_txt(train_list_file, split_type=' ') for info in infos:",
"for line in lines: line = line.strip().split('\\t') keys += line[-1] key = ''.join(list(set(list(keys))))",
"= './key.txt' fid_key = open(keys_file, 'a+', encoding='utf-8') keys = '' def read_txt(txt_path, split_type):",
"'a+', encoding='utf-8') keys = '' def read_txt(txt_path, split_type): ''' 读取txt文件的标注信息,格式为 xxx/a/1.png,a xxx/a/2.png,a Args:",
"2021/5/11 11:20 # @Auto : zzf-jeff train_list_file = '../test/train_rec_05.txt' test_list_file = '../test/test_rec_05.txt' keys_file",
"encoding='utf-8') keys = '' def read_txt(txt_path, split_type): ''' 读取txt文件的标注信息,格式为 xxx/a/1.png,a xxx/a/2.png,a Args: txt_path:",
"'../test/train_rec_05.txt' test_list_file = '../test/test_rec_05.txt' keys_file = './key.txt' fid_key = open(keys_file, 'a+', encoding='utf-8') keys",
"= '../test/test_rec_05.txt' keys_file = './key.txt' fid_key = open(keys_file, 'a+', encoding='utf-8') keys = ''",
"= line.strip().split('\\t') keys += line[-1] infos = read_txt(test_list_file, split_type=' ') for info in",
"in lines: line = line.strip().split('\\t') keys += line[-1] key = ''.join(list(set(list(keys)))) for _key",
"keys_file = './key.txt' fid_key = open(keys_file, 'a+', encoding='utf-8') keys = '' def read_txt(txt_path,",
"11:20 # @Auto : zzf-jeff train_list_file = '../test/train_rec_05.txt' test_list_file = '../test/test_rec_05.txt' keys_file =",
"''' with open(txt_path, 'r', encoding='utf-8') as f: infos = list(map(lambda line: line.strip().split(split_type), f))",
"txt_file, use_flag = info if int(use_flag) == 1: with open(txt_file, 'r', encoding='utf-8') as",
"open(keys_file, 'a+', encoding='utf-8') keys = '' def read_txt(txt_path, split_type): ''' 读取txt文件的标注信息,格式为 xxx/a/1.png,a xxx/a/2.png,a",
"infos = read_txt(train_list_file, split_type=' ') for info in infos: txt_file, use_flag = info",
"fid_train: lines = fid_train.readlines() for line in lines: line = line.strip().split('\\t') keys +=",
"with open(txt_file, 'r', encoding='utf-8') as fid_train: lines = fid_train.readlines() for line in lines:",
"= line.strip().split('\\t') keys += line[-1] key = ''.join(list(set(list(keys)))) for _key in key: fid_key.write(_key",
"+= line[-1] infos = read_txt(test_list_file, split_type=' ') for info in infos: txt_file, use_flag",
"encoding='utf-8') as f: infos = list(map(lambda line: line.strip().split(split_type), f)) return infos infos =",
"zzf-jeff train_list_file = '../test/train_rec_05.txt' test_list_file = '../test/test_rec_05.txt' keys_file = './key.txt' fid_key = open(keys_file,",
"keys += line[-1] key = ''.join(list(set(list(keys)))) for _key in key: fid_key.write(_key + '\\n')",
"for line in lines: line = line.strip().split('\\t') keys += line[-1] infos = read_txt(test_list_file,",
"line[-1] infos = read_txt(test_list_file, split_type=' ') for info in infos: txt_file, use_flag =",
"fid_train.readlines() for line in lines: line = line.strip().split('\\t') keys += line[-1] key =",
"line = line.strip().split('\\t') keys += line[-1] key = ''.join(list(set(list(keys)))) for _key in key:",
"line in lines: line = line.strip().split('\\t') keys += line[-1] key = ''.join(list(set(list(keys)))) for",
"'../test/test_rec_05.txt' keys_file = './key.txt' fid_key = open(keys_file, 'a+', encoding='utf-8') keys = '' def",
"info if int(use_flag) == 1: with open(txt_file, 'r', encoding='utf-8') as fid_train: lines =",
"info in infos: txt_file, use_flag = info if int(use_flag) == 1: with open(txt_file,",
"in infos: txt_file, use_flag = info if int(use_flag) == 1: with open(txt_file, 'r',",
"@Auto : zzf-jeff train_list_file = '../test/train_rec_05.txt' test_list_file = '../test/test_rec_05.txt' keys_file = './key.txt' fid_key",
"imgs:list, all data info ''' with open(txt_path, 'r', encoding='utf-8') as f: infos =",
"xxx/a/1.png,a xxx/a/2.png,a Args: txt_path: train/valid/test data txt or json Returns: imgs:list, all data",
"read_txt(train_list_file, split_type=' ') for info in infos: txt_file, use_flag = info if int(use_flag)",
"encoding='utf-8') as fid_train: lines = fid_train.readlines() for line in lines: line = line.strip().split('\\t')",
"txt or json Returns: imgs:list, all data info ''' with open(txt_path, 'r', encoding='utf-8')",
"line.strip().split('\\t') keys += line[-1] key = ''.join(list(set(list(keys)))) for _key in key: fid_key.write(_key +",
"fid_key = open(keys_file, 'a+', encoding='utf-8') keys = '' def read_txt(txt_path, split_type): ''' 读取txt文件的标注信息,格式为",
"') for info in infos: txt_file, use_flag = info if int(use_flag) == 1:",
"train/valid/test data txt or json Returns: imgs:list, all data info ''' with open(txt_path,",
"''' 读取txt文件的标注信息,格式为 xxx/a/1.png,a xxx/a/2.png,a Args: txt_path: train/valid/test data txt or json Returns: imgs:list,",
"data info ''' with open(txt_path, 'r', encoding='utf-8') as f: infos = list(map(lambda line:",
"def read_txt(txt_path, split_type): ''' 读取txt文件的标注信息,格式为 xxx/a/1.png,a xxx/a/2.png,a Args: txt_path: train/valid/test data txt or",
"= '' def read_txt(txt_path, split_type): ''' 读取txt文件的标注信息,格式为 xxx/a/1.png,a xxx/a/2.png,a Args: txt_path: train/valid/test data",
"data txt or json Returns: imgs:list, all data info ''' with open(txt_path, 'r',",
"= open(keys_file, 'a+', encoding='utf-8') keys = '' def read_txt(txt_path, split_type): ''' 读取txt文件的标注信息,格式为 xxx/a/1.png,a",
"train_list_file = '../test/train_rec_05.txt' test_list_file = '../test/test_rec_05.txt' keys_file = './key.txt' fid_key = open(keys_file, 'a+',",
"line: line.strip().split(split_type), f)) return infos infos = read_txt(train_list_file, split_type=' ') for info in",
"with open(txt_path, 'r', encoding='utf-8') as f: infos = list(map(lambda line: line.strip().split(split_type), f)) return",
"lines: line = line.strip().split('\\t') keys += line[-1] infos = read_txt(test_list_file, split_type=' ') for",
"= list(map(lambda line: line.strip().split(split_type), f)) return infos infos = read_txt(train_list_file, split_type=' ') for",
"in lines: line = line.strip().split('\\t') keys += line[-1] infos = read_txt(test_list_file, split_type=' ')",
"== 1: with open(txt_file, 'r', encoding='utf-8') as fid_train: lines = fid_train.readlines() for line",
"infos = list(map(lambda line: line.strip().split(split_type), f)) return infos infos = read_txt(train_list_file, split_type=' ')",
"infos: txt_file, use_flag = info if int(use_flag) == 1: with open(txt_file, 'r', encoding='utf-8')",
"'r', encoding='utf-8') as fid_train: lines = fid_train.readlines() for line in lines: line =",
"xxx/a/2.png,a Args: txt_path: train/valid/test data txt or json Returns: imgs:list, all data info",
"line = line.strip().split('\\t') keys += line[-1] infos = read_txt(test_list_file, split_type=' ') for info",
"as fid_train: lines = fid_train.readlines() for line in lines: line = line.strip().split('\\t') keys",
"= read_txt(train_list_file, split_type=' ') for info in infos: txt_file, use_flag = info if",
"open(txt_file, 'r', encoding='utf-8') as fid_train: lines = fid_train.readlines() for line in lines: line",
"lines: line = line.strip().split('\\t') keys += line[-1] key = ''.join(list(set(list(keys)))) for _key in"
] |
[
"bblfsh_sonar_checks.utils as utils import bblfsh def check(uast): findings = [] fin_calls = bblfsh.filter(uast,",
"= bblfsh.filter(uast, \"//MethodInvocation//\" \"Identifier[@roleCall and @roleReceiver and @Name='System']/parent::MethodInvocation/\" \"Identifier[@roleCall and @roleCallee and @Name='gc']/parent::MethodInvocation\")",
"if len(list(fin_calls)): findings.append({\"msg\": \"Don't use Runtime.getRuntime().gc(})\", \"pos\": None}) return findings if __name__ ==",
"findings = [] fin_calls = bblfsh.filter(uast, \"//MethodInvocation//\" \"Identifier[@roleCall and @roleReceiver and @Name='System']/parent::MethodInvocation/\" \"Identifier[@roleCall",
"and @Name='System']/parent::MethodInvocation/\" \"Identifier[@roleCall and @roleCallee and @Name='gc']/parent::MethodInvocation\") if len(list(fin_calls)): findings.append({\"msg\": \"Don't use System.gc()\",",
"use System.gc()\", \"pos\": None}) fin_calls = bblfsh.filter(uast, \"//MethodInvocation//\" \"Identifier[@roleCall and @roleReceiver and @Name='Runtime']/parent::MethodInvocation//\"",
"if len(list(fin_calls)): findings.append({\"msg\": \"Don't use System.gc()\", \"pos\": None}) fin_calls = bblfsh.filter(uast, \"//MethodInvocation//\" \"Identifier[@roleCall",
"bblfsh.filter(uast, \"//MethodInvocation//\" \"Identifier[@roleCall and @roleReceiver and @Name='Runtime']/parent::MethodInvocation//\" \"Identifier[@roleCall and @roleCallee and @Name='getRuntime']/parent::MethodInvocation/parent::MethodInvocation//\" \"Identifier[@roleCall",
"\"//MethodInvocation//\" \"Identifier[@roleCall and @roleReceiver and @Name='Runtime']/parent::MethodInvocation//\" \"Identifier[@roleCall and @roleCallee and @Name='getRuntime']/parent::MethodInvocation/parent::MethodInvocation//\" \"Identifier[@roleCall and",
"@Name='gc']/parent::MethodInvocation\") if len(list(fin_calls)): findings.append({\"msg\": \"Don't use Runtime.getRuntime().gc(})\", \"pos\": None}) return findings if __name__",
"@roleReceiver and @Name='System']/parent::MethodInvocation/\" \"Identifier[@roleCall and @roleCallee and @Name='gc']/parent::MethodInvocation\") if len(list(fin_calls)): findings.append({\"msg\": \"Don't use",
"def check(uast): findings = [] fin_calls = bblfsh.filter(uast, \"//MethodInvocation//\" \"Identifier[@roleCall and @roleReceiver and",
"and @roleCallee and @Name='getRuntime']/parent::MethodInvocation/parent::MethodInvocation//\" \"Identifier[@roleCall and @roleCallee and @Name='gc']/parent::MethodInvocation\") if len(list(fin_calls)): findings.append({\"msg\": \"Don't",
"and @Name='gc']/parent::MethodInvocation\") if len(list(fin_calls)): findings.append({\"msg\": \"Don't use System.gc()\", \"pos\": None}) fin_calls = bblfsh.filter(uast,",
"and @Name='getRuntime']/parent::MethodInvocation/parent::MethodInvocation//\" \"Identifier[@roleCall and @roleCallee and @Name='gc']/parent::MethodInvocation\") if len(list(fin_calls)): findings.append({\"msg\": \"Don't use Runtime.getRuntime().gc(})\",",
"= [] fin_calls = bblfsh.filter(uast, \"//MethodInvocation//\" \"Identifier[@roleCall and @roleReceiver and @Name='System']/parent::MethodInvocation/\" \"Identifier[@roleCall and",
"\"pos\": None}) fin_calls = bblfsh.filter(uast, \"//MethodInvocation//\" \"Identifier[@roleCall and @roleReceiver and @Name='Runtime']/parent::MethodInvocation//\" \"Identifier[@roleCall and",
"= bblfsh.filter(uast, \"//MethodInvocation//\" \"Identifier[@roleCall and @roleReceiver and @Name='Runtime']/parent::MethodInvocation//\" \"Identifier[@roleCall and @roleCallee and @Name='getRuntime']/parent::MethodInvocation/parent::MethodInvocation//\"",
"and @roleCallee and @Name='gc']/parent::MethodInvocation\") if len(list(fin_calls)): findings.append({\"msg\": \"Don't use Runtime.getRuntime().gc(})\", \"pos\": None}) return",
"\"Identifier[@roleCall and @roleCallee and @Name='gc']/parent::MethodInvocation\") if len(list(fin_calls)): findings.append({\"msg\": \"Don't use Runtime.getRuntime().gc(})\", \"pos\": None})",
"bblfsh def check(uast): findings = [] fin_calls = bblfsh.filter(uast, \"//MethodInvocation//\" \"Identifier[@roleCall and @roleReceiver",
"as utils import bblfsh def check(uast): findings = [] fin_calls = bblfsh.filter(uast, \"//MethodInvocation//\"",
"@roleReceiver and @Name='Runtime']/parent::MethodInvocation//\" \"Identifier[@roleCall and @roleCallee and @Name='getRuntime']/parent::MethodInvocation/parent::MethodInvocation//\" \"Identifier[@roleCall and @roleCallee and @Name='gc']/parent::MethodInvocation\")",
"findings.append({\"msg\": \"Don't use Runtime.getRuntime().gc(})\", \"pos\": None}) return findings if __name__ == '__main__': utils.run_default_fixture(__file__,",
"@Name='gc']/parent::MethodInvocation\") if len(list(fin_calls)): findings.append({\"msg\": \"Don't use System.gc()\", \"pos\": None}) fin_calls = bblfsh.filter(uast, \"//MethodInvocation//\"",
"findings.append({\"msg\": \"Don't use System.gc()\", \"pos\": None}) fin_calls = bblfsh.filter(uast, \"//MethodInvocation//\" \"Identifier[@roleCall and @roleReceiver",
"import bblfsh def check(uast): findings = [] fin_calls = bblfsh.filter(uast, \"//MethodInvocation//\" \"Identifier[@roleCall and",
"and @roleReceiver and @Name='Runtime']/parent::MethodInvocation//\" \"Identifier[@roleCall and @roleCallee and @Name='getRuntime']/parent::MethodInvocation/parent::MethodInvocation//\" \"Identifier[@roleCall and @roleCallee and",
"bblfsh.filter(uast, \"//MethodInvocation//\" \"Identifier[@roleCall and @roleReceiver and @Name='System']/parent::MethodInvocation/\" \"Identifier[@roleCall and @roleCallee and @Name='gc']/parent::MethodInvocation\") if",
"@Name='getRuntime']/parent::MethodInvocation/parent::MethodInvocation//\" \"Identifier[@roleCall and @roleCallee and @Name='gc']/parent::MethodInvocation\") if len(list(fin_calls)): findings.append({\"msg\": \"Don't use Runtime.getRuntime().gc(})\", \"pos\":",
"[] fin_calls = bblfsh.filter(uast, \"//MethodInvocation//\" \"Identifier[@roleCall and @roleReceiver and @Name='System']/parent::MethodInvocation/\" \"Identifier[@roleCall and @roleCallee",
"None}) fin_calls = bblfsh.filter(uast, \"//MethodInvocation//\" \"Identifier[@roleCall and @roleReceiver and @Name='Runtime']/parent::MethodInvocation//\" \"Identifier[@roleCall and @roleCallee",
"and @Name='Runtime']/parent::MethodInvocation//\" \"Identifier[@roleCall and @roleCallee and @Name='getRuntime']/parent::MethodInvocation/parent::MethodInvocation//\" \"Identifier[@roleCall and @roleCallee and @Name='gc']/parent::MethodInvocation\") if",
"fin_calls = bblfsh.filter(uast, \"//MethodInvocation//\" \"Identifier[@roleCall and @roleReceiver and @Name='System']/parent::MethodInvocation/\" \"Identifier[@roleCall and @roleCallee and",
"check(uast): findings = [] fin_calls = bblfsh.filter(uast, \"//MethodInvocation//\" \"Identifier[@roleCall and @roleReceiver and @Name='System']/parent::MethodInvocation/\"",
"@roleCallee and @Name='gc']/parent::MethodInvocation\") if len(list(fin_calls)): findings.append({\"msg\": \"Don't use System.gc()\", \"pos\": None}) fin_calls =",
"len(list(fin_calls)): findings.append({\"msg\": \"Don't use Runtime.getRuntime().gc(})\", \"pos\": None}) return findings if __name__ == '__main__':",
"System.gc()\", \"pos\": None}) fin_calls = bblfsh.filter(uast, \"//MethodInvocation//\" \"Identifier[@roleCall and @roleReceiver and @Name='Runtime']/parent::MethodInvocation//\" \"Identifier[@roleCall",
"fin_calls = bblfsh.filter(uast, \"//MethodInvocation//\" \"Identifier[@roleCall and @roleReceiver and @Name='Runtime']/parent::MethodInvocation//\" \"Identifier[@roleCall and @roleCallee and",
"\"Identifier[@roleCall and @roleReceiver and @Name='System']/parent::MethodInvocation/\" \"Identifier[@roleCall and @roleCallee and @Name='gc']/parent::MethodInvocation\") if len(list(fin_calls)): findings.append({\"msg\":",
"and @roleReceiver and @Name='System']/parent::MethodInvocation/\" \"Identifier[@roleCall and @roleCallee and @Name='gc']/parent::MethodInvocation\") if len(list(fin_calls)): findings.append({\"msg\": \"Don't",
"@Name='Runtime']/parent::MethodInvocation//\" \"Identifier[@roleCall and @roleCallee and @Name='getRuntime']/parent::MethodInvocation/parent::MethodInvocation//\" \"Identifier[@roleCall and @roleCallee and @Name='gc']/parent::MethodInvocation\") if len(list(fin_calls)):",
"@roleCallee and @Name='gc']/parent::MethodInvocation\") if len(list(fin_calls)): findings.append({\"msg\": \"Don't use Runtime.getRuntime().gc(})\", \"pos\": None}) return findings",
"@Name='System']/parent::MethodInvocation/\" \"Identifier[@roleCall and @roleCallee and @Name='gc']/parent::MethodInvocation\") if len(list(fin_calls)): findings.append({\"msg\": \"Don't use System.gc()\", \"pos\":",
"and @roleCallee and @Name='gc']/parent::MethodInvocation\") if len(list(fin_calls)): findings.append({\"msg\": \"Don't use System.gc()\", \"pos\": None}) fin_calls",
"len(list(fin_calls)): findings.append({\"msg\": \"Don't use System.gc()\", \"pos\": None}) fin_calls = bblfsh.filter(uast, \"//MethodInvocation//\" \"Identifier[@roleCall and",
"@roleCallee and @Name='getRuntime']/parent::MethodInvocation/parent::MethodInvocation//\" \"Identifier[@roleCall and @roleCallee and @Name='gc']/parent::MethodInvocation\") if len(list(fin_calls)): findings.append({\"msg\": \"Don't use",
"\"Don't use System.gc()\", \"pos\": None}) fin_calls = bblfsh.filter(uast, \"//MethodInvocation//\" \"Identifier[@roleCall and @roleReceiver and",
"and @Name='gc']/parent::MethodInvocation\") if len(list(fin_calls)): findings.append({\"msg\": \"Don't use Runtime.getRuntime().gc(})\", \"pos\": None}) return findings if",
"import bblfsh_sonar_checks.utils as utils import bblfsh def check(uast): findings = [] fin_calls =",
"utils import bblfsh def check(uast): findings = [] fin_calls = bblfsh.filter(uast, \"//MethodInvocation//\" \"Identifier[@roleCall",
"\"Identifier[@roleCall and @roleReceiver and @Name='Runtime']/parent::MethodInvocation//\" \"Identifier[@roleCall and @roleCallee and @Name='getRuntime']/parent::MethodInvocation/parent::MethodInvocation//\" \"Identifier[@roleCall and @roleCallee",
"\"Don't use Runtime.getRuntime().gc(})\", \"pos\": None}) return findings if __name__ == '__main__': utils.run_default_fixture(__file__, check)",
"\"//MethodInvocation//\" \"Identifier[@roleCall and @roleReceiver and @Name='System']/parent::MethodInvocation/\" \"Identifier[@roleCall and @roleCallee and @Name='gc']/parent::MethodInvocation\") if len(list(fin_calls)):",
"\"Identifier[@roleCall and @roleCallee and @Name='gc']/parent::MethodInvocation\") if len(list(fin_calls)): findings.append({\"msg\": \"Don't use System.gc()\", \"pos\": None})",
"\"Identifier[@roleCall and @roleCallee and @Name='getRuntime']/parent::MethodInvocation/parent::MethodInvocation//\" \"Identifier[@roleCall and @roleCallee and @Name='gc']/parent::MethodInvocation\") if len(list(fin_calls)): findings.append({\"msg\":"
] |
[] |
[
"<reponame>Sp-X/PCAP class One: def do_it(self): print(\"do_it from One\") def doanything(self): self.do_it() class Two(One):",
"def do_it(self): print(\"do_it from One\") def doanything(self): self.do_it() class Two(One): def do_it(self): print(\"do_it",
"One: def do_it(self): print(\"do_it from One\") def doanything(self): self.do_it() class Two(One): def do_it(self):",
"do_it(self): print(\"do_it from One\") def doanything(self): self.do_it() class Two(One): def do_it(self): print(\"do_it from",
"doanything(self): self.do_it() class Two(One): def do_it(self): print(\"do_it from Two\") one = One() two",
"def doanything(self): self.do_it() class Two(One): def do_it(self): print(\"do_it from Two\") one = One()",
"Two(One): def do_it(self): print(\"do_it from Two\") one = One() two = Two() one.doanything()",
"print(\"do_it from One\") def doanything(self): self.do_it() class Two(One): def do_it(self): print(\"do_it from Two\")",
"One\") def doanything(self): self.do_it() class Two(One): def do_it(self): print(\"do_it from Two\") one =",
"class Two(One): def do_it(self): print(\"do_it from Two\") one = One() two = Two()",
"def do_it(self): print(\"do_it from Two\") one = One() two = Two() one.doanything() two.doanything()",
"self.do_it() class Two(One): def do_it(self): print(\"do_it from Two\") one = One() two =",
"from One\") def doanything(self): self.do_it() class Two(One): def do_it(self): print(\"do_it from Two\") one",
"class One: def do_it(self): print(\"do_it from One\") def doanything(self): self.do_it() class Two(One): def"
] |
[
"# # Licensed under the Apache License, Version 2.0 (the \"License\"); # you",
"writing, software # distributed under the License is distributed on an \"AS IS\"",
"permissions and # limitations under the License. # import json import logging \"\"\"",
"path \"\"\" f = open(self.path, \"r\") self.manifest_json = f.read() def parse(self): \"\"\" Parses",
"KIND, either express or implied. # See the License for the specific language",
"Unless required by applicable law or agreed to in writing, software # distributed",
"You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 #",
"the License is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR",
"# See the License for the specific language governing permissions and # limitations",
"License. # You may obtain a copy of the License at # #",
"the list of metrics associated with the plugin manifest \"\"\" return self.manifest['metrics'] def",
"logging.debug(self.manifest) return self.manifest['name'] @property def param_array(self): return self.manifest['paramArray'] @property def post_extract(self): return self.manifest['postExtract']",
"@property def ignore(self): return self.manifest['ignore'] @property def metrics(self): return self.manifest['metrics'] @property def name(self):",
"and provides access to a plugin.json file the manifest of plugins. \"\"\" class",
"language governing permissions and # limitations under the License. # import json import",
"load(self): \"\"\" Read the JSON file and parse into a dictionary \"\"\" self.read()",
"def command_lua(self): return self.manifest['command_lua'] @property def description(self): return self.manifest['description'] @property def icon(self): return",
"PluginManifest(object): def __init__(self, path=\"plugin.json\"): \"\"\" Initialize the PluginManifest instance \"\"\" self.path = path",
"= open(self.path, \"r\") self.manifest_json = f.read() def parse(self): \"\"\" Parses the manifest JSON",
"self.manifest['tags'] @property def version(self): return self.manifest['version'] def get_manifest(self): \"\"\" Returns the dictionary from",
"law or agreed to in writing, software # distributed under the License is",
"# limitations under the License. # import json import logging \"\"\" Reads and",
"self.path = path self.manifest_json = None self.manifest = None def get_metric_names(self): \"\"\" Returns",
"the License for the specific language governing permissions and # limitations under the",
"specific language governing permissions and # limitations under the License. # import json",
"from the given path \"\"\" f = open(self.path, \"r\") self.manifest_json = f.read() def",
"compliance with the License. # You may obtain a copy of the License",
"f = open(self.path, \"r\") self.manifest_json = f.read() def parse(self): \"\"\" Parses the manifest",
"a dictionary \"\"\" self.manifest = json.loads(self.manifest_json) def load(self): \"\"\" Read the JSON file",
"@property def command_lua(self): return self.manifest['command_lua'] @property def description(self): return self.manifest['description'] @property def icon(self):",
"the plugin manifest \"\"\" return self.manifest['metrics'] def read(self): \"\"\" Load the metrics file",
"file from the given path \"\"\" f = open(self.path, \"r\") self.manifest_json = f.read()",
"on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,",
"limitations under the License. # import json import logging \"\"\" Reads and provides",
"this file except in compliance with the License. # You may obtain a",
"self.manifest_json = None self.manifest = None def get_metric_names(self): \"\"\" Returns the list of",
"def post_extract(self): return self.manifest['postExtract'] @property def post_extract_lua(self): return self.manifest['postExtract_lua'] @property def tags(self): return",
"Returns the list of metrics associated with the plugin manifest \"\"\" return self.manifest['metrics']",
"the Apache License, Version 2.0 (the \"License\"); # you may not use this",
"import logging \"\"\" Reads and provides access to a plugin.json file the manifest",
"self.manifest['paramArray'] @property def post_extract(self): return self.manifest['postExtract'] @property def post_extract_lua(self): return self.manifest['postExtract_lua'] @property def",
"you may not use this file except in compliance with the License. #",
"the given path \"\"\" f = open(self.path, \"r\") self.manifest_json = f.read() def parse(self):",
"self.manifest['version'] def get_manifest(self): \"\"\" Returns the dictionary from the parse JSON plugin manifest",
"@property def metrics(self): return self.manifest['metrics'] @property def name(self): logging.debug(self.manifest) return self.manifest['name'] @property def",
"of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable",
"self.manifest['ignore'] @property def metrics(self): return self.manifest['metrics'] @property def name(self): logging.debug(self.manifest) return self.manifest['name'] @property",
"def get_manifest(self): \"\"\" Returns the dictionary from the parse JSON plugin manifest \"\"\"",
"ANY KIND, either express or implied. # See the License for the specific",
"def param_array(self): return self.manifest['paramArray'] @property def post_extract(self): return self.manifest['postExtract'] @property def post_extract_lua(self): return",
"to a plugin.json file the manifest of plugins. \"\"\" class PluginManifest(object): def __init__(self,",
"BMC Software, Inc. # # Licensed under the Apache License, Version 2.0 (the",
"the PluginManifest instance \"\"\" self.path = path self.manifest_json = None self.manifest = None",
"in compliance with the License. # You may obtain a copy of the",
"def version(self): return self.manifest['version'] def get_manifest(self): \"\"\" Returns the dictionary from the parse",
"License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or",
"\"\"\" f = open(self.path, \"r\") self.manifest_json = f.read() def parse(self): \"\"\" Parses the",
"\"r\") self.manifest_json = f.read() def parse(self): \"\"\" Parses the manifest JSON into a",
"ignore(self): return self.manifest['ignore'] @property def metrics(self): return self.manifest['metrics'] @property def name(self): logging.debug(self.manifest) return",
"# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. #",
"the JSON file and parse into a dictionary \"\"\" self.read() self.parse() @property def",
"use this file except in compliance with the License. # You may obtain",
"\"\"\" Reads and provides access to a plugin.json file the manifest of plugins.",
"the manifest JSON into a dictionary \"\"\" self.manifest = json.loads(self.manifest_json) def load(self): \"\"\"",
"def __init__(self, path=\"plugin.json\"): \"\"\" Initialize the PluginManifest instance \"\"\" self.path = path self.manifest_json",
"at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed",
"def post_extract_lua(self): return self.manifest['postExtract_lua'] @property def tags(self): return self.manifest['tags'] @property def version(self): return",
"not use this file except in compliance with the License. # You may",
"governing permissions and # limitations under the License. # import json import logging",
"icon(self): return self.manifest['icon'] @property def ignore(self): return self.manifest['ignore'] @property def metrics(self): return self.manifest['metrics']",
"WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See",
"of plugins. \"\"\" class PluginManifest(object): def __init__(self, path=\"plugin.json\"): \"\"\" Initialize the PluginManifest instance",
"associated with the plugin manifest \"\"\" return self.manifest['metrics'] def read(self): \"\"\" Load the",
"\"\"\" return self.manifest['metrics'] def read(self): \"\"\" Load the metrics file from the given",
"self.manifest_json = f.read() def parse(self): \"\"\" Parses the manifest JSON into a dictionary",
"= json.loads(self.manifest_json) def load(self): \"\"\" Read the JSON file and parse into a",
"See the License for the specific language governing permissions and # limitations under",
"BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.",
"# Copyright 2015 BMC Software, Inc. # # Licensed under the Apache License,",
"return self.manifest['description'] @property def icon(self): return self.manifest['icon'] @property def ignore(self): return self.manifest['ignore'] @property",
"License, Version 2.0 (the \"License\"); # you may not use this file except",
"\"\"\" Returns the dictionary from the parse JSON plugin manifest \"\"\" return self.manifest",
"# Licensed under the Apache License, Version 2.0 (the \"License\"); # you may",
"return self.manifest['command_lua'] @property def description(self): return self.manifest['description'] @property def icon(self): return self.manifest['icon'] @property",
"License. # import json import logging \"\"\" Reads and provides access to a",
"self.read() self.parse() @property def command(self): return self.manifest['command'] @property def command_lua(self): return self.manifest['command_lua'] @property",
"IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or",
"and parse into a dictionary \"\"\" self.read() self.parse() @property def command(self): return self.manifest['command']",
"def load(self): \"\"\" Read the JSON file and parse into a dictionary \"\"\"",
"a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required",
"def get_metric_names(self): \"\"\" Returns the list of metrics associated with the plugin manifest",
"distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY",
"return self.manifest['version'] def get_manifest(self): \"\"\" Returns the dictionary from the parse JSON plugin",
"# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in",
"post_extract_lua(self): return self.manifest['postExtract_lua'] @property def tags(self): return self.manifest['tags'] @property def version(self): return self.manifest['version']",
"Initialize the PluginManifest instance \"\"\" self.path = path self.manifest_json = None self.manifest =",
"return self.manifest['postExtract'] @property def post_extract_lua(self): return self.manifest['postExtract_lua'] @property def tags(self): return self.manifest['tags'] @property",
"self.manifest['command'] @property def command_lua(self): return self.manifest['command_lua'] @property def description(self): return self.manifest['description'] @property def",
"OF ANY KIND, either express or implied. # See the License for the",
"# # Copyright 2015 BMC Software, Inc. # # Licensed under the Apache",
"__init__(self, path=\"plugin.json\"): \"\"\" Initialize the PluginManifest instance \"\"\" self.path = path self.manifest_json =",
"the manifest of plugins. \"\"\" class PluginManifest(object): def __init__(self, path=\"plugin.json\"): \"\"\" Initialize the",
"description(self): return self.manifest['description'] @property def icon(self): return self.manifest['icon'] @property def ignore(self): return self.manifest['ignore']",
"2.0 (the \"License\"); # you may not use this file except in compliance",
"JSON file and parse into a dictionary \"\"\" self.read() self.parse() @property def command(self):",
"return self.manifest['metrics'] def read(self): \"\"\" Load the metrics file from the given path",
"parse(self): \"\"\" Parses the manifest JSON into a dictionary \"\"\" self.manifest = json.loads(self.manifest_json)",
"f.read() def parse(self): \"\"\" Parses the manifest JSON into a dictionary \"\"\" self.manifest",
"\"\"\" Returns the list of metrics associated with the plugin manifest \"\"\" return",
"\"\"\" Initialize the PluginManifest instance \"\"\" self.path = path self.manifest_json = None self.manifest",
"# you may not use this file except in compliance with the License.",
"= path self.manifest_json = None self.manifest = None def get_metric_names(self): \"\"\" Returns the",
"version(self): return self.manifest['version'] def get_manifest(self): \"\"\" Returns the dictionary from the parse JSON",
"return self.manifest['paramArray'] @property def post_extract(self): return self.manifest['postExtract'] @property def post_extract_lua(self): return self.manifest['postExtract_lua'] @property",
"for the specific language governing permissions and # limitations under the License. #",
"@property def post_extract(self): return self.manifest['postExtract'] @property def post_extract_lua(self): return self.manifest['postExtract_lua'] @property def tags(self):",
"agreed to in writing, software # distributed under the License is distributed on",
"def description(self): return self.manifest['description'] @property def icon(self): return self.manifest['icon'] @property def ignore(self): return",
"tags(self): return self.manifest['tags'] @property def version(self): return self.manifest['version'] def get_manifest(self): \"\"\" Returns the",
"@property def post_extract_lua(self): return self.manifest['postExtract_lua'] @property def tags(self): return self.manifest['tags'] @property def version(self):",
"Software, Inc. # # Licensed under the Apache License, Version 2.0 (the \"License\");",
"the specific language governing permissions and # limitations under the License. # import",
"WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the",
"metrics(self): return self.manifest['metrics'] @property def name(self): logging.debug(self.manifest) return self.manifest['name'] @property def param_array(self): return",
"param_array(self): return self.manifest['paramArray'] @property def post_extract(self): return self.manifest['postExtract'] @property def post_extract_lua(self): return self.manifest['postExtract_lua']",
"None self.manifest = None def get_metric_names(self): \"\"\" Returns the list of metrics associated",
"= None self.manifest = None def get_metric_names(self): \"\"\" Returns the list of metrics",
"self.manifest = None def get_metric_names(self): \"\"\" Returns the list of metrics associated with",
"self.parse() @property def command(self): return self.manifest['command'] @property def command_lua(self): return self.manifest['command_lua'] @property def",
"(the \"License\"); # you may not use this file except in compliance with",
"PluginManifest instance \"\"\" self.path = path self.manifest_json = None self.manifest = None def",
"self.manifest['icon'] @property def ignore(self): return self.manifest['ignore'] @property def metrics(self): return self.manifest['metrics'] @property def",
"\"\"\" Parses the manifest JSON into a dictionary \"\"\" self.manifest = json.loads(self.manifest_json) def",
"= None def get_metric_names(self): \"\"\" Returns the list of metrics associated with the",
"dictionary \"\"\" self.read() self.parse() @property def command(self): return self.manifest['command'] @property def command_lua(self): return",
"# # Unless required by applicable law or agreed to in writing, software",
"self.manifest['name'] @property def param_array(self): return self.manifest['paramArray'] @property def post_extract(self): return self.manifest['postExtract'] @property def",
"express or implied. # See the License for the specific language governing permissions",
"Copyright 2015 BMC Software, Inc. # # Licensed under the Apache License, Version",
"Version 2.0 (the \"License\"); # you may not use this file except in",
"# Unless required by applicable law or agreed to in writing, software #",
"except in compliance with the License. # You may obtain a copy of",
"\"\"\" Read the JSON file and parse into a dictionary \"\"\" self.read() self.parse()",
"a plugin.json file the manifest of plugins. \"\"\" class PluginManifest(object): def __init__(self, path=\"plugin.json\"):",
"by applicable law or agreed to in writing, software # distributed under the",
"class PluginManifest(object): def __init__(self, path=\"plugin.json\"): \"\"\" Initialize the PluginManifest instance \"\"\" self.path =",
"read(self): \"\"\" Load the metrics file from the given path \"\"\" f =",
"plugins. \"\"\" class PluginManifest(object): def __init__(self, path=\"plugin.json\"): \"\"\" Initialize the PluginManifest instance \"\"\"",
"and # limitations under the License. # import json import logging \"\"\" Reads",
"Read the JSON file and parse into a dictionary \"\"\" self.read() self.parse() @property",
"copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by",
"def command(self): return self.manifest['command'] @property def command_lua(self): return self.manifest['command_lua'] @property def description(self): return",
"Parses the manifest JSON into a dictionary \"\"\" self.manifest = json.loads(self.manifest_json) def load(self):",
"either express or implied. # See the License for the specific language governing",
"@property def name(self): logging.debug(self.manifest) return self.manifest['name'] @property def param_array(self): return self.manifest['paramArray'] @property def",
"software # distributed under the License is distributed on an \"AS IS\" BASIS,",
"Inc. # # Licensed under the Apache License, Version 2.0 (the \"License\"); #",
"@property def param_array(self): return self.manifest['paramArray'] @property def post_extract(self): return self.manifest['postExtract'] @property def post_extract_lua(self):",
"# You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0",
"may not use this file except in compliance with the License. # You",
"License is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS",
"None def get_metric_names(self): \"\"\" Returns the list of metrics associated with the plugin",
"= f.read() def parse(self): \"\"\" Parses the manifest JSON into a dictionary \"\"\"",
"dictionary \"\"\" self.manifest = json.loads(self.manifest_json) def load(self): \"\"\" Read the JSON file and",
"a dictionary \"\"\" self.read() self.parse() @property def command(self): return self.manifest['command'] @property def command_lua(self):",
"@property def tags(self): return self.manifest['tags'] @property def version(self): return self.manifest['version'] def get_manifest(self): \"\"\"",
"Licensed under the Apache License, Version 2.0 (the \"License\"); # you may not",
"an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either",
"# # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to",
"given path \"\"\" f = open(self.path, \"r\") self.manifest_json = f.read() def parse(self): \"\"\"",
"return self.manifest['tags'] @property def version(self): return self.manifest['version'] def get_manifest(self): \"\"\" Returns the dictionary",
"with the plugin manifest \"\"\" return self.manifest['metrics'] def read(self): \"\"\" Load the metrics",
"command_lua(self): return self.manifest['command_lua'] @property def description(self): return self.manifest['description'] @property def icon(self): return self.manifest['icon']",
"return self.manifest['metrics'] @property def name(self): logging.debug(self.manifest) return self.manifest['name'] @property def param_array(self): return self.manifest['paramArray']",
"plugin.json file the manifest of plugins. \"\"\" class PluginManifest(object): def __init__(self, path=\"plugin.json\"): \"\"\"",
"file except in compliance with the License. # You may obtain a copy",
"\"\"\" self.manifest = json.loads(self.manifest_json) def load(self): \"\"\" Read the JSON file and parse",
"parse into a dictionary \"\"\" self.read() self.parse() @property def command(self): return self.manifest['command'] @property",
"self.manifest['description'] @property def icon(self): return self.manifest['icon'] @property def ignore(self): return self.manifest['ignore'] @property def",
"name(self): logging.debug(self.manifest) return self.manifest['name'] @property def param_array(self): return self.manifest['paramArray'] @property def post_extract(self): return",
"Reads and provides access to a plugin.json file the manifest of plugins. \"\"\"",
"self.manifest = json.loads(self.manifest_json) def load(self): \"\"\" Read the JSON file and parse into",
"plugin manifest \"\"\" return self.manifest['metrics'] def read(self): \"\"\" Load the metrics file from",
"provides access to a plugin.json file the manifest of plugins. \"\"\" class PluginManifest(object):",
"open(self.path, \"r\") self.manifest_json = f.read() def parse(self): \"\"\" Parses the manifest JSON into",
"metrics associated with the plugin manifest \"\"\" return self.manifest['metrics'] def read(self): \"\"\" Load",
"under the License is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES",
"path self.manifest_json = None self.manifest = None def get_metric_names(self): \"\"\" Returns the list",
"@property def icon(self): return self.manifest['icon'] @property def ignore(self): return self.manifest['ignore'] @property def metrics(self):",
"License for the specific language governing permissions and # limitations under the License.",
"@property def version(self): return self.manifest['version'] def get_manifest(self): \"\"\" Returns the dictionary from the",
"the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law",
"the License. # You may obtain a copy of the License at #",
"return self.manifest['postExtract_lua'] @property def tags(self): return self.manifest['tags'] @property def version(self): return self.manifest['version'] def",
"def name(self): logging.debug(self.manifest) return self.manifest['name'] @property def param_array(self): return self.manifest['paramArray'] @property def post_extract(self):",
"manifest \"\"\" return self.manifest['metrics'] def read(self): \"\"\" Load the metrics file from the",
"JSON into a dictionary \"\"\" self.manifest = json.loads(self.manifest_json) def load(self): \"\"\" Read the",
"to in writing, software # distributed under the License is distributed on an",
"of metrics associated with the plugin manifest \"\"\" return self.manifest['metrics'] def read(self): \"\"\"",
"\"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express",
"manifest JSON into a dictionary \"\"\" self.manifest = json.loads(self.manifest_json) def load(self): \"\"\" Read",
"self.manifest['metrics'] @property def name(self): logging.debug(self.manifest) return self.manifest['name'] @property def param_array(self): return self.manifest['paramArray'] @property",
"access to a plugin.json file the manifest of plugins. \"\"\" class PluginManifest(object): def",
"return self.manifest['command'] @property def command_lua(self): return self.manifest['command_lua'] @property def description(self): return self.manifest['description'] @property",
"# distributed under the License is distributed on an \"AS IS\" BASIS, #",
"implied. # See the License for the specific language governing permissions and #",
"\"\"\" Load the metrics file from the given path \"\"\" f = open(self.path,",
"Load the metrics file from the given path \"\"\" f = open(self.path, \"r\")",
"\"License\"); # you may not use this file except in compliance with the",
"metrics file from the given path \"\"\" f = open(self.path, \"r\") self.manifest_json =",
"is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF",
"obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless",
"return self.manifest['name'] @property def param_array(self): return self.manifest['paramArray'] @property def post_extract(self): return self.manifest['postExtract'] @property",
"required by applicable law or agreed to in writing, software # distributed under",
"def icon(self): return self.manifest['icon'] @property def ignore(self): return self.manifest['ignore'] @property def metrics(self): return",
"json import logging \"\"\" Reads and provides access to a plugin.json file the",
"get_metric_names(self): \"\"\" Returns the list of metrics associated with the plugin manifest \"\"\"",
"the metrics file from the given path \"\"\" f = open(self.path, \"r\") self.manifest_json",
"2015 BMC Software, Inc. # # Licensed under the Apache License, Version 2.0",
"under the License. # import json import logging \"\"\" Reads and provides access",
"def tags(self): return self.manifest['tags'] @property def version(self): return self.manifest['version'] def get_manifest(self): \"\"\" Returns",
"applicable law or agreed to in writing, software # distributed under the License",
"into a dictionary \"\"\" self.read() self.parse() @property def command(self): return self.manifest['command'] @property def",
"the License. # import json import logging \"\"\" Reads and provides access to",
"self.manifest['metrics'] def read(self): \"\"\" Load the metrics file from the given path \"\"\"",
"@property def description(self): return self.manifest['description'] @property def icon(self): return self.manifest['icon'] @property def ignore(self):",
"self.manifest['postExtract'] @property def post_extract_lua(self): return self.manifest['postExtract_lua'] @property def tags(self): return self.manifest['tags'] @property def",
"# import json import logging \"\"\" Reads and provides access to a plugin.json",
"list of metrics associated with the plugin manifest \"\"\" return self.manifest['metrics'] def read(self):",
"file the manifest of plugins. \"\"\" class PluginManifest(object): def __init__(self, path=\"plugin.json\"): \"\"\" Initialize",
"\"\"\" self.path = path self.manifest_json = None self.manifest = None def get_metric_names(self): \"\"\"",
"post_extract(self): return self.manifest['postExtract'] @property def post_extract_lua(self): return self.manifest['postExtract_lua'] @property def tags(self): return self.manifest['tags']",
"\"\"\" class PluginManifest(object): def __init__(self, path=\"plugin.json\"): \"\"\" Initialize the PluginManifest instance \"\"\" self.path",
"json.loads(self.manifest_json) def load(self): \"\"\" Read the JSON file and parse into a dictionary",
"or agreed to in writing, software # distributed under the License is distributed",
"or implied. # See the License for the specific language governing permissions and",
"get_manifest(self): \"\"\" Returns the dictionary from the parse JSON plugin manifest \"\"\" return",
"return self.manifest['icon'] @property def ignore(self): return self.manifest['ignore'] @property def metrics(self): return self.manifest['metrics'] @property",
"manifest of plugins. \"\"\" class PluginManifest(object): def __init__(self, path=\"plugin.json\"): \"\"\" Initialize the PluginManifest",
"@property def command(self): return self.manifest['command'] @property def command_lua(self): return self.manifest['command_lua'] @property def description(self):",
"def ignore(self): return self.manifest['ignore'] @property def metrics(self): return self.manifest['metrics'] @property def name(self): logging.debug(self.manifest)",
"distributed under the License is distributed on an \"AS IS\" BASIS, # WITHOUT",
"CONDITIONS OF ANY KIND, either express or implied. # See the License for",
"def read(self): \"\"\" Load the metrics file from the given path \"\"\" f",
"Apache License, Version 2.0 (the \"License\"); # you may not use this file",
"self.manifest['postExtract_lua'] @property def tags(self): return self.manifest['tags'] @property def version(self): return self.manifest['version'] def get_manifest(self):",
"def metrics(self): return self.manifest['metrics'] @property def name(self): logging.debug(self.manifest) return self.manifest['name'] @property def param_array(self):",
"import json import logging \"\"\" Reads and provides access to a plugin.json file",
"OR CONDITIONS OF ANY KIND, either express or implied. # See the License",
"may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # #",
"path=\"plugin.json\"): \"\"\" Initialize the PluginManifest instance \"\"\" self.path = path self.manifest_json = None",
"def parse(self): \"\"\" Parses the manifest JSON into a dictionary \"\"\" self.manifest =",
"command(self): return self.manifest['command'] @property def command_lua(self): return self.manifest['command_lua'] @property def description(self): return self.manifest['description']",
"\"\"\" self.read() self.parse() @property def command(self): return self.manifest['command'] @property def command_lua(self): return self.manifest['command_lua']",
"into a dictionary \"\"\" self.manifest = json.loads(self.manifest_json) def load(self): \"\"\" Read the JSON",
"return self.manifest['ignore'] @property def metrics(self): return self.manifest['metrics'] @property def name(self): logging.debug(self.manifest) return self.manifest['name']",
"with the License. # You may obtain a copy of the License at",
"http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing,",
"<filename>boundary/plugin_manifest.py<gh_stars>0 # # Copyright 2015 BMC Software, Inc. # # Licensed under the",
"logging \"\"\" Reads and provides access to a plugin.json file the manifest of",
"in writing, software # distributed under the License is distributed on an \"AS",
"instance \"\"\" self.path = path self.manifest_json = None self.manifest = None def get_metric_names(self):",
"file and parse into a dictionary \"\"\" self.read() self.parse() @property def command(self): return",
"self.manifest['command_lua'] @property def description(self): return self.manifest['description'] @property def icon(self): return self.manifest['icon'] @property def",
"under the Apache License, Version 2.0 (the \"License\"); # you may not use"
] |
[
"# # Licensed under the Apache License, Version 2.0 (the \"License\"); # you",
"writing, software # distributed under the License is distributed on an \"AS IS\"",
"rights reserved # # Licensed under the Apache License, Version 2.0 (the \"License\");",
"\"Jinja2>=2.7.2\", # terminal 'pycrypto', # ssh_key 'pyyaml', # cloudinit and rest 'xmltodict'] #",
"Unless required by applicable law or agreed to in writing, software # distributed",
"You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 #",
"express or implied. # * See the License for the specific language governing",
"License. # You may obtain a copy of the License at # #",
"License for the specific language governing permissions and # * limitations under the",
"# terminal \"Jinja2>=2.7.2\", # terminal 'pycrypto', # ssh_key 'pyyaml', # cloudinit and rest",
"law or agreed to in writing, software # distributed under the License is",
"compliance with the License. # You may obtain a copy of the License",
"OR CONDITIONS OF ANY KIND, either express or implied. # * See the",
"Copyright (c) 2017 GigaSpaces Technologies Ltd. All rights reserved # # Licensed under",
"'cloudify_terminal', 'cloudify_configuration', 'cloudify_custom_workflow', 'cloudify_suspend', 'cloudify_cloudinit', 'cloudify_rest', 'cloudify_rest/rest_sdk', 'cloudify_scalelist'], license='LICENSE', install_requires=[ 'cloudify-plugins-common>=3.4.2', 'cloudify-rest-client>=4.0', #",
"All rights reserved # # Licensed under the Apache License, Version 2.0 (the",
"author_email='<EMAIL>', description='Utilities for extending Cloudify', packages=['cloudify_deployment_proxy', 'cloudify_ssh_key', 'cloudify_files', 'cloudify_terminal', 'cloudify_configuration', 'cloudify_custom_workflow', 'cloudify_suspend', 'cloudify_cloudinit',",
"'cloudify_rest/rest_sdk', 'cloudify_scalelist'], license='LICENSE', install_requires=[ 'cloudify-plugins-common>=3.4.2', 'cloudify-rest-client>=4.0', # deployment_proxy 'paramiko', # terminal \"Jinja2>=2.7.2\", #",
"this file except in compliance with the License. # You may obtain a",
"the Apache License, Version 2.0 (the \"License\"); # you may not use this",
"extending Cloudify', packages=['cloudify_deployment_proxy', 'cloudify_ssh_key', 'cloudify_files', 'cloudify_terminal', 'cloudify_configuration', 'cloudify_custom_workflow', 'cloudify_suspend', 'cloudify_cloudinit', 'cloudify_rest', 'cloudify_rest/rest_sdk', 'cloudify_scalelist'],",
"you may not use this file except in compliance with the License. #",
"'cloudify_files', 'cloudify_terminal', 'cloudify_configuration', 'cloudify_custom_workflow', 'cloudify_suspend', 'cloudify_cloudinit', 'cloudify_rest', 'cloudify_rest/rest_sdk', 'cloudify_scalelist'], license='LICENSE', install_requires=[ 'cloudify-plugins-common>=3.4.2', 'cloudify-rest-client>=4.0',",
"'cloudify_cloudinit', 'cloudify_rest', 'cloudify_rest/rest_sdk', 'cloudify_scalelist'], license='LICENSE', install_requires=[ 'cloudify-plugins-common>=3.4.2', 'cloudify-rest-client>=4.0', # deployment_proxy 'paramiko', # terminal",
"of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable",
"import setuptools setuptools.setup( name='cloudify-utilities-plugin', version='1.9.6', author='<EMAIL>', author_email='<EMAIL>', description='Utilities for extending Cloudify', packages=['cloudify_deployment_proxy', 'cloudify_ssh_key',",
"2017 GigaSpaces Technologies Ltd. All rights reserved # # Licensed under the Apache",
"'cloudify-plugins-common>=3.4.2', 'cloudify-rest-client>=4.0', # deployment_proxy 'paramiko', # terminal \"Jinja2>=2.7.2\", # terminal 'pycrypto', # ssh_key",
"deployment_proxy 'paramiko', # terminal \"Jinja2>=2.7.2\", # terminal 'pycrypto', # ssh_key 'pyyaml', # cloudinit",
"in compliance with the License. # You may obtain a copy of the",
"License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or",
"on an \"AS IS\" BASIS, # * WITHOUT WARRANTIES OR CONDITIONS OF ANY",
"use this file except in compliance with the License. # You may obtain",
"'cloudify_custom_workflow', 'cloudify_suspend', 'cloudify_cloudinit', 'cloudify_rest', 'cloudify_rest/rest_sdk', 'cloudify_scalelist'], license='LICENSE', install_requires=[ 'cloudify-plugins-common>=3.4.2', 'cloudify-rest-client>=4.0', # deployment_proxy 'paramiko',",
"at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed",
"CONDITIONS OF ANY KIND, either express or implied. # * See the License",
"not use this file except in compliance with the License. # You may",
"distributed on an \"AS IS\" BASIS, # * WITHOUT WARRANTIES OR CONDITIONS OF",
"permissions and # * limitations under the License. import setuptools setuptools.setup( name='cloudify-utilities-plugin', version='1.9.6',",
"and # * limitations under the License. import setuptools setuptools.setup( name='cloudify-utilities-plugin', version='1.9.6', author='<EMAIL>',",
"setuptools setuptools.setup( name='cloudify-utilities-plugin', version='1.9.6', author='<EMAIL>', author_email='<EMAIL>', description='Utilities for extending Cloudify', packages=['cloudify_deployment_proxy', 'cloudify_ssh_key', 'cloudify_files',",
"License, Version 2.0 (the \"License\"); # you may not use this file except",
"the License is distributed on an \"AS IS\" BASIS, # * WITHOUT WARRANTIES",
"(c) 2017 GigaSpaces Technologies Ltd. All rights reserved # # Licensed under the",
"# Licensed under the Apache License, Version 2.0 (the \"License\"); # you may",
"* limitations under the License. import setuptools setuptools.setup( name='cloudify-utilities-plugin', version='1.9.6', author='<EMAIL>', author_email='<EMAIL>', description='Utilities",
"Technologies Ltd. All rights reserved # # Licensed under the Apache License, Version",
"a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required",
"\"AS IS\" BASIS, # * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either",
"limitations under the License. import setuptools setuptools.setup( name='cloudify-utilities-plugin', version='1.9.6', author='<EMAIL>', author_email='<EMAIL>', description='Utilities for",
"specific language governing permissions and # * limitations under the License. import setuptools",
"# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in",
"author='<EMAIL>', author_email='<EMAIL>', description='Utilities for extending Cloudify', packages=['cloudify_deployment_proxy', 'cloudify_ssh_key', 'cloudify_files', 'cloudify_terminal', 'cloudify_configuration', 'cloudify_custom_workflow', 'cloudify_suspend',",
"# deployment_proxy 'paramiko', # terminal \"Jinja2>=2.7.2\", # terminal 'pycrypto', # ssh_key 'pyyaml', #",
"'cloudify_rest', 'cloudify_rest/rest_sdk', 'cloudify_scalelist'], license='LICENSE', install_requires=[ 'cloudify-plugins-common>=3.4.2', 'cloudify-rest-client>=4.0', # deployment_proxy 'paramiko', # terminal \"Jinja2>=2.7.2\",",
"* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. #",
"2.0 (the \"License\"); # you may not use this file except in compliance",
"License. import setuptools setuptools.setup( name='cloudify-utilities-plugin', version='1.9.6', author='<EMAIL>', author_email='<EMAIL>', description='Utilities for extending Cloudify', packages=['cloudify_deployment_proxy',",
"# * See the License for the specific language governing permissions and #",
"# you may not use this file except in compliance with the License.",
"See the License for the specific language governing permissions and # * limitations",
"'cloudify_ssh_key', 'cloudify_files', 'cloudify_terminal', 'cloudify_configuration', 'cloudify_custom_workflow', 'cloudify_suspend', 'cloudify_cloudinit', 'cloudify_rest', 'cloudify_rest/rest_sdk', 'cloudify_scalelist'], license='LICENSE', install_requires=[ 'cloudify-plugins-common>=3.4.2',",
"agreed to in writing, software # distributed under the License is distributed on",
"'cloudify-rest-client>=4.0', # deployment_proxy 'paramiko', # terminal \"Jinja2>=2.7.2\", # terminal 'pycrypto', # ssh_key 'pyyaml',",
"* See the License for the specific language governing permissions and # *",
"for extending Cloudify', packages=['cloudify_deployment_proxy', 'cloudify_ssh_key', 'cloudify_files', 'cloudify_terminal', 'cloudify_configuration', 'cloudify_custom_workflow', 'cloudify_suspend', 'cloudify_cloudinit', 'cloudify_rest', 'cloudify_rest/rest_sdk',",
"description='Utilities for extending Cloudify', packages=['cloudify_deployment_proxy', 'cloudify_ssh_key', 'cloudify_files', 'cloudify_terminal', 'cloudify_configuration', 'cloudify_custom_workflow', 'cloudify_suspend', 'cloudify_cloudinit', 'cloudify_rest',",
"(the \"License\"); # you may not use this file except in compliance with",
"version='1.9.6', author='<EMAIL>', author_email='<EMAIL>', description='Utilities for extending Cloudify', packages=['cloudify_deployment_proxy', 'cloudify_ssh_key', 'cloudify_files', 'cloudify_terminal', 'cloudify_configuration', 'cloudify_custom_workflow',",
"'cloudify_configuration', 'cloudify_custom_workflow', 'cloudify_suspend', 'cloudify_cloudinit', 'cloudify_rest', 'cloudify_rest/rest_sdk', 'cloudify_scalelist'], license='LICENSE', install_requires=[ 'cloudify-plugins-common>=3.4.2', 'cloudify-rest-client>=4.0', # deployment_proxy",
"# * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.",
"setuptools.setup( name='cloudify-utilities-plugin', version='1.9.6', author='<EMAIL>', author_email='<EMAIL>', description='Utilities for extending Cloudify', packages=['cloudify_deployment_proxy', 'cloudify_ssh_key', 'cloudify_files', 'cloudify_terminal',",
"terminal \"Jinja2>=2.7.2\", # terminal 'pycrypto', # ssh_key 'pyyaml', # cloudinit and rest 'xmltodict']",
"is distributed on an \"AS IS\" BASIS, # * WITHOUT WARRANTIES OR CONDITIONS",
"# # Unless required by applicable law or agreed to in writing, software",
"distributed under the License is distributed on an \"AS IS\" BASIS, # *",
"language governing permissions and # * limitations under the License. import setuptools setuptools.setup(",
"OF ANY KIND, either express or implied. # * See the License for",
"Version 2.0 (the \"License\"); # you may not use this file except in",
"# Unless required by applicable law or agreed to in writing, software #",
"'cloudify_suspend', 'cloudify_cloudinit', 'cloudify_rest', 'cloudify_rest/rest_sdk', 'cloudify_scalelist'], license='LICENSE', install_requires=[ 'cloudify-plugins-common>=3.4.2', 'cloudify-rest-client>=4.0', # deployment_proxy 'paramiko', #",
"except in compliance with the License. # You may obtain a copy of",
"by applicable law or agreed to in writing, software # distributed under the",
"governing permissions and # * limitations under the License. import setuptools setuptools.setup( name='cloudify-utilities-plugin',",
"copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by",
"or implied. # * See the License for the specific language governing permissions",
"GigaSpaces Technologies Ltd. All rights reserved # # Licensed under the Apache License,",
"WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # * See",
"software # distributed under the License is distributed on an \"AS IS\" BASIS,",
"BASIS, # * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or",
"# You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0",
"may not use this file except in compliance with the License. # You",
"IS\" BASIS, # * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express",
"under the License. import setuptools setuptools.setup( name='cloudify-utilities-plugin', version='1.9.6', author='<EMAIL>', author_email='<EMAIL>', description='Utilities for extending",
"'cloudify_scalelist'], license='LICENSE', install_requires=[ 'cloudify-plugins-common>=3.4.2', 'cloudify-rest-client>=4.0', # deployment_proxy 'paramiko', # terminal \"Jinja2>=2.7.2\", # terminal",
"Cloudify', packages=['cloudify_deployment_proxy', 'cloudify_ssh_key', 'cloudify_files', 'cloudify_terminal', 'cloudify_configuration', 'cloudify_custom_workflow', 'cloudify_suspend', 'cloudify_cloudinit', 'cloudify_rest', 'cloudify_rest/rest_sdk', 'cloudify_scalelist'], license='LICENSE',",
"Licensed under the Apache License, Version 2.0 (the \"License\"); # you may not",
"# # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to",
"file except in compliance with the License. # You may obtain a copy",
"# terminal 'pycrypto', # ssh_key 'pyyaml', # cloudinit and rest 'xmltodict'] # rest",
"ANY KIND, either express or implied. # * See the License for the",
"either express or implied. # * See the License for the specific language",
"the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law",
"the License. import setuptools setuptools.setup( name='cloudify-utilities-plugin', version='1.9.6', author='<EMAIL>', author_email='<EMAIL>', description='Utilities for extending Cloudify',",
"the License. # You may obtain a copy of the License at #",
"to in writing, software # distributed under the License is distributed on an",
"packages=['cloudify_deployment_proxy', 'cloudify_ssh_key', 'cloudify_files', 'cloudify_terminal', 'cloudify_configuration', 'cloudify_custom_workflow', 'cloudify_suspend', 'cloudify_cloudinit', 'cloudify_rest', 'cloudify_rest/rest_sdk', 'cloudify_scalelist'], license='LICENSE', install_requires=[",
"# distributed under the License is distributed on an \"AS IS\" BASIS, #",
"under the License is distributed on an \"AS IS\" BASIS, # * WITHOUT",
"\"License\"); # you may not use this file except in compliance with the",
"an \"AS IS\" BASIS, # * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,",
"obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless",
"required by applicable law or agreed to in writing, software # distributed under",
"license='LICENSE', install_requires=[ 'cloudify-plugins-common>=3.4.2', 'cloudify-rest-client>=4.0', # deployment_proxy 'paramiko', # terminal \"Jinja2>=2.7.2\", # terminal 'pycrypto',",
"applicable law or agreed to in writing, software # distributed under the License",
"WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # *",
"'paramiko', # terminal \"Jinja2>=2.7.2\", # terminal 'pycrypto', # ssh_key 'pyyaml', # cloudinit and",
"# Copyright (c) 2017 GigaSpaces Technologies Ltd. All rights reserved # # Licensed",
"Ltd. All rights reserved # # Licensed under the Apache License, Version 2.0",
"# * limitations under the License. import setuptools setuptools.setup( name='cloudify-utilities-plugin', version='1.9.6', author='<EMAIL>', author_email='<EMAIL>',",
"License is distributed on an \"AS IS\" BASIS, # * WITHOUT WARRANTIES OR",
"or agreed to in writing, software # distributed under the License is distributed",
"implied. # * See the License for the specific language governing permissions and",
"KIND, either express or implied. # * See the License for the specific",
"the specific language governing permissions and # * limitations under the License. import",
"name='cloudify-utilities-plugin', version='1.9.6', author='<EMAIL>', author_email='<EMAIL>', description='Utilities for extending Cloudify', packages=['cloudify_deployment_proxy', 'cloudify_ssh_key', 'cloudify_files', 'cloudify_terminal', 'cloudify_configuration',",
"<filename>setup.py # Copyright (c) 2017 GigaSpaces Technologies Ltd. All rights reserved # #",
"the License for the specific language governing permissions and # * limitations under",
"install_requires=[ 'cloudify-plugins-common>=3.4.2', 'cloudify-rest-client>=4.0', # deployment_proxy 'paramiko', # terminal \"Jinja2>=2.7.2\", # terminal 'pycrypto', #",
"Apache License, Version 2.0 (the \"License\"); # you may not use this file",
"terminal 'pycrypto', # ssh_key 'pyyaml', # cloudinit and rest 'xmltodict'] # rest )",
"may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # #",
"for the specific language governing permissions and # * limitations under the License.",
"reserved # # Licensed under the Apache License, Version 2.0 (the \"License\"); #",
"with the License. # You may obtain a copy of the License at",
"http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing,",
"in writing, software # distributed under the License is distributed on an \"AS",
"under the Apache License, Version 2.0 (the \"License\"); # you may not use"
] |
[
"iteration_power(number: int, exp: int) -> int: \"\"\" Perpangkatan dengan metode iteratif atau perulangan",
"Pangkat sama dengan 0 print(iteration_power(number=100, exp=0)) # Angka 0 dengan pangkat lebih dari",
">>> iteration_power(2, 5) 32 >>> iteration_power(100, 0) 1 >>> iteration_power(0, 100) 0 >>>",
"5) 32 >>> iteration_power(100, 0) 1 >>> iteration_power(0, 100) 0 >>> iteration_power(1, 100)",
"__name__ == \"__main__\": import doctest doctest.testmod() # Pangkat lebih dari 1 print(iteration_power(number=2, exp=5))",
"\"\"\" Perpangkatan dengan metode iteratif atau perulangan rumus matematika: number^exp >>> iteration_power(2, 5)",
"iteratif atau perulangan rumus matematika: number^exp >>> iteration_power(2, 5) 32 >>> iteration_power(100, 0)",
"# Pangkat lebih dari 1 print(iteration_power(number=2, exp=5)) # Pangkat sama dengan 0 print(iteration_power(number=100,",
"iteration_power(0, 100) 0 >>> iteration_power(1, 100) 1 \"\"\" result = 1 for _",
"-> int: \"\"\" Perpangkatan dengan metode iteratif atau perulangan rumus matematika: number^exp >>>",
"if __name__ == \"__main__\": import doctest doctest.testmod() # Pangkat lebih dari 1 print(iteration_power(number=2,",
"perulangan rumus matematika: number^exp >>> iteration_power(2, 5) 32 >>> iteration_power(100, 0) 1 >>>",
"rumus matematika: number^exp >>> iteration_power(2, 5) 32 >>> iteration_power(100, 0) 1 >>> iteration_power(0,",
"dari 1 print(iteration_power(number=2, exp=5)) # Pangkat sama dengan 0 print(iteration_power(number=100, exp=0)) # Angka",
"0 >>> iteration_power(1, 100) 1 \"\"\" result = 1 for _ in range(exp):",
">>> iteration_power(0, 100) 0 >>> iteration_power(1, 100) 1 \"\"\" result = 1 for",
"lebih dari 1 print(iteration_power(number=0, exp=100)) # Angka 1 dengan pangkat lebih dari 1",
"== \"__main__\": import doctest doctest.testmod() # Pangkat lebih dari 1 print(iteration_power(number=2, exp=5)) #",
"1 print(iteration_power(number=0, exp=100)) # Angka 1 dengan pangkat lebih dari 1 print(iteration_power(number=1, exp=100))",
">>> iteration_power(1, 100) 1 \"\"\" result = 1 for _ in range(exp): result",
"*= number return result if __name__ == \"__main__\": import doctest doctest.testmod() # Pangkat",
"0) 1 >>> iteration_power(0, 100) 0 >>> iteration_power(1, 100) 1 \"\"\" result =",
"0 print(iteration_power(number=100, exp=0)) # Angka 0 dengan pangkat lebih dari 1 print(iteration_power(number=0, exp=100))",
"# Angka 0 dengan pangkat lebih dari 1 print(iteration_power(number=0, exp=100)) # Angka 1",
"iteration_power(1, 100) 1 \"\"\" result = 1 for _ in range(exp): result *=",
"# Pangkat sama dengan 0 print(iteration_power(number=100, exp=0)) # Angka 0 dengan pangkat lebih",
"pangkat lebih dari 1 print(iteration_power(number=0, exp=100)) # Angka 1 dengan pangkat lebih dari",
"\"\"\" result = 1 for _ in range(exp): result *= number return result",
"1 >>> iteration_power(0, 100) 0 >>> iteration_power(1, 100) 1 \"\"\" result = 1",
"exp: int) -> int: \"\"\" Perpangkatan dengan metode iteratif atau perulangan rumus matematika:",
">>> iteration_power(100, 0) 1 >>> iteration_power(0, 100) 0 >>> iteration_power(1, 100) 1 \"\"\"",
"iteration_power(100, 0) 1 >>> iteration_power(0, 100) 0 >>> iteration_power(1, 100) 1 \"\"\" result",
"_ in range(exp): result *= number return result if __name__ == \"__main__\": import",
"sama dengan 0 print(iteration_power(number=100, exp=0)) # Angka 0 dengan pangkat lebih dari 1",
"1 for _ in range(exp): result *= number return result if __name__ ==",
"matematika: number^exp >>> iteration_power(2, 5) 32 >>> iteration_power(100, 0) 1 >>> iteration_power(0, 100)",
"iteration_power(2, 5) 32 >>> iteration_power(100, 0) 1 >>> iteration_power(0, 100) 0 >>> iteration_power(1,",
"atau perulangan rumus matematika: number^exp >>> iteration_power(2, 5) 32 >>> iteration_power(100, 0) 1",
"Perpangkatan dengan metode iteratif atau perulangan rumus matematika: number^exp >>> iteration_power(2, 5) 32",
"100) 1 \"\"\" result = 1 for _ in range(exp): result *= number",
"metode iteratif atau perulangan rumus matematika: number^exp >>> iteration_power(2, 5) 32 >>> iteration_power(100,",
"= 1 for _ in range(exp): result *= number return result if __name__",
"dengan metode iteratif atau perulangan rumus matematika: number^exp >>> iteration_power(2, 5) 32 >>>",
"in range(exp): result *= number return result if __name__ == \"__main__\": import doctest",
"print(iteration_power(number=100, exp=0)) # Angka 0 dengan pangkat lebih dari 1 print(iteration_power(number=0, exp=100)) #",
"dari 1 print(iteration_power(number=0, exp=100)) # Angka 1 dengan pangkat lebih dari 1 print(iteration_power(number=1,",
"100) 0 >>> iteration_power(1, 100) 1 \"\"\" result = 1 for _ in",
"def iteration_power(number: int, exp: int) -> int: \"\"\" Perpangkatan dengan metode iteratif atau",
"1 \"\"\" result = 1 for _ in range(exp): result *= number return",
"32 >>> iteration_power(100, 0) 1 >>> iteration_power(0, 100) 0 >>> iteration_power(1, 100) 1",
"lebih dari 1 print(iteration_power(number=2, exp=5)) # Pangkat sama dengan 0 print(iteration_power(number=100, exp=0)) #",
"import doctest doctest.testmod() # Pangkat lebih dari 1 print(iteration_power(number=2, exp=5)) # Pangkat sama",
"int, exp: int) -> int: \"\"\" Perpangkatan dengan metode iteratif atau perulangan rumus",
"result = 1 for _ in range(exp): result *= number return result if",
"for _ in range(exp): result *= number return result if __name__ == \"__main__\":",
"Pangkat lebih dari 1 print(iteration_power(number=2, exp=5)) # Pangkat sama dengan 0 print(iteration_power(number=100, exp=0))",
"return result if __name__ == \"__main__\": import doctest doctest.testmod() # Pangkat lebih dari",
"number^exp >>> iteration_power(2, 5) 32 >>> iteration_power(100, 0) 1 >>> iteration_power(0, 100) 0",
"int) -> int: \"\"\" Perpangkatan dengan metode iteratif atau perulangan rumus matematika: number^exp",
"print(iteration_power(number=2, exp=5)) # Pangkat sama dengan 0 print(iteration_power(number=100, exp=0)) # Angka 0 dengan",
"dengan pangkat lebih dari 1 print(iteration_power(number=0, exp=100)) # Angka 1 dengan pangkat lebih",
"1 print(iteration_power(number=2, exp=5)) # Pangkat sama dengan 0 print(iteration_power(number=100, exp=0)) # Angka 0",
"exp=0)) # Angka 0 dengan pangkat lebih dari 1 print(iteration_power(number=0, exp=100)) # Angka",
"number return result if __name__ == \"__main__\": import doctest doctest.testmod() # Pangkat lebih",
"Angka 0 dengan pangkat lebih dari 1 print(iteration_power(number=0, exp=100)) # Angka 1 dengan",
"<filename>math/iteration_power.py def iteration_power(number: int, exp: int) -> int: \"\"\" Perpangkatan dengan metode iteratif",
"0 dengan pangkat lebih dari 1 print(iteration_power(number=0, exp=100)) # Angka 1 dengan pangkat",
"result if __name__ == \"__main__\": import doctest doctest.testmod() # Pangkat lebih dari 1",
"\"__main__\": import doctest doctest.testmod() # Pangkat lebih dari 1 print(iteration_power(number=2, exp=5)) # Pangkat",
"range(exp): result *= number return result if __name__ == \"__main__\": import doctest doctest.testmod()",
"doctest doctest.testmod() # Pangkat lebih dari 1 print(iteration_power(number=2, exp=5)) # Pangkat sama dengan",
"dengan 0 print(iteration_power(number=100, exp=0)) # Angka 0 dengan pangkat lebih dari 1 print(iteration_power(number=0,",
"result *= number return result if __name__ == \"__main__\": import doctest doctest.testmod() #",
"int: \"\"\" Perpangkatan dengan metode iteratif atau perulangan rumus matematika: number^exp >>> iteration_power(2,",
"exp=5)) # Pangkat sama dengan 0 print(iteration_power(number=100, exp=0)) # Angka 0 dengan pangkat",
"doctest.testmod() # Pangkat lebih dari 1 print(iteration_power(number=2, exp=5)) # Pangkat sama dengan 0"
] |
[
"and Alphas text wrapping\"\"\" def __init__(self, font_path, font_size): super(BoxWrapper, self).__init__() self.font_path = font_path",
"font_size) def line_size(self, virtual_line): return self.font.getsize(virtual_line) def split(self, text): words = [] word_tmp",
"> 0 and \\ len(split_words[wordpos-1]) > 1: split_words[wordpos] = ' ' + split_words[wordpos]",
"> 1 and wordpos > 0 and \\ len(split_words[wordpos-1]) > 1: split_words[wordpos] =",
"split_words[wordpos] # print(split_words) return split_words def wrap_as_box(self, text, box_width, color, place='left'): words =",
"color=back_color) draw = ImageDraw.Draw(image) x = 0 y = 0 for index, line",
"def __init__(self, font_path, font_size): super(BoxWrapper, self).__init__() self.font_path = font_path self.font = ImageFont.truetype(font_path, font_size)",
"word in words: line_tmp = line + word size = self.line_size(line_tmp) text_h =",
"len(word) == 1: split_words.append(word) else: split_words.extend(word.split()) for wordpos, word in enumerate(split_words): if len(word)",
"text_h = size[1] if size[0] <= box_width: line = line_tmp else: lines.append(line) line",
"line = word.strip() if line: lines.append(line) return lines, (box_width, text_h*len(lines)), text_h def mkimg(self,",
"+= chx if word_tmp: words.append(word_tmp) word_tmp = '' # split Alpha words split_words",
"line_tmp = line + word size = self.line_size(line_tmp) text_h = size[1] if size[0]",
"line_tmp else: lines.append(line) line = word.strip() if line: lines.append(line) return lines, (box_width, text_h*len(lines)),",
"line: lines.append(line) return lines, (box_width, text_h*len(lines)), text_h def mkimg(self, text, box_width, color='#000', place='left',",
"y), line, font=self.font, fill=color) y += line_h + line_padding return image if __name__",
"0 and \\ len(split_words[wordpos-1]) > 1: split_words[wordpos] = ' ' + split_words[wordpos] #",
"wordpos, word in enumerate(split_words): if len(word) > 1 and wordpos > 0 and",
"line, font=self.font, fill=color) y += line_h + line_padding return image if __name__ ==",
"return split_words def wrap_as_box(self, text, box_width, color, place='left'): words = self.split(text) lines =",
"-*- coding: utf-8 -*- \"\"\" Image tools \"\"\" __author__ = 'Zagfai' __date__ =",
"font_path self.font = ImageFont.truetype(font_path, font_size) def line_size(self, virtual_line): return self.font.getsize(virtual_line) def split(self, text):",
"word.strip() if line: lines.append(line) return lines, (box_width, text_h*len(lines)), text_h def mkimg(self, text, box_width,",
"= self.line_size(line_tmp) text_h = size[1] if size[0] <= box_width: line = line_tmp else:",
"if len(word) > 1 and wordpos > 0 and \\ len(split_words[wordpos-1]) > 1:",
"enumerate(split_words): if len(word) > 1 and wordpos > 0 and \\ len(split_words[wordpos-1]) >",
"lines, (box_width, text_h*len(lines)), text_h def mkimg(self, text, box_width, color='#000', place='left', mode='RGBA', back_color=(255, 255,",
"split_words.append(word) else: split_words.extend(word.split()) for wordpos, word in enumerate(split_words): if len(word) > 1 and",
"= '2018-02' from PIL import Image from PIL import ImageDraw from PIL import",
"= [] line = '' for word in words: line_tmp = line +",
"line_padding=0): lines, (w, h), line_h = self.wrap_as_box(text, box_width, color) image = Image.new( mode,",
"word in words: if len(word) == 1: split_words.append(word) else: split_words.extend(word.split()) for wordpos, word",
"= '/usr/share/fonts/opentype/noto/NotoSansCJK-Regular.ttc' text = \"【以色列钻石交易所:将发行两种数字货币】世界大型交易所之一的以色列钻石交易所宣布,将发行两种数字货币:一种为Carat,定位于广大投资券;另一种为Cut,预计将用于钻石市场专业参与者间的结算。25%的Carat价值将基于交易平台所拥有的钻石。\" # NOQA x = BoxWrapper(charpath, 24) x.mkimg(text, 390,",
"'' for chx in text: if ord(chx) > 255: if word_tmp: words.append(word_tmp) word_tmp",
"= 0 y = 0 for index, line in enumerate(lines): draw.text((x, y), line,",
"# -*- coding: utf-8 -*- \"\"\" Image tools \"\"\" __author__ = 'Zagfai' __date__",
"== \"__main__\": charpath = '/usr/share/fonts/opentype/noto/NotoSansCJK-Regular.ttc' text = \"【以色列钻石交易所:将发行两种数字货币】世界大型交易所之一的以色列钻石交易所宣布,将发行两种数字货币:一种为Carat,定位于广大投资券;另一种为Cut,预计将用于钻石市场专业参与者间的结算。25%的Carat价值将基于交易平台所拥有的钻石。\" # NOQA x = BoxWrapper(charpath,",
"box_width: line = line_tmp else: lines.append(line) line = word.strip() if line: lines.append(line) return",
"chx in text: if ord(chx) > 255: if word_tmp: words.append(word_tmp) word_tmp = ''",
"\\ len(split_words[wordpos-1]) > 1: split_words[wordpos] = ' ' + split_words[wordpos] # print(split_words) return",
"'/usr/share/fonts/opentype/noto/NotoSansCJK-Regular.ttc' text = \"【以色列钻石交易所:将发行两种数字货币】世界大型交易所之一的以色列钻石交易所宣布,将发行两种数字货币:一种为Carat,定位于广大投资券;另一种为Cut,预计将用于钻石市场专业参与者间的结算。25%的Carat价值将基于交易平台所拥有的钻石。\" # NOQA x = BoxWrapper(charpath, 24) x.mkimg(text, 390, '#000')",
"chx if word_tmp: words.append(word_tmp) word_tmp = '' # split Alpha words split_words =",
"'' words.append(chx) else: word_tmp += chx if word_tmp: words.append(word_tmp) word_tmp = '' #",
"mode='RGBA', back_color=(255, 255, 255, 0), line_padding=0): lines, (w, h), line_h = self.wrap_as_box(text, box_width,",
"x = 0 y = 0 for index, line in enumerate(lines): draw.text((x, y),",
"words: line_tmp = line + word size = self.line_size(line_tmp) text_h = size[1] if",
"words.append(word_tmp) word_tmp = '' words.append(chx) else: word_tmp += chx if word_tmp: words.append(word_tmp) word_tmp",
"= font_path self.font = ImageFont.truetype(font_path, font_size) def line_size(self, virtual_line): return self.font.getsize(virtual_line) def split(self,",
"virtual_line): return self.font.getsize(virtual_line) def split(self, text): words = [] word_tmp = '' for",
"= size[1] if size[0] <= box_width: line = line_tmp else: lines.append(line) line =",
"self.font = ImageFont.truetype(font_path, font_size) def line_size(self, virtual_line): return self.font.getsize(virtual_line) def split(self, text): words",
"= line + word size = self.line_size(line_tmp) text_h = size[1] if size[0] <=",
"len(word) > 1 and wordpos > 0 and \\ len(split_words[wordpos-1]) > 1: split_words[wordpos]",
"return lines, (box_width, text_h*len(lines)), text_h def mkimg(self, text, box_width, color='#000', place='left', mode='RGBA', back_color=(255,",
"= [] for word in words: if len(word) == 1: split_words.append(word) else: split_words.extend(word.split())",
"and wordpos > 0 and \\ len(split_words[wordpos-1]) > 1: split_words[wordpos] = ' '",
"print(split_words) return split_words def wrap_as_box(self, text, box_width, color, place='left'): words = self.split(text) lines",
"in words: if len(word) == 1: split_words.append(word) else: split_words.extend(word.split()) for wordpos, word in",
"text_h*len(lines)), text_h def mkimg(self, text, box_width, color='#000', place='left', mode='RGBA', back_color=(255, 255, 255, 0),",
"= self.split(text) lines = [] line = '' for word in words: line_tmp",
"'2018-02' from PIL import Image from PIL import ImageDraw from PIL import ImageFont",
"words: if len(word) == 1: split_words.append(word) else: split_words.extend(word.split()) for wordpos, word in enumerate(split_words):",
"text: if ord(chx) > 255: if word_tmp: words.append(word_tmp) word_tmp = '' words.append(chx) else:",
"'' for word in words: line_tmp = line + word size = self.line_size(line_tmp)",
"1: split_words.append(word) else: split_words.extend(word.split()) for wordpos, word in enumerate(split_words): if len(word) > 1",
"line_size(self, virtual_line): return self.font.getsize(virtual_line) def split(self, text): words = [] word_tmp = ''",
"= [] word_tmp = '' for chx in text: if ord(chx) > 255:",
"index, line in enumerate(lines): draw.text((x, y), line, font=self.font, fill=color) y += line_h +",
"ImageDraw.Draw(image) x = 0 y = 0 for index, line in enumerate(lines): draw.text((x,",
"if ord(chx) > 255: if word_tmp: words.append(word_tmp) word_tmp = '' words.append(chx) else: word_tmp",
"\"__main__\": charpath = '/usr/share/fonts/opentype/noto/NotoSansCJK-Regular.ttc' text = \"【以色列钻石交易所:将发行两种数字货币】世界大型交易所之一的以色列钻石交易所宣布,将发行两种数字货币:一种为Carat,定位于广大投资券;另一种为Cut,预计将用于钻石市场专业参与者间的结算。25%的Carat价值将基于交易平台所拥有的钻石。\" # NOQA x = BoxWrapper(charpath, 24)",
"h+line_padding*len(lines)), color=back_color) draw = ImageDraw.Draw(image) x = 0 y = 0 for index,",
"if line: lines.append(line) return lines, (box_width, text_h*len(lines)), text_h def mkimg(self, text, box_width, color='#000',",
"tools \"\"\" __author__ = 'Zagfai' __date__ = '2018-02' from PIL import Image from",
"\"\"\" __author__ = 'Zagfai' __date__ = '2018-02' from PIL import Image from PIL",
"= ImageDraw.Draw(image) x = 0 y = 0 for index, line in enumerate(lines):",
"from PIL import ImageFont class BoxWrapper(object): \"\"\"BoxWrapper for Chinese and Alphas text wrapping\"\"\"",
"self.wrap_as_box(text, box_width, color) image = Image.new( mode, (box_width, h+line_padding*len(lines)), color=back_color) draw = ImageDraw.Draw(image)",
"y = 0 for index, line in enumerate(lines): draw.text((x, y), line, font=self.font, fill=color)",
"y += line_h + line_padding return image if __name__ == \"__main__\": charpath =",
"<= box_width: line = line_tmp else: lines.append(line) line = word.strip() if line: lines.append(line)",
"+= line_h + line_padding return image if __name__ == \"__main__\": charpath = '/usr/share/fonts/opentype/noto/NotoSansCJK-Regular.ttc'",
"def wrap_as_box(self, text, box_width, color, place='left'): words = self.split(text) lines = [] line",
"__name__ == \"__main__\": charpath = '/usr/share/fonts/opentype/noto/NotoSansCJK-Regular.ttc' text = \"【以色列钻石交易所:将发行两种数字货币】世界大型交易所之一的以色列钻石交易所宣布,将发行两种数字货币:一种为Carat,定位于广大投资券;另一种为Cut,预计将用于钻石市场专业参与者间的结算。25%的Carat价值将基于交易平台所拥有的钻石。\" # NOQA x =",
"for index, line in enumerate(lines): draw.text((x, y), line, font=self.font, fill=color) y += line_h",
"ImageDraw from PIL import ImageFont class BoxWrapper(object): \"\"\"BoxWrapper for Chinese and Alphas text",
"255, 0), line_padding=0): lines, (w, h), line_h = self.wrap_as_box(text, box_width, color) image =",
"(box_width, text_h*len(lines)), text_h def mkimg(self, text, box_width, color='#000', place='left', mode='RGBA', back_color=(255, 255, 255,",
"fill=color) y += line_h + line_padding return image if __name__ == \"__main__\": charpath",
"size = self.line_size(line_tmp) text_h = size[1] if size[0] <= box_width: line = line_tmp",
"lines.append(line) line = word.strip() if line: lines.append(line) return lines, (box_width, text_h*len(lines)), text_h def",
"if word_tmp: words.append(word_tmp) word_tmp = '' # split Alpha words split_words = []",
"return image if __name__ == \"__main__\": charpath = '/usr/share/fonts/opentype/noto/NotoSansCJK-Regular.ttc' text = \"【以色列钻石交易所:将发行两种数字货币】世界大型交易所之一的以色列钻石交易所宣布,将发行两种数字货币:一种为Carat,定位于广大投资券;另一种为Cut,预计将用于钻石市场专业参与者间的结算。25%的Carat价值将基于交易平台所拥有的钻石。\" #",
"split_words = [] for word in words: if len(word) == 1: split_words.append(word) else:",
"for word in words: line_tmp = line + word size = self.line_size(line_tmp) text_h",
"ImageFont class BoxWrapper(object): \"\"\"BoxWrapper for Chinese and Alphas text wrapping\"\"\" def __init__(self, font_path,",
"Alpha words split_words = [] for word in words: if len(word) == 1:",
"= '' # split Alpha words split_words = [] for word in words:",
"'' # split Alpha words split_words = [] for word in words: if",
"back_color=(255, 255, 255, 0), line_padding=0): lines, (w, h), line_h = self.wrap_as_box(text, box_width, color)",
"0 for index, line in enumerate(lines): draw.text((x, y), line, font=self.font, fill=color) y +=",
"PIL import ImageFont class BoxWrapper(object): \"\"\"BoxWrapper for Chinese and Alphas text wrapping\"\"\" def",
"words.append(chx) else: word_tmp += chx if word_tmp: words.append(word_tmp) word_tmp = '' # split",
"self.font_path = font_path self.font = ImageFont.truetype(font_path, font_size) def line_size(self, virtual_line): return self.font.getsize(virtual_line) def",
"255, 255, 0), line_padding=0): lines, (w, h), line_h = self.wrap_as_box(text, box_width, color) image",
"image = Image.new( mode, (box_width, h+line_padding*len(lines)), color=back_color) draw = ImageDraw.Draw(image) x = 0",
"def line_size(self, virtual_line): return self.font.getsize(virtual_line) def split(self, text): words = [] word_tmp =",
"self.font.getsize(virtual_line) def split(self, text): words = [] word_tmp = '' for chx in",
"line = '' for word in words: line_tmp = line + word size",
"[] line = '' for word in words: line_tmp = line + word",
"for word in words: if len(word) == 1: split_words.append(word) else: split_words.extend(word.split()) for wordpos,",
"def split(self, text): words = [] word_tmp = '' for chx in text:",
"-*- \"\"\" Image tools \"\"\" __author__ = 'Zagfai' __date__ = '2018-02' from PIL",
"+ split_words[wordpos] # print(split_words) return split_words def wrap_as_box(self, text, box_width, color, place='left'): words",
"text_h def mkimg(self, text, box_width, color='#000', place='left', mode='RGBA', back_color=(255, 255, 255, 0), line_padding=0):",
"word_tmp = '' words.append(chx) else: word_tmp += chx if word_tmp: words.append(word_tmp) word_tmp =",
"else: word_tmp += chx if word_tmp: words.append(word_tmp) word_tmp = '' # split Alpha",
"image if __name__ == \"__main__\": charpath = '/usr/share/fonts/opentype/noto/NotoSansCJK-Regular.ttc' text = \"【以色列钻石交易所:将发行两种数字货币】世界大型交易所之一的以色列钻石交易所宣布,将发行两种数字货币:一种为Carat,定位于广大投资券;另一种为Cut,预计将用于钻石市场专业参与者间的结算。25%的Carat价值将基于交易平台所拥有的钻石。\" # NOQA",
"= '' for word in words: line_tmp = line + word size =",
"line_padding return image if __name__ == \"__main__\": charpath = '/usr/share/fonts/opentype/noto/NotoSansCJK-Regular.ttc' text = \"【以色列钻石交易所:将发行两种数字货币】世界大型交易所之一的以色列钻石交易所宣布,将发行两种数字货币:一种为Carat,定位于广大投资券;另一种为Cut,预计将用于钻石市场专业参与者间的结算。25%的Carat价值将基于交易平台所拥有的钻石。\"",
"[] for word in words: if len(word) == 1: split_words.append(word) else: split_words.extend(word.split()) for",
"in words: line_tmp = line + word size = self.line_size(line_tmp) text_h = size[1]",
"<filename>webtul/img.py #!/usr/bin/python # -*- coding: utf-8 -*- \"\"\" Image tools \"\"\" __author__ =",
"place='left'): words = self.split(text) lines = [] line = '' for word in",
"split_words[wordpos] = ' ' + split_words[wordpos] # print(split_words) return split_words def wrap_as_box(self, text,",
"lines.append(line) return lines, (box_width, text_h*len(lines)), text_h def mkimg(self, text, box_width, color='#000', place='left', mode='RGBA',",
"place='left', mode='RGBA', back_color=(255, 255, 255, 0), line_padding=0): lines, (w, h), line_h = self.wrap_as_box(text,",
"lines = [] line = '' for word in words: line_tmp = line",
"+ line_padding return image if __name__ == \"__main__\": charpath = '/usr/share/fonts/opentype/noto/NotoSansCJK-Regular.ttc' text =",
"(w, h), line_h = self.wrap_as_box(text, box_width, color) image = Image.new( mode, (box_width, h+line_padding*len(lines)),",
"' + split_words[wordpos] # print(split_words) return split_words def wrap_as_box(self, text, box_width, color, place='left'):",
"= ImageFont.truetype(font_path, font_size) def line_size(self, virtual_line): return self.font.getsize(virtual_line) def split(self, text): words =",
"in enumerate(split_words): if len(word) > 1 and wordpos > 0 and \\ len(split_words[wordpos-1])",
"for chx in text: if ord(chx) > 255: if word_tmp: words.append(word_tmp) word_tmp =",
"(box_width, h+line_padding*len(lines)), color=back_color) draw = ImageDraw.Draw(image) x = 0 y = 0 for",
"PIL import Image from PIL import ImageDraw from PIL import ImageFont class BoxWrapper(object):",
"= '' words.append(chx) else: word_tmp += chx if word_tmp: words.append(word_tmp) word_tmp = ''",
"ord(chx) > 255: if word_tmp: words.append(word_tmp) word_tmp = '' words.append(chx) else: word_tmp +=",
"wrap_as_box(self, text, box_width, color, place='left'): words = self.split(text) lines = [] line =",
"= 0 for index, line in enumerate(lines): draw.text((x, y), line, font=self.font, fill=color) y",
"word_tmp = '' # split Alpha words split_words = [] for word in",
"size[0] <= box_width: line = line_tmp else: lines.append(line) line = word.strip() if line:",
"self.split(text) lines = [] line = '' for word in words: line_tmp =",
"> 1: split_words[wordpos] = ' ' + split_words[wordpos] # print(split_words) return split_words def",
"= word.strip() if line: lines.append(line) return lines, (box_width, text_h*len(lines)), text_h def mkimg(self, text,",
"text wrapping\"\"\" def __init__(self, font_path, font_size): super(BoxWrapper, self).__init__() self.font_path = font_path self.font =",
"' ' + split_words[wordpos] # print(split_words) return split_words def wrap_as_box(self, text, box_width, color,",
"mkimg(self, text, box_width, color='#000', place='left', mode='RGBA', back_color=(255, 255, 255, 0), line_padding=0): lines, (w,",
"0), line_padding=0): lines, (w, h), line_h = self.wrap_as_box(text, box_width, color) image = Image.new(",
"text, box_width, color='#000', place='left', mode='RGBA', back_color=(255, 255, 255, 0), line_padding=0): lines, (w, h),",
"Image from PIL import ImageDraw from PIL import ImageFont class BoxWrapper(object): \"\"\"BoxWrapper for",
"# split Alpha words split_words = [] for word in words: if len(word)",
"else: lines.append(line) line = word.strip() if line: lines.append(line) return lines, (box_width, text_h*len(lines)), text_h",
"split(self, text): words = [] word_tmp = '' for chx in text: if",
"text, box_width, color, place='left'): words = self.split(text) lines = [] line = ''",
"draw.text((x, y), line, font=self.font, fill=color) y += line_h + line_padding return image if",
"self).__init__() self.font_path = font_path self.font = ImageFont.truetype(font_path, font_size) def line_size(self, virtual_line): return self.font.getsize(virtual_line)",
"[] word_tmp = '' for chx in text: if ord(chx) > 255: if",
"font=self.font, fill=color) y += line_h + line_padding return image if __name__ == \"__main__\":",
"+ word size = self.line_size(line_tmp) text_h = size[1] if size[0] <= box_width: line",
"return self.font.getsize(virtual_line) def split(self, text): words = [] word_tmp = '' for chx",
"lines, (w, h), line_h = self.wrap_as_box(text, box_width, color) image = Image.new( mode, (box_width,",
"color) image = Image.new( mode, (box_width, h+line_padding*len(lines)), color=back_color) draw = ImageDraw.Draw(image) x =",
"line in enumerate(lines): draw.text((x, y), line, font=self.font, fill=color) y += line_h + line_padding",
"BoxWrapper(object): \"\"\"BoxWrapper for Chinese and Alphas text wrapping\"\"\" def __init__(self, font_path, font_size): super(BoxWrapper,",
"class BoxWrapper(object): \"\"\"BoxWrapper for Chinese and Alphas text wrapping\"\"\" def __init__(self, font_path, font_size):",
"mode, (box_width, h+line_padding*len(lines)), color=back_color) draw = ImageDraw.Draw(image) x = 0 y = 0",
"= self.wrap_as_box(text, box_width, color) image = Image.new( mode, (box_width, h+line_padding*len(lines)), color=back_color) draw =",
"for wordpos, word in enumerate(split_words): if len(word) > 1 and wordpos > 0",
"for Chinese and Alphas text wrapping\"\"\" def __init__(self, font_path, font_size): super(BoxWrapper, self).__init__() self.font_path",
"'Zagfai' __date__ = '2018-02' from PIL import Image from PIL import ImageDraw from",
"#!/usr/bin/python # -*- coding: utf-8 -*- \"\"\" Image tools \"\"\" __author__ = 'Zagfai'",
"word_tmp += chx if word_tmp: words.append(word_tmp) word_tmp = '' # split Alpha words",
"super(BoxWrapper, self).__init__() self.font_path = font_path self.font = ImageFont.truetype(font_path, font_size) def line_size(self, virtual_line): return",
"ImageFont.truetype(font_path, font_size) def line_size(self, virtual_line): return self.font.getsize(virtual_line) def split(self, text): words = []",
"import ImageFont class BoxWrapper(object): \"\"\"BoxWrapper for Chinese and Alphas text wrapping\"\"\" def __init__(self,",
"wrapping\"\"\" def __init__(self, font_path, font_size): super(BoxWrapper, self).__init__() self.font_path = font_path self.font = ImageFont.truetype(font_path,",
"text): words = [] word_tmp = '' for chx in text: if ord(chx)",
"def mkimg(self, text, box_width, color='#000', place='left', mode='RGBA', back_color=(255, 255, 255, 0), line_padding=0): lines,",
"draw = ImageDraw.Draw(image) x = 0 y = 0 for index, line in",
"utf-8 -*- \"\"\" Image tools \"\"\" __author__ = 'Zagfai' __date__ = '2018-02' from",
"== 1: split_words.append(word) else: split_words.extend(word.split()) for wordpos, word in enumerate(split_words): if len(word) >",
"if __name__ == \"__main__\": charpath = '/usr/share/fonts/opentype/noto/NotoSansCJK-Regular.ttc' text = \"【以色列钻石交易所:将发行两种数字货币】世界大型交易所之一的以色列钻石交易所宣布,将发行两种数字货币:一种为Carat,定位于广大投资券;另一种为Cut,预计将用于钻石市场专业参与者间的结算。25%的Carat价值将基于交易平台所拥有的钻石。\" # NOQA x",
"Chinese and Alphas text wrapping\"\"\" def __init__(self, font_path, font_size): super(BoxWrapper, self).__init__() self.font_path =",
"from PIL import Image from PIL import ImageDraw from PIL import ImageFont class",
"box_width, color) image = Image.new( mode, (box_width, h+line_padding*len(lines)), color=back_color) draw = ImageDraw.Draw(image) x",
"wordpos > 0 and \\ len(split_words[wordpos-1]) > 1: split_words[wordpos] = ' ' +",
"h), line_h = self.wrap_as_box(text, box_width, color) image = Image.new( mode, (box_width, h+line_padding*len(lines)), color=back_color)",
"__init__(self, font_path, font_size): super(BoxWrapper, self).__init__() self.font_path = font_path self.font = ImageFont.truetype(font_path, font_size) def",
"line = line_tmp else: lines.append(line) line = word.strip() if line: lines.append(line) return lines,",
"= Image.new( mode, (box_width, h+line_padding*len(lines)), color=back_color) draw = ImageDraw.Draw(image) x = 0 y",
"word_tmp: words.append(word_tmp) word_tmp = '' words.append(chx) else: word_tmp += chx if word_tmp: words.append(word_tmp)",
"PIL import ImageDraw from PIL import ImageFont class BoxWrapper(object): \"\"\"BoxWrapper for Chinese and",
"= ' ' + split_words[wordpos] # print(split_words) return split_words def wrap_as_box(self, text, box_width,",
"split_words def wrap_as_box(self, text, box_width, color, place='left'): words = self.split(text) lines = []",
"from PIL import ImageDraw from PIL import ImageFont class BoxWrapper(object): \"\"\"BoxWrapper for Chinese",
"enumerate(lines): draw.text((x, y), line, font=self.font, fill=color) y += line_h + line_padding return image",
"word_tmp: words.append(word_tmp) word_tmp = '' # split Alpha words split_words = [] for",
"Image tools \"\"\" __author__ = 'Zagfai' __date__ = '2018-02' from PIL import Image",
"font_path, font_size): super(BoxWrapper, self).__init__() self.font_path = font_path self.font = ImageFont.truetype(font_path, font_size) def line_size(self,",
"box_width, color, place='left'): words = self.split(text) lines = [] line = '' for",
"__author__ = 'Zagfai' __date__ = '2018-02' from PIL import Image from PIL import",
"line + word size = self.line_size(line_tmp) text_h = size[1] if size[0] <= box_width:",
"line_h = self.wrap_as_box(text, box_width, color) image = Image.new( mode, (box_width, h+line_padding*len(lines)), color=back_color) draw",
"\"\"\"BoxWrapper for Chinese and Alphas text wrapping\"\"\" def __init__(self, font_path, font_size): super(BoxWrapper, self).__init__()",
"words.append(word_tmp) word_tmp = '' # split Alpha words split_words = [] for word",
"\"\"\" Image tools \"\"\" __author__ = 'Zagfai' __date__ = '2018-02' from PIL import",
"and \\ len(split_words[wordpos-1]) > 1: split_words[wordpos] = ' ' + split_words[wordpos] # print(split_words)",
"Image.new( mode, (box_width, h+line_padding*len(lines)), color=back_color) draw = ImageDraw.Draw(image) x = 0 y =",
"in text: if ord(chx) > 255: if word_tmp: words.append(word_tmp) word_tmp = '' words.append(chx)",
"import Image from PIL import ImageDraw from PIL import ImageFont class BoxWrapper(object): \"\"\"BoxWrapper",
"word size = self.line_size(line_tmp) text_h = size[1] if size[0] <= box_width: line =",
"box_width, color='#000', place='left', mode='RGBA', back_color=(255, 255, 255, 0), line_padding=0): lines, (w, h), line_h",
"255: if word_tmp: words.append(word_tmp) word_tmp = '' words.append(chx) else: word_tmp += chx if",
"color='#000', place='left', mode='RGBA', back_color=(255, 255, 255, 0), line_padding=0): lines, (w, h), line_h =",
"> 255: if word_tmp: words.append(word_tmp) word_tmp = '' words.append(chx) else: word_tmp += chx",
"split Alpha words split_words = [] for word in words: if len(word) ==",
"split_words.extend(word.split()) for wordpos, word in enumerate(split_words): if len(word) > 1 and wordpos >",
"words = self.split(text) lines = [] line = '' for word in words:",
"self.line_size(line_tmp) text_h = size[1] if size[0] <= box_width: line = line_tmp else: lines.append(line)",
"in enumerate(lines): draw.text((x, y), line, font=self.font, fill=color) y += line_h + line_padding return",
"__date__ = '2018-02' from PIL import Image from PIL import ImageDraw from PIL",
"words split_words = [] for word in words: if len(word) == 1: split_words.append(word)",
"words = [] word_tmp = '' for chx in text: if ord(chx) >",
"word_tmp = '' for chx in text: if ord(chx) > 255: if word_tmp:",
"charpath = '/usr/share/fonts/opentype/noto/NotoSansCJK-Regular.ttc' text = \"【以色列钻石交易所:将发行两种数字货币】世界大型交易所之一的以色列钻石交易所宣布,将发行两种数字货币:一种为Carat,定位于广大投资券;另一种为Cut,预计将用于钻石市场专业参与者间的结算。25%的Carat价值将基于交易平台所拥有的钻石。\" # NOQA x = BoxWrapper(charpath, 24) x.mkimg(text,",
"Alphas text wrapping\"\"\" def __init__(self, font_path, font_size): super(BoxWrapper, self).__init__() self.font_path = font_path self.font",
"font_size): super(BoxWrapper, self).__init__() self.font_path = font_path self.font = ImageFont.truetype(font_path, font_size) def line_size(self, virtual_line):",
"word in enumerate(split_words): if len(word) > 1 and wordpos > 0 and \\",
"size[1] if size[0] <= box_width: line = line_tmp else: lines.append(line) line = word.strip()",
"1: split_words[wordpos] = ' ' + split_words[wordpos] # print(split_words) return split_words def wrap_as_box(self,",
"# print(split_words) return split_words def wrap_as_box(self, text, box_width, color, place='left'): words = self.split(text)",
"= 'Zagfai' __date__ = '2018-02' from PIL import Image from PIL import ImageDraw",
"1 and wordpos > 0 and \\ len(split_words[wordpos-1]) > 1: split_words[wordpos] = '",
"else: split_words.extend(word.split()) for wordpos, word in enumerate(split_words): if len(word) > 1 and wordpos",
"line_h + line_padding return image if __name__ == \"__main__\": charpath = '/usr/share/fonts/opentype/noto/NotoSansCJK-Regular.ttc' text",
"if word_tmp: words.append(word_tmp) word_tmp = '' words.append(chx) else: word_tmp += chx if word_tmp:",
"import ImageDraw from PIL import ImageFont class BoxWrapper(object): \"\"\"BoxWrapper for Chinese and Alphas",
"= line_tmp else: lines.append(line) line = word.strip() if line: lines.append(line) return lines, (box_width,",
"if size[0] <= box_width: line = line_tmp else: lines.append(line) line = word.strip() if",
"color, place='left'): words = self.split(text) lines = [] line = '' for word",
"0 y = 0 for index, line in enumerate(lines): draw.text((x, y), line, font=self.font,",
"= '' for chx in text: if ord(chx) > 255: if word_tmp: words.append(word_tmp)",
"len(split_words[wordpos-1]) > 1: split_words[wordpos] = ' ' + split_words[wordpos] # print(split_words) return split_words",
"if len(word) == 1: split_words.append(word) else: split_words.extend(word.split()) for wordpos, word in enumerate(split_words): if",
"coding: utf-8 -*- \"\"\" Image tools \"\"\" __author__ = 'Zagfai' __date__ = '2018-02'"
] |
[
"with open(filename, 'w') as f: graph_mod_index(f, code_map) os.system('dot -Tpng -O {}'.format(filename)) # Function",
"table = '|location||description|\\n' table += '|:---|:---:|:---|\\n' lines = '' for line in line_list:",
"func_name, func in code_map.funcs_sorted(func_filter): if func_name == mark_func: f.write('{} [color=lightblue];\\n'.format(func_name)) elif func.private: f.write('{}",
"in code_map.mods_sorted(): filename = os.path.join(output_dir, mod_page_name(mod_name)) with open(filename, 'w') as f: page_module(f, code_map,",
"{} - {}\\n'.format(mod_link, mod.brief)) def graph_func_index(f, code_map): def all_mods(kv): return True def public_funcs(kv):",
"mod): # Filter for functions that are in, are called by, or call",
"# Helpful builder functions def link(text, filename): return '[{}]({})'.format(text, text) def table_list(f, line_list):",
"import sys import scanner import codemap # ------------------------------------------------------------------------------ # Parameterized output filenames def",
"> 0: has_table = True name = line[:findPtr].lstrip().rstrip() desc = line[findPtr + 2:].lstrip().rstrip()",
"Public Functions:\\n\\n') inmod = codemap.inmodule(mod_name) ispub = codemap.ispublic() filt = lambda f :",
"test = kv[1] if test_name == func_name: return True if test_name in func.calls:",
"Filter for functions that are in, are called by, or call a module",
"callee_name, callee in code_map.funcs_sorted(filt): if callee.private: f.write('* {} - {}\\n'.format(callee_name, callee.brief)) else: callee_link",
"func in code_map.funcs_sorted(func_filter): if func_name == mark_func: f.write('{} [color=lightblue];\\n'.format(func_name)) elif func.private: f.write('{} [color=lightgrey];\\n'.format(func_name))",
"= codemap.ispublic() filt = lambda f : inmod(f) and ispub(f) for func_name, func",
"= kv[0] test = kv[1] if test_name in mod.functions: return True for func_name",
"func_filter((callee_name, callee)): continue f.write('\\t{} -> {};\\n'.format(func_name, callee_name)) f.write('}\\n') # ------------------------------------------------------------------------------ # Output file",
"import os import sys import scanner import codemap # ------------------------------------------------------------------------------ # Parameterized output",
"f.write('\\t\\tstyle = filled;\\n') if mod_name == mark_mod: f.write('\\t\\tcolor = lightblue;\\n') else: f.write('\\t\\tcolor =",
"f.write('* {} - {}\\n'.format(caller_link, caller.brief)) f.write('\\n') # ------------------------------------------------------------------------------ # Top-level documentation builder def",
"python3 import os import sys import scanner import codemap # ------------------------------------------------------------------------------ # Parameterized",
"return True def public_funcs(kv): return not kv[1].private callgraph(f, code_map, all_mods, public_funcs) def page_func_index(f,",
"True return False # Filter for functions that are or are callers/callees of",
"f.write('}\\n') # ------------------------------------------------------------------------------ # Output file builders def graph_mod_index(f, code_map): f.write('digraph Callgraph {\\n')",
"if caller.private: f.write('* {} - {}\\n'.format(caller_name, caller.brief)) else: caller_link = link(caller_name, func_page_name(caller_name)) f.write('*",
"Filter for modules that contain or contain callers/callees of func def mod_touches_func(kv): test_name",
"scanner import codemap # ------------------------------------------------------------------------------ # Parameterized output filenames def func_index_name(): return 'Function-Index.md'",
"- {}\\n'.format(mod_link, mod.brief)) def graph_func_index(f, code_map): def all_mods(kv): return True def public_funcs(kv): return",
"kv[0] test = kv[1] if test_name == mod_name: return True if test_name in",
"filled;\\n') if mod_name == mark_mod: f.write('\\t\\tcolor = lightblue;\\n') else: f.write('\\t\\tcolor = grey;\\n') f.write('\\t\\tlabel",
"if test_name == func_name: return True if test_name in func.calls: return True if",
"func.sideeffects) f.write('## Callgraph:\\n\\n') f.write('\\n\\n'.format(func_graph_name(func_name))) f.write('## Functions called by {}\\n\\n'.format(func_name)) filt = codemap.iscalledby(func) for",
"mod in code_map.mods_sorted(): mod_link = link(mod_name, mod_page_name(mod_name)) f.write('* {} - {}\\n'.format(mod_link, mod.brief)) def",
"Side Effects:\\n\\n') table_list(f, func.sideeffects) f.write('## Callgraph:\\n\\n') f.write('\\n\\n'.format(func_graph_name(func_name))) f.write('## Functions called by {}\\n\\n'.format(func_name)) filt",
"codemap.CodeMap() builder = codemap.MapBuilder(code_map) for token in scanner.scan_project('./src'): builder.absorb_token(token) build_dox(code_map, './doc/vos64.wiki') if __name__",
"mod_name, mod in code_map.mods_sorted(): mod_link = link(mod_name, mod_page_name(mod_name)) f.write('* Module {} - {}:\\n'.format(mod_link,",
"mod.functions: func = code_map.funcs[func_name] if func_filter((func_name, func)): f.write('\\t\\t{};\\n'.format(func_name)) f.write('\\t}\\n') for func_name, func in",
"in code_map.mods_sorted(): for callee_name in mod.calls: f.write('\\t{} -> {};\\n'.format(mod_name, callee_name)) f.write('}\\n') def page_mod_index(f,",
"return os.path.join('funcs', '{}.md'.format(func_name)) def func_graph_name(func_name): return os.path.join('funcs', '{}.dot'.format(func_name)) def mod_page_name(mod_name): return os.path.join('mods', '{}.md'.format(mod_name))",
"for callee_name in func.calls: callee = code_map.funcs[callee_name] if not func_filter((callee_name, callee)): continue f.write('\\t{}",
"{}\\n\\n'.format(func_name)) filt = codemap.calls(func_name) for caller_name, caller in code_map.funcs_sorted(filt): if caller.private: f.write('* {}",
"graph_module(f, code_map, mod_name, mod) os.system('dot -Tpng -O {}'.format(filename)) # Function pages def ispub(kv):",
"return False callgraph(f, code_map, mod_touches_func, func_touches_func, mark_func=func_name) def page_function(f, code_map, func_name, func): mod_link",
"def graph_function(f, code_map, func_name, func): # Filter for modules that contain or contain",
"table_list(f, func.sideeffects) f.write('## Callgraph:\\n\\n') f.write('\\n\\n'.format(func_graph_name(func_name))) f.write('## Functions called by {}\\n\\n'.format(func_name)) filt = codemap.iscalledby(func)",
"= line[findPtr + 2:].lstrip().rstrip() table += '|`{}`|->|{}|\\n'.format(name, desc) elif findEq > 0: has_table",
"mod in code_map.mods_sorted(): for callee_name in mod.calls: f.write('\\t{} -> {};\\n'.format(mod_name, callee_name)) f.write('}\\n') def",
"in, are called by, or call a module def func_touches_mod(kv): test_name = kv[0]",
"callee_name in mod.calls: f.write('\\t{} -> {};\\n'.format(mod_name, callee_name)) f.write('}\\n') def page_mod_index(f, code_map): f.write('# Module",
"= True lines += '* {}\\n'.format(line) if (not has_table) and (not has_lines): f.write('None\\n\\n')",
"return not kv[1].private callgraph(f, code_map, all_mods, public_funcs) def page_func_index(f, code_map): f.write('# Function Index\\n\\n')",
"mod in code_map.mods_sorted(): filename = os.path.join(output_dir, mod_page_name(mod_name)) with open(filename, 'w') as f: page_module(f,",
"func_filter((func_name, func)): f.write('\\t\\t{};\\n'.format(func_name)) f.write('\\t}\\n') for func_name, func in code_map.funcs_sorted(func_filter): if func_name == mark_func:",
"test_name == func.module: return True for f_name in test.functions: f = code_map.funcs[f_name] if",
"findEq = line.find('=') if findPtr > 0: has_table = True name = line[:findPtr].lstrip().rstrip()",
"has_lines: f.write('{}\\n'.format(lines)) def callgraph(f, code_map, mod_filter, func_filter, mark_mod=None, mark_func=None): f.write('digraph Callgraph {\\n') for",
"True if test_name in func.calls: return True if func_name in test.calls: return True",
"mark_func=None): f.write('digraph Callgraph {\\n') for mod_name, mod in code_map.mods_sorted(mod_filter): f.write('\\tsubgraph cluster_{} {{\\n'.format(mod_name)) f.write('\\t\\tnode",
"{}\\n\\n'.format(mod_name)) filt = codemap.iscalledby(mod) for callee_name, callee in code_map.mods_sorted(filt): callee_link = link(callee_name, mod_page_name(callee_name))",
"else: caller_link = link(caller_name, func_page_name(caller_name)) f.write('* {} - {}\\n'.format(caller_link, caller.brief)) f.write('\\n') # ------------------------------------------------------------------------------",
"func_name, func) filename = os.path.join(output_dir, func_graph_name(func_name)) with open(filename, 'w') as f: graph_function(f, code_map,",
"caller.private: f.write('* {} - {}\\n'.format(caller_name, caller.brief)) else: caller_link = link(caller_name, func_page_name(caller_name)) f.write('* {}",
"mod_page_name(mod_name): return os.path.join('mods', '{}.md'.format(mod_name)) def mod_graph_name(mod_name): return os.path.join('mods', '{}.dot'.format(mod_name)) # ------------------------------------------------------------------------------ # Helpful",
"+ 2:].lstrip().rstrip() table += '|`{}`|->|{}|\\n'.format(name, desc) elif findEq > 0: has_table = True",
"# Module pages for mod_name, mod in code_map.mods_sorted(): filename = os.path.join(output_dir, mod_page_name(mod_name)) with",
"desc) elif findEq > 0: has_table = True name = line[:findEq].lstrip().rstrip() desc =",
"in line_list: findPtr = line.find('->') findEq = line.find('=') if findPtr > 0: has_table",
"'{}.md'.format(func_name)) def func_graph_name(func_name): return os.path.join('funcs', '{}.dot'.format(func_name)) def mod_page_name(mod_name): return os.path.join('mods', '{}.md'.format(mod_name)) def mod_graph_name(mod_name):",
"callers/callees of func def func_touches_func(kv): test_name = kv[0] test = kv[1] if test_name",
"kv[0] test = kv[1] if test_name == func_name: return True if test_name in",
"mark_func: f.write('{} [color=lightblue];\\n'.format(func_name)) elif func.private: f.write('{} [color=lightgrey];\\n'.format(func_name)) for callee_name in func.calls: callee =",
"= True name = line[:findPtr].lstrip().rstrip() desc = line[findPtr + 2:].lstrip().rstrip() table += '|`{}`|->|{}|\\n'.format(name,",
"# ------------------------------------------------------------------------------ # Helpful builder functions def link(text, filename): return '[{}]({})'.format(text, text) def",
"line.find('->') findEq = line.find('=') if findPtr > 0: has_table = True name =",
"os.path.join(output_dir, func_index_name()) with open(filename, 'w') as f: page_func_index(f, code_map) filename = os.path.join(output_dir, func_index_graph_name())",
"False has_lines = False table = '|location||description|\\n' table += '|:---|:---:|:---|\\n' lines = ''",
"code_map.funcs[func_name] if func_name in test.calls: return True if test_name in func.calls: return True",
"+= '|`{}`|->|{}|\\n'.format(name, desc) elif findEq > 0: has_table = True name = line[:findEq].lstrip().rstrip()",
"def mod_touches_func(kv): test_name = kv[0] test = kv[1] if test_name == func.module: return",
"in code_map.funcs_sorted(filt): func_link = link(func_name, func_page_name(func_name)) f.write(' * {} - {}\\n'.format(func_link, func.brief)) def",
"in code_map.funcs_sorted(filt): func_link = link(func_name, func_page_name(func_name)) f.write('* {} - {}\\n'.format(func_link, func.brief)) f.write('\\n') f.write('##",
"= os.path.join(output_dir, func_index_graph_name()) with open(filename, 'w') as f: graph_func_index(f, code_map) os.system('dot -Tpng -O",
"main(): code_map = codemap.CodeMap() builder = codemap.MapBuilder(code_map) for token in scanner.scan_project('./src'): builder.absorb_token(token) build_dox(code_map,",
"table += '|`{}`|=|{}|\\n'.format(name, desc) elif line != '': has_lines = True lines +=",
"func in code_map.funcs_sorted(filt): func_link = link(func_name, func_page_name(func_name)) f.write('* {} - {}\\n'.format(func_link, func.brief)) f.write('\\n')",
"= codemap.calls(func_name) for caller_name, caller in code_map.funcs_sorted(filt): if caller.private: f.write('* {} - {}\\n'.format(caller_name,",
"def mod_index_name(): return 'Module-Index.md' def mod_index_graph_name(): return 'mod_index_graph.dot' def func_page_name(func_name): return os.path.join('funcs', '{}.md'.format(func_name))",
"code_map.mods_sorted(): mod_link = link(mod_name, mod_page_name(mod_name)) f.write('* {} - {}\\n'.format(mod_link, mod.brief)) def graph_func_index(f, code_map):",
"def page_func_index(f, code_map): f.write('# Function Index\\n\\n') f.write('\\n\\n'.format(func_index_graph_name())) for mod_name, mod in code_map.mods_sorted():",
"return True return False callgraph(f, code_map, mod_touches_mod, func_touches_mod, mark_mod=mod_name) def page_module(f, code_map, mod_name,",
"filt = codemap.calls(func_name) for caller_name, caller in code_map.funcs_sorted(filt): if caller.private: f.write('* {} -",
"mod_name, mod in code_map.mods_sorted(mod_filter): f.write('\\tsubgraph cluster_{} {{\\n'.format(mod_name)) f.write('\\t\\tnode [style=filled, color=white];\\n') f.write('\\t\\tstyle = filled;\\n')",
"f.write('\\t{} -> {};\\n'.format(func_name, callee_name)) f.write('}\\n') # ------------------------------------------------------------------------------ # Output file builders def graph_mod_index(f,",
"def graph_func_index(f, code_map): def all_mods(kv): return True def public_funcs(kv): return not kv[1].private callgraph(f,",
"code_map.mods_sorted(filt): callee_link = link(callee_name, mod_page_name(callee_name)) f.write('* {} - {}\\n'.format(callee_link, callee.brief)) f.write('\\n') f.write('## Modules",
"= '|location||description|\\n' table += '|:---|:---:|:---|\\n' lines = '' for line in line_list: findPtr",
"output_dir): f = sys.stdout # Module index page filename = os.path.join(output_dir, mod_index_name()) with",
"f: page_func_index(f, code_map) filename = os.path.join(output_dir, func_index_graph_name()) with open(filename, 'w') as f: graph_func_index(f,",
"mod_index_name()) with open(filename, 'w') as f: page_mod_index(f, code_map) filename = os.path.join(output_dir, mod_index_graph_name()) with",
"filename = os.path.join(output_dir, func_page_name(func_name)) with open(filename, 'w') as f: page_function(f, code_map, func_name, func)",
"code_map.funcs_sorted(ispub): filename = os.path.join(output_dir, func_page_name(func_name)) with open(filename, 'w') as f: page_function(f, code_map, func_name,",
"modules that are, are called by, or call a module def mod_touches_mod(kv): test_name",
"test = kv[1] if test_name in mod.functions: return True for func_name in mod.functions:",
"link(text, filename): return '[{}]({})'.format(text, text) def table_list(f, line_list): has_table = False has_lines =",
"return 'Module-Index.md' def mod_index_graph_name(): return 'mod_index_graph.dot' def func_page_name(func_name): return os.path.join('funcs', '{}.md'.format(func_name)) def func_graph_name(func_name):",
"return True return False # Filter for modules that are, are called by,",
"# Filter for functions that are or are callers/callees of func def func_touches_func(kv):",
"modules that contain or contain callers/callees of func def mod_touches_func(kv): test_name = kv[0]",
"callee)): continue f.write('\\t{} -> {};\\n'.format(func_name, callee_name)) f.write('}\\n') # ------------------------------------------------------------------------------ # Output file builders",
"test_name = kv[0] test = kv[1] if test_name == func_name: return True if",
"else: callee_link = link(callee_name, func_page_name(callee_name)) f.write('* {} - {}\\n'.format(callee_link, callee.brief)) f.write('\\n') f.write('## Functions",
"func_name, func): mod_link = link(func.module, mod_page_name(func.module)) f.write('# Function {}.{}\\n\\n'.format(mod_link, func_name)) f.write('{}\\n\\n'.format(func.brief)) f.write('## Detail:\\n\\n')",
"Index\\n\\n') f.write('\\n\\n'.format(func_index_graph_name())) for mod_name, mod in code_map.mods_sorted(): mod_link = link(mod_name, mod_page_name(mod_name)) f.write('*",
"code_map, all_mods, public_funcs) def page_func_index(f, code_map): f.write('# Function Index\\n\\n') f.write('\\n\\n'.format(func_index_graph_name())) for mod_name,",
"code_map, func_name, func) filename = os.path.join(output_dir, func_graph_name(func_name)) with open(filename, 'w') as f: graph_function(f,",
"line[:findEq].lstrip().rstrip() desc = line[findEq + 2:].lstrip().rstrip() table += '|`{}`|=|{}|\\n'.format(name, desc) elif line !=",
"= codemap.inmodule(mod_name) ispub = codemap.ispublic() filt = lambda f : inmod(f) and ispub(f)",
"Callgraph]({}.png)\\n\\n'.format(mod_index_graph_name())) for mod_name, mod in code_map.mods_sorted(): mod_link = link(mod_name, mod_page_name(mod_name)) f.write('* {} -",
"def test(): pass def main(): code_map = codemap.CodeMap() builder = codemap.MapBuilder(code_map) for token",
"f.write(' * {} - {}\\n'.format(func_link, func.brief)) def graph_module(f, code_map, mod_name, mod): # Filter",
"= codemap.MapBuilder(code_map) for token in scanner.scan_project('./src'): builder.absorb_token(token) build_dox(code_map, './doc/vos64.wiki') if __name__ == '__main__':",
"return '[{}]({})'.format(text, text) def table_list(f, line_list): has_table = False has_lines = False table",
"os.path.join('mods', '{}.md'.format(mod_name)) def mod_graph_name(mod_name): return os.path.join('mods', '{}.dot'.format(mod_name)) # ------------------------------------------------------------------------------ # Helpful builder functions",
"page filename = os.path.join(output_dir, mod_index_name()) with open(filename, 'w') as f: page_mod_index(f, code_map) filename",
"{}\\n\\n'.format(mod_name)) f.write('{}\\n\\n'.format(mod.brief)) f.write('## Detail:\\n\\n') f.write('{}\\n\\n'.format(mod.detail)) f.write('## Callgraph:\\n\\n') f.write('\\n\\n'.format(mod_graph_name(mod_name))) f.write('## Public Functions:\\n\\n') inmod =",
"f.write('* {} - {}\\n'.format(caller_name, caller.brief)) f.write('\\n') def graph_function(f, code_map, func_name, func): # Filter",
"func): # Filter for modules that contain or contain callers/callees of func def",
"f.write('digraph Callgraph {\\n') for mod_name, mod in code_map.mods_sorted(): for callee_name in mod.calls: f.write('\\t{}",
"line[findEq + 2:].lstrip().rstrip() table += '|`{}`|=|{}|\\n'.format(name, desc) elif line != '': has_lines =",
"{};\\n'.format(func_name, callee_name)) f.write('}\\n') # ------------------------------------------------------------------------------ # Output file builders def graph_mod_index(f, code_map): f.write('digraph",
"f.write('{}\\n'.format(table)) elif has_lines: f.write('{}\\n'.format(lines)) def callgraph(f, code_map, mod_filter, func_filter, mark_mod=None, mark_func=None): f.write('digraph Callgraph",
"findPtr > 0: has_table = True name = line[:findPtr].lstrip().rstrip() desc = line[findPtr +",
"# ------------------------------------------------------------------------------ # Top-level documentation builder def build_dox(code_map, output_dir): f = sys.stdout #",
"that call {}\\n\\n'.format(mod_name)) filt = codemap.calls(mod_name) for caller_name, caller in code_map.mods_sorted(filt): caller_link =",
"= os.path.join(output_dir, mod_index_graph_name()) with open(filename, 'w') as f: graph_mod_index(f, code_map) os.system('dot -Tpng -O",
"= lambda f : inmod(f) and ispub(f) for func_name, func in code_map.funcs_sorted(filt): func_link",
"f.write('* {} - {}\\n'.format(callee_link, callee.brief)) f.write('\\n') f.write('## Modules that call {}\\n\\n'.format(mod_name)) filt =",
"continue f.write('\\t{} -> {};\\n'.format(func_name, callee_name)) f.write('}\\n') # ------------------------------------------------------------------------------ # Output file builders def",
"True return False callgraph(f, code_map, mod_touches_func, func_touches_func, mark_func=func_name) def page_function(f, code_map, func_name, func):",
"if test_name == func.module: return True for f_name in test.functions: f = code_map.funcs[f_name]",
"mod_name in code_map.mods[test_name].calls: return True return False callgraph(f, code_map, mod_touches_mod, func_touches_mod, mark_mod=mod_name) def",
"'{}.md'.format(mod_name)) def mod_graph_name(mod_name): return os.path.join('mods', '{}.dot'.format(mod_name)) # ------------------------------------------------------------------------------ # Helpful builder functions def",
"a module def mod_touches_mod(kv): test_name = kv[0] test = kv[1] if test_name ==",
"return True if test_name in func.calls: return True return False # Filter for",
"in code_map.funcs_sorted(func_filter): if func_name == mark_func: f.write('{} [color=lightblue];\\n'.format(func_name)) elif func.private: f.write('{} [color=lightgrey];\\n'.format(func_name)) for",
"True lines += '* {}\\n'.format(line) if (not has_table) and (not has_lines): f.write('None\\n\\n') elif",
"-> {};\\n'.format(mod_name, callee_name)) f.write('}\\n') def page_mod_index(f, code_map): f.write('# Module Index\\n\\n') f.write('\\n\\n'.format(mod_index_graph_name())) for",
"link(func_name, func_page_name(func_name)) f.write(' * {} - {}\\n'.format(func_link, func.brief)) def graph_module(f, code_map, mod_name, mod):",
"os.path.join(output_dir, mod_index_name()) with open(filename, 'w') as f: page_mod_index(f, code_map) filename = os.path.join(output_dir, mod_index_graph_name())",
"+ 2:].lstrip().rstrip() table += '|`{}`|=|{}|\\n'.format(name, desc) elif line != '': has_lines = True",
"code_map.funcs[func_name] if func_filter((func_name, func)): f.write('\\t\\t{};\\n'.format(func_name)) f.write('\\t}\\n') for func_name, func in code_map.funcs_sorted(func_filter): if func_name",
"contain or contain callers/callees of func def mod_touches_func(kv): test_name = kv[0] test =",
"func_index_name()) with open(filename, 'w') as f: page_func_index(f, code_map) filename = os.path.join(output_dir, func_index_graph_name()) with",
"-O {}'.format(filename)) # Function index page filename = os.path.join(output_dir, func_index_name()) with open(filename, 'w')",
"func.brief)) f.write('\\n') f.write('## Modules called by {}\\n\\n'.format(mod_name)) filt = codemap.iscalledby(mod) for callee_name, callee",
"graph_function(f, code_map, func_name, func): # Filter for modules that contain or contain callers/callees",
"f.write('\\t{} -> {};\\n'.format(mod_name, callee_name)) f.write('}\\n') def page_mod_index(f, code_map): f.write('# Module Index\\n\\n') f.write('\\n\\n'.format(mod_index_graph_name()))",
"import scanner import codemap # ------------------------------------------------------------------------------ # Parameterized output filenames def func_index_name(): return",
"# Filter for modules that contain or contain callers/callees of func def mod_touches_func(kv):",
"func_link = link(func_name, func_page_name(func_name)) f.write(' * {} - {}\\n'.format(func_link, func.brief)) def graph_module(f, code_map,",
"line[:findPtr].lstrip().rstrip() desc = line[findPtr + 2:].lstrip().rstrip() table += '|`{}`|->|{}|\\n'.format(name, desc) elif findEq >",
"return os.path.join('mods', '{}.md'.format(mod_name)) def mod_graph_name(mod_name): return os.path.join('mods', '{}.dot'.format(mod_name)) # ------------------------------------------------------------------------------ # Helpful builder",
"def func_graph_name(func_name): return os.path.join('funcs', '{}.dot'.format(func_name)) def mod_page_name(mod_name): return os.path.join('mods', '{}.md'.format(mod_name)) def mod_graph_name(mod_name): return",
"caller_link = link(caller_name, func_page_name(caller_name)) f.write('* {} - {}\\n'.format(caller_link, caller.brief)) f.write('\\n') # ------------------------------------------------------------------------------ #",
"Parameterized output filenames def func_index_name(): return 'Function-Index.md' def func_index_graph_name(): return 'func_index_graph.dot' def mod_index_name():",
"- {}\\n'.format(func_link, func.brief)) def graph_module(f, code_map, mod_name, mod): # Filter for functions that",
"== func.module: return True for f_name in test.functions: f = code_map.funcs[f_name] if func_name",
"f.write('\\t\\tcolor = lightblue;\\n') else: f.write('\\t\\tcolor = grey;\\n') f.write('\\t\\tlabel = \"Module {}\";\\n'.format(mod_name)) for func_name",
"code_map) os.system('dot -Tpng -O {}'.format(filename)) # Module pages for mod_name, mod in code_map.mods_sorted():",
"callee_name)) f.write('}\\n') def page_mod_index(f, code_map): f.write('# Module Index\\n\\n') f.write('\\n\\n'.format(mod_index_graph_name())) for mod_name, mod",
"# Module index page filename = os.path.join(output_dir, mod_index_name()) with open(filename, 'w') as f:",
"filename = os.path.join(output_dir, mod_page_name(mod_name)) with open(filename, 'w') as f: page_module(f, code_map, mod_name, mod)",
"caller in code_map.mods_sorted(filt): caller_link = link(caller_name, mod_page_name(caller_name)) f.write('* {} - {}\\n'.format(caller_name, caller.brief)) f.write('\\n')",
"func): mod_link = link(func.module, mod_page_name(func.module)) f.write('# Function {}.{}\\n\\n'.format(mod_link, func_name)) f.write('{}\\n\\n'.format(func.brief)) f.write('## Detail:\\n\\n') f.write('{}\\n\\n'.format(func.detail))",
"for mod_name, mod in code_map.mods_sorted(): for callee_name in mod.calls: f.write('\\t{} -> {};\\n'.format(mod_name, callee_name))",
"public_funcs(kv): return not kv[1].private callgraph(f, code_map, all_mods, public_funcs) def page_func_index(f, code_map): f.write('# Function",
"in func.calls: return True return False # Filter for modules that are, are",
"mod_link = link(func.module, mod_page_name(func.module)) f.write('# Function {}.{}\\n\\n'.format(mod_link, func_name)) f.write('{}\\n\\n'.format(func.brief)) f.write('## Detail:\\n\\n') f.write('{}\\n\\n'.format(func.detail)) f.write('##",
"Helpful builder functions def link(text, filename): return '[{}]({})'.format(text, text) def table_list(f, line_list): has_table",
"filt = codemap.iscalledby(func) for callee_name, callee in code_map.funcs_sorted(filt): if callee.private: f.write('* {} -",
"mod_link = link(mod_name, mod_page_name(mod_name)) f.write('* Module {} - {}:\\n'.format(mod_link, mod.brief)) inmod = codemap.inmodule(mod_name)",
"= codemap.iscalledby(func) for callee_name, callee in code_map.funcs_sorted(filt): if callee.private: f.write('* {} - {}\\n'.format(callee_name,",
"= sys.stdout # Module index page filename = os.path.join(output_dir, mod_index_name()) with open(filename, 'w')",
"all_mods, public_funcs) def page_func_index(f, code_map): f.write('# Function Index\\n\\n') f.write('\\n\\n'.format(func_index_graph_name())) for mod_name, mod",
"mod.brief)) def graph_func_index(f, code_map): def all_mods(kv): return True def public_funcs(kv): return not kv[1].private",
"return True if test_name in func.calls: return True if func_name in test.calls: return",
"open(filename, 'w') as f: graph_function(f, code_map, func_name, func) os.system('dot -Tpng -O {}'.format(filename)) #",
"return 'func_index_graph.dot' def mod_index_name(): return 'Module-Index.md' def mod_index_graph_name(): return 'mod_index_graph.dot' def func_page_name(func_name): return",
"= link(mod_name, mod_page_name(mod_name)) f.write('* Module {} - {}:\\n'.format(mod_link, mod.brief)) inmod = codemap.inmodule(mod_name) ispub",
"called by, or call a module def mod_touches_mod(kv): test_name = kv[0] test =",
"cluster_{} {{\\n'.format(mod_name)) f.write('\\t\\tnode [style=filled, color=white];\\n') f.write('\\t\\tstyle = filled;\\n') if mod_name == mark_mod: f.write('\\t\\tcolor",
"mod_graph_name(mod_name): return os.path.join('mods', '{}.dot'.format(mod_name)) # ------------------------------------------------------------------------------ # Helpful builder functions def link(text, filename):",
"f.write('\\n') f.write('## Functions that call {}\\n\\n'.format(func_name)) filt = codemap.calls(func_name) for caller_name, caller in",
"code_map, mod_touches_func, func_touches_func, mark_func=func_name) def page_function(f, code_map, func_name, func): mod_link = link(func.module, mod_page_name(func.module))",
"if callee.private: f.write('* {} - {}\\n'.format(callee_name, callee.brief)) else: callee_link = link(callee_name, func_page_name(callee_name)) f.write('*",
"codemap.MapBuilder(code_map) for token in scanner.scan_project('./src'): builder.absorb_token(token) build_dox(code_map, './doc/vos64.wiki') if __name__ == '__main__': main()",
"has_table = True name = line[:findPtr].lstrip().rstrip() desc = line[findPtr + 2:].lstrip().rstrip() table +=",
"code_map, mod_name, mod) filename = os.path.join(output_dir, mod_graph_name(mod_name)) with open(filename, 'w') as f: graph_module(f,",
"for caller_name, caller in code_map.mods_sorted(filt): caller_link = link(caller_name, mod_page_name(caller_name)) f.write('* {} - {}\\n'.format(caller_name,",
"kv[0] test = kv[1] if test_name == func.module: return True for f_name in",
"Callgraph:\\n\\n') f.write('\\n\\n'.format(func_graph_name(func_name))) f.write('## Functions called by {}\\n\\n'.format(func_name)) filt = codemap.iscalledby(func) for callee_name, callee",
"- {}:\\n'.format(mod_link, mod.brief)) inmod = codemap.inmodule(mod_name) ispub = codemap.ispublic() filt = lambda f",
"in mod.calls: return True if mod_name in code_map.mods[test_name].calls: return True return False callgraph(f,",
"func.private: f.write('{} [color=lightgrey];\\n'.format(func_name)) for callee_name in func.calls: callee = code_map.funcs[callee_name] if not func_filter((callee_name,",
"test_name == func_name: return True if test_name in func.calls: return True if func_name",
"func_page_name(func_name)) f.write('* {} - {}\\n'.format(func_link, func.brief)) f.write('\\n') f.write('## Modules called by {}\\n\\n'.format(mod_name)) filt",
"def mod_page_name(mod_name): return os.path.join('mods', '{}.md'.format(mod_name)) def mod_graph_name(mod_name): return os.path.join('mods', '{}.dot'.format(mod_name)) # ------------------------------------------------------------------------------ #",
"f = sys.stdout # Module index page filename = os.path.join(output_dir, mod_index_name()) with open(filename,",
"in code_map.funcs_sorted(filt): if caller.private: f.write('* {} - {}\\n'.format(caller_name, caller.brief)) else: caller_link = link(caller_name,",
"func_name, func): # Filter for modules that contain or contain callers/callees of func",
"test_name = kv[0] test = kv[1] if test_name == func.module: return True for",
"open(filename, 'w') as f: page_func_index(f, code_map) filename = os.path.join(output_dir, func_index_graph_name()) with open(filename, 'w')",
"f : inmod(f) and ispub(f) for func_name, func in code_map.funcs_sorted(filt): func_link = link(func_name,",
"are called by, or call a module def mod_touches_mod(kv): test_name = kv[0] test",
"{} - {}\\n'.format(callee_link, callee.brief)) f.write('\\n') f.write('## Functions that call {}\\n\\n'.format(func_name)) filt = codemap.calls(func_name)",
"code_map, mod_name, mod) os.system('dot -Tpng -O {}'.format(filename)) # Function pages def ispub(kv): return",
"test_name in func.calls: return True return False # Filter for modules that are,",
"{}\\n'.format(callee_link, callee.brief)) f.write('\\n') f.write('## Modules that call {}\\n\\n'.format(mod_name)) filt = codemap.calls(mod_name) for caller_name,",
"desc) elif line != '': has_lines = True lines += '* {}\\n'.format(line) if",
"code_map.mods_sorted(filt): caller_link = link(caller_name, mod_page_name(caller_name)) f.write('* {} - {}\\n'.format(caller_name, caller.brief)) f.write('\\n') def graph_function(f,",
"Filter for functions that are or are callers/callees of func def func_touches_func(kv): test_name",
"code_map.funcs_sorted(filt): if caller.private: f.write('* {} - {}\\n'.format(caller_name, caller.brief)) else: caller_link = link(caller_name, func_page_name(caller_name))",
"return False # Filter for functions that are or are callers/callees of func",
"f.write('{}\\n\\n'.format(func.detail)) f.write('## Pass:\\n\\n') table_list(f, func.inputs) f.write('## Return:\\n\\n') table_list(f, func.outputs) f.write('## Side Effects:\\n\\n') table_list(f,",
"= link(caller_name, mod_page_name(caller_name)) f.write('* {} - {}\\n'.format(caller_name, caller.brief)) f.write('\\n') def graph_function(f, code_map, func_name,",
"for line in line_list: findPtr = line.find('->') findEq = line.find('=') if findPtr >",
"(not has_lines): f.write('None\\n\\n') elif has_table: f.write('{}\\n'.format(table)) elif has_lines: f.write('{}\\n'.format(lines)) def callgraph(f, code_map, mod_filter,",
"open(filename, 'w') as f: graph_mod_index(f, code_map) os.system('dot -Tpng -O {}'.format(filename)) # Function index",
"f.write('\\n') # ------------------------------------------------------------------------------ # Top-level documentation builder def build_dox(code_map, output_dir): f = sys.stdout",
"f.write('* Module {} - {}:\\n'.format(mod_link, mod.brief)) inmod = codemap.inmodule(mod_name) ispub = codemap.ispublic() filt",
"Function {}.{}\\n\\n'.format(mod_link, func_name)) f.write('{}\\n\\n'.format(func.brief)) f.write('## Detail:\\n\\n') f.write('{}\\n\\n'.format(func.detail)) f.write('## Pass:\\n\\n') table_list(f, func.inputs) f.write('## Return:\\n\\n')",
"os.path.join('mods', '{}.dot'.format(mod_name)) # ------------------------------------------------------------------------------ # Helpful builder functions def link(text, filename): return '[{}]({})'.format(text,",
"f: page_mod_index(f, code_map) filename = os.path.join(output_dir, mod_index_graph_name()) with open(filename, 'w') as f: graph_mod_index(f,",
"elif has_table: f.write('{}\\n'.format(table)) elif has_lines: f.write('{}\\n'.format(lines)) def callgraph(f, code_map, mod_filter, func_filter, mark_mod=None, mark_func=None):",
"'{}.dot'.format(mod_name)) # ------------------------------------------------------------------------------ # Helpful builder functions def link(text, filename): return '[{}]({})'.format(text, text)",
"mod.calls: f.write('\\t{} -> {};\\n'.format(mod_name, callee_name)) f.write('}\\n') def page_mod_index(f, code_map): f.write('# Module Index\\n\\n') f.write('\\n\\n'.format(mod_graph_name(mod_name))) f.write('## Public Functions:\\n\\n') inmod = codemap.inmodule(mod_name) ispub = codemap.ispublic() filt",
"{}\\n'.format(callee_name, callee.brief)) else: callee_link = link(callee_name, func_page_name(callee_name)) f.write('* {} - {}\\n'.format(callee_link, callee.brief)) f.write('\\n')",
"{}\\n\\n'.format(func_name)) filt = codemap.iscalledby(func) for callee_name, callee in code_map.funcs_sorted(filt): if callee.private: f.write('* {}",
"that are in, are called by, or call a module def func_touches_mod(kv): test_name",
"are in, are called by, or call a module def func_touches_mod(kv): test_name =",
"def page_function(f, code_map, func_name, func): mod_link = link(func.module, mod_page_name(func.module)) f.write('# Function {}.{}\\n\\n'.format(mod_link, func_name))",
"called by, or call a module def func_touches_mod(kv): test_name = kv[0] test =",
"table += '|`{}`|->|{}|\\n'.format(name, desc) elif findEq > 0: has_table = True name =",
"output filenames def func_index_name(): return 'Function-Index.md' def func_index_graph_name(): return 'func_index_graph.dot' def mod_index_name(): return",
"f.write('{} [color=lightgrey];\\n'.format(func_name)) for callee_name in func.calls: callee = code_map.funcs[callee_name] if not func_filter((callee_name, callee)):",
"= line[:findEq].lstrip().rstrip() desc = line[findEq + 2:].lstrip().rstrip() table += '|`{}`|=|{}|\\n'.format(name, desc) elif line",
"code_map): def all_mods(kv): return True def public_funcs(kv): return not kv[1].private callgraph(f, code_map, all_mods,",
"f.write('{}\\n\\n'.format(mod.detail)) f.write('## Callgraph:\\n\\n') f.write('\\n\\n'.format(mod_graph_name(mod_name))) f.write('## Public Functions:\\n\\n') inmod = codemap.inmodule(mod_name) ispub = codemap.ispublic()",
"> 0: has_table = True name = line[:findEq].lstrip().rstrip() desc = line[findEq + 2:].lstrip().rstrip()",
"codemap.inmodule(mod_name) ispub = codemap.ispublic() filt = lambda f : inmod(f) and ispub(f) for",
"name = line[:findEq].lstrip().rstrip() desc = line[findEq + 2:].lstrip().rstrip() table += '|`{}`|=|{}|\\n'.format(name, desc) elif",
"return True return False callgraph(f, code_map, mod_touches_func, func_touches_func, mark_func=func_name) def page_function(f, code_map, func_name,",
"-O {}'.format(filename)) # ------------------------------------------------------------------------------ def test(): pass def main(): code_map = codemap.CodeMap() builder",
"'w') as f: page_function(f, code_map, func_name, func) filename = os.path.join(output_dir, func_graph_name(func_name)) with open(filename,",
"as f: page_mod_index(f, code_map) filename = os.path.join(output_dir, mod_index_graph_name()) with open(filename, 'w') as f:",
"kv[0] test = kv[1] if test_name in mod.functions: return True for func_name in",
"for func_name in mod.functions: func = code_map.funcs[func_name] if func_name in test.calls: return True",
"* {} - {}\\n'.format(func_link, func.brief)) def graph_module(f, code_map, mod_name, mod): # Filter for",
"True name = line[:findPtr].lstrip().rstrip() desc = line[findPtr + 2:].lstrip().rstrip() table += '|`{}`|->|{}|\\n'.format(name, desc)",
"for mod_name, mod in code_map.mods_sorted(mod_filter): f.write('\\tsubgraph cluster_{} {{\\n'.format(mod_name)) f.write('\\t\\tnode [style=filled, color=white];\\n') f.write('\\t\\tstyle =",
"open(filename, 'w') as f: graph_module(f, code_map, mod_name, mod) os.system('dot -Tpng -O {}'.format(filename)) #",
"public_funcs) def page_func_index(f, code_map): f.write('# Function Index\\n\\n') f.write('\\n\\n'.format(func_index_graph_name())) for mod_name, mod in",
"page_function(f, code_map, func_name, func): mod_link = link(func.module, mod_page_name(func.module)) f.write('# Function {}.{}\\n\\n'.format(mod_link, func_name)) f.write('{}\\n\\n'.format(func.brief))",
"{}\\n\\n'.format(mod_name)) filt = codemap.calls(mod_name) for caller_name, caller in code_map.mods_sorted(filt): caller_link = link(caller_name, mod_page_name(caller_name))",
"mod_page_name(mod_name)) f.write('* Module {} - {}:\\n'.format(mod_link, mod.brief)) inmod = codemap.inmodule(mod_name) ispub = codemap.ispublic()",
"code_map.mods_sorted(): mod_link = link(mod_name, mod_page_name(mod_name)) f.write('* Module {} - {}:\\n'.format(mod_link, mod.brief)) inmod =",
"def table_list(f, line_list): has_table = False has_lines = False table = '|location||description|\\n' table",
"return True if test_name in mod.calls: return True if mod_name in code_map.mods[test_name].calls: return",
"- {}\\n'.format(caller_name, caller.brief)) else: caller_link = link(caller_name, func_page_name(caller_name)) f.write('* {} - {}\\n'.format(caller_link, caller.brief))",
"called by {}\\n\\n'.format(mod_name)) filt = codemap.iscalledby(mod) for callee_name, callee in code_map.mods_sorted(filt): callee_link =",
"page_mod_index(f, code_map) filename = os.path.join(output_dir, mod_index_graph_name()) with open(filename, 'w') as f: graph_mod_index(f, code_map)",
"kv[1] if test_name == func.module: return True for f_name in test.functions: f =",
"func_touches_func(kv): test_name = kv[0] test = kv[1] if test_name == func_name: return True",
"code_map.mods_sorted(): filename = os.path.join(output_dir, mod_page_name(mod_name)) with open(filename, 'w') as f: page_module(f, code_map, mod_name,",
"True if mod_name in code_map.mods[test_name].calls: return True return False callgraph(f, code_map, mod_touches_mod, func_touches_mod,",
"page_func_index(f, code_map) filename = os.path.join(output_dir, func_index_graph_name()) with open(filename, 'w') as f: graph_func_index(f, code_map)",
"line_list): has_table = False has_lines = False table = '|location||description|\\n' table += '|:---|:---:|:---|\\n'",
"os.path.join(output_dir, mod_page_name(mod_name)) with open(filename, 'w') as f: page_module(f, code_map, mod_name, mod) filename =",
"func_name in f.calls: return True if f_name in func.calls: return True return False",
"inmod(f) and ispub(f) for func_name, func in code_map.funcs_sorted(filt): func_link = link(func_name, func_page_name(func_name)) f.write('*",
"'Function-Index.md' def func_index_graph_name(): return 'func_index_graph.dot' def mod_index_name(): return 'Module-Index.md' def mod_index_graph_name(): return 'mod_index_graph.dot'",
"in code_map.mods_sorted(filt): caller_link = link(caller_name, mod_page_name(caller_name)) f.write('* {} - {}\\n'.format(caller_name, caller.brief)) f.write('\\n') def",
"link(caller_name, func_page_name(caller_name)) f.write('* {} - {}\\n'.format(caller_link, caller.brief)) f.write('\\n') # ------------------------------------------------------------------------------ # Top-level documentation",
"------------------------------------------------------------------------------ # Output file builders def graph_mod_index(f, code_map): f.write('digraph Callgraph {\\n') for mod_name,",
"+= '|`{}`|=|{}|\\n'.format(name, desc) elif line != '': has_lines = True lines += '*",
"mark_mod=mod_name) def page_module(f, code_map, mod_name, mod): f.write('# Module {}\\n\\n'.format(mod_name)) f.write('{}\\n\\n'.format(mod.brief)) f.write('## Detail:\\n\\n') f.write('{}\\n\\n'.format(mod.detail))",
"+= '* {}\\n'.format(line) if (not has_table) and (not has_lines): f.write('None\\n\\n') elif has_table: f.write('{}\\n'.format(table))",
"func.module: return True for f_name in test.functions: f = code_map.funcs[f_name] if func_name in",
"f.write('\\n') f.write('## Modules called by {}\\n\\n'.format(mod_name)) filt = codemap.iscalledby(mod) for callee_name, callee in",
"lightblue;\\n') else: f.write('\\t\\tcolor = grey;\\n') f.write('\\t\\tlabel = \"Module {}\";\\n'.format(mod_name)) for func_name in mod.functions:",
"return False # Filter for modules that are, are called by, or call",
"code_map, func_name, func): # Filter for modules that contain or contain callers/callees of",
"filename = os.path.join(output_dir, mod_index_name()) with open(filename, 'w') as f: page_mod_index(f, code_map) filename =",
"a module def func_touches_mod(kv): test_name = kv[0] test = kv[1] if test_name in",
"code_map): f.write('# Module Index\\n\\n') f.write('\\n\\n'.format(mod_index_graph_name())) for mod_name, mod in code_map.mods_sorted(): mod_link =",
"f.write('## Return:\\n\\n') table_list(f, func.outputs) f.write('## Side Effects:\\n\\n') table_list(f, func.sideeffects) f.write('## Callgraph:\\n\\n') f.write('\\n\\n'.format(func_graph_name(func_name))) f.write('##",
"test(): pass def main(): code_map = codemap.CodeMap() builder = codemap.MapBuilder(code_map) for token in",
"= kv[0] test = kv[1] if test_name == func.module: return True for f_name",
"func.brief)) def graph_module(f, code_map, mod_name, mod): # Filter for functions that are in,",
"return True for func_name in mod.functions: func = code_map.funcs[func_name] if func_name in test.calls:",
"mod_index_name(): return 'Module-Index.md' def mod_index_graph_name(): return 'mod_index_graph.dot' def func_page_name(func_name): return os.path.join('funcs', '{}.md'.format(func_name)) def",
"f: page_function(f, code_map, func_name, func) filename = os.path.join(output_dir, func_graph_name(func_name)) with open(filename, 'w') as",
"False # Filter for modules that are, are called by, or call a",
"module def func_touches_mod(kv): test_name = kv[0] test = kv[1] if test_name in mod.functions:",
"f.write('# Function {}.{}\\n\\n'.format(mod_link, func_name)) f.write('{}\\n\\n'.format(func.brief)) f.write('## Detail:\\n\\n') f.write('{}\\n\\n'.format(func.detail)) f.write('## Pass:\\n\\n') table_list(f, func.inputs) f.write('##",
"f.write('\\t\\tnode [style=filled, color=white];\\n') f.write('\\t\\tstyle = filled;\\n') if mod_name == mark_mod: f.write('\\t\\tcolor = lightblue;\\n')",
"if mod_name == mark_mod: f.write('\\t\\tcolor = lightblue;\\n') else: f.write('\\t\\tcolor = grey;\\n') f.write('\\t\\tlabel =",
"True if test_name in func.calls: return True return False # Filter for modules",
"for f_name in test.functions: f = code_map.funcs[f_name] if func_name in f.calls: return True",
"in test.functions: f = code_map.funcs[f_name] if func_name in f.calls: return True if f_name",
"for mod_name, mod in code_map.mods_sorted(): filename = os.path.join(output_dir, mod_page_name(mod_name)) with open(filename, 'w') as",
"ispub(kv): return not kv[1].private for func_name, func in code_map.funcs_sorted(ispub): filename = os.path.join(output_dir, func_page_name(func_name))",
"2:].lstrip().rstrip() table += '|`{}`|=|{}|\\n'.format(name, desc) elif line != '': has_lines = True lines",
"filename = os.path.join(output_dir, func_graph_name(func_name)) with open(filename, 'w') as f: graph_function(f, code_map, func_name, func)",
"for callee_name, callee in code_map.funcs_sorted(filt): if callee.private: f.write('* {} - {}\\n'.format(callee_name, callee.brief)) else:",
"f.write('## Functions called by {}\\n\\n'.format(func_name)) filt = codemap.iscalledby(func) for callee_name, callee in code_map.funcs_sorted(filt):",
"index page filename = os.path.join(output_dir, mod_index_name()) with open(filename, 'w') as f: page_mod_index(f, code_map)",
"return True for f_name in test.functions: f = code_map.funcs[f_name] if func_name in f.calls:",
"f.write('## Callgraph:\\n\\n') f.write('\\n\\n'.format(func_graph_name(func_name))) f.write('## Functions called by {}\\n\\n'.format(func_name)) filt = codemap.iscalledby(func) for callee_name,",
"func def func_touches_func(kv): test_name = kv[0] test = kv[1] if test_name == func_name:",
"mod in code_map.mods_sorted(mod_filter): f.write('\\tsubgraph cluster_{} {{\\n'.format(mod_name)) f.write('\\t\\tnode [style=filled, color=white];\\n') f.write('\\t\\tstyle = filled;\\n') if",
"Callgraph {\\n') for mod_name, mod in code_map.mods_sorted(): for callee_name in mod.calls: f.write('\\t{} ->",
"Modules called by {}\\n\\n'.format(mod_name)) filt = codemap.iscalledby(mod) for callee_name, callee in code_map.mods_sorted(filt): callee_link",
"= kv[1] if test_name == func_name: return True if test_name in func.calls: return",
"if func_name in test.calls: return True return False callgraph(f, code_map, mod_touches_func, func_touches_func, mark_func=func_name)",
"True for func_name in mod.functions: func = code_map.funcs[func_name] if func_name in test.calls: return",
"'|location||description|\\n' table += '|:---|:---:|:---|\\n' lines = '' for line in line_list: findPtr =",
"callers/callees of func def mod_touches_func(kv): test_name = kv[0] test = kv[1] if test_name",
"func_name, func) os.system('dot -Tpng -O {}'.format(filename)) # ------------------------------------------------------------------------------ def test(): pass def main():",
"with open(filename, 'w') as f: page_func_index(f, code_map) filename = os.path.join(output_dir, func_index_graph_name()) with open(filename,",
"func) os.system('dot -Tpng -O {}'.format(filename)) # ------------------------------------------------------------------------------ def test(): pass def main(): code_map",
"def build_dox(code_map, output_dir): f = sys.stdout # Module index page filename = os.path.join(output_dir,",
"func_touches_mod, mark_mod=mod_name) def page_module(f, code_map, mod_name, mod): f.write('# Module {}\\n\\n'.format(mod_name)) f.write('{}\\n\\n'.format(mod.brief)) f.write('## Detail:\\n\\n')",
"by {}\\n\\n'.format(func_name)) filt = codemap.iscalledby(func) for callee_name, callee in code_map.funcs_sorted(filt): if callee.private: f.write('*",
"open(filename, 'w') as f: page_module(f, code_map, mod_name, mod) filename = os.path.join(output_dir, mod_graph_name(mod_name)) with",
"'w') as f: graph_module(f, code_map, mod_name, mod) os.system('dot -Tpng -O {}'.format(filename)) # Function",
"ispub(f) for func_name, func in code_map.funcs_sorted(filt): func_link = link(func_name, func_page_name(func_name)) f.write(' * {}",
"-Tpng -O {}'.format(filename)) # Function index page filename = os.path.join(output_dir, func_index_name()) with open(filename,",
"Effects:\\n\\n') table_list(f, func.sideeffects) f.write('## Callgraph:\\n\\n') f.write('\\n\\n'.format(func_graph_name(func_name))) f.write('## Functions called by {}\\n\\n'.format(func_name)) filt =",
"and ispub(f) for func_name, func in code_map.funcs_sorted(filt): func_link = link(func_name, func_page_name(func_name)) f.write('* {}",
"for callee_name in mod.calls: f.write('\\t{} -> {};\\n'.format(mod_name, callee_name)) f.write('}\\n') def page_mod_index(f, code_map): f.write('#",
"func.calls: return True if func_name in test.calls: return True return False callgraph(f, code_map,",
"pages for mod_name, mod in code_map.mods_sorted(): filename = os.path.join(output_dir, mod_page_name(mod_name)) with open(filename, 'w')",
"func_page_name(func_name)) with open(filename, 'w') as f: page_function(f, code_map, func_name, func) filename = os.path.join(output_dir,",
"kv[1] if test_name in mod.functions: return True for func_name in mod.functions: func =",
"color=white];\\n') f.write('\\t\\tstyle = filled;\\n') if mod_name == mark_mod: f.write('\\t\\tcolor = lightblue;\\n') else: f.write('\\t\\tcolor",
"'' for line in line_list: findPtr = line.find('->') findEq = line.find('=') if findPtr",
"f.write('## Detail:\\n\\n') f.write('{}\\n\\n'.format(mod.detail)) f.write('## Callgraph:\\n\\n') f.write('\\n\\n'.format(mod_graph_name(mod_name))) f.write('## Public Functions:\\n\\n') inmod = codemap.inmodule(mod_name) ispub",
"elif func.private: f.write('{} [color=lightgrey];\\n'.format(func_name)) for callee_name in func.calls: callee = code_map.funcs[callee_name] if not",
"mod_page_name(mod_name)) f.write('* {} - {}\\n'.format(mod_link, mod.brief)) def graph_func_index(f, code_map): def all_mods(kv): return True",
"True return False callgraph(f, code_map, mod_touches_mod, func_touches_mod, mark_mod=mod_name) def page_module(f, code_map, mod_name, mod):",
"that are or are callers/callees of func def func_touches_func(kv): test_name = kv[0] test",
"codemap.ispublic() filt = lambda f : inmod(f) and ispub(f) for func_name, func in",
"Function Index\\n\\n') f.write('\\n\\n'.format(func_index_graph_name())) for mod_name, mod in code_map.mods_sorted(): mod_link = link(mod_name, mod_page_name(mod_name))",
"for mod_name, mod in code_map.mods_sorted(): mod_link = link(mod_name, mod_page_name(mod_name)) f.write('* {} - {}\\n'.format(mod_link,",
"f.write('## Modules that call {}\\n\\n'.format(mod_name)) filt = codemap.calls(mod_name) for caller_name, caller in code_map.mods_sorted(filt):",
"= line.find('=') if findPtr > 0: has_table = True name = line[:findPtr].lstrip().rstrip() desc",
"Pass:\\n\\n') table_list(f, func.inputs) f.write('## Return:\\n\\n') table_list(f, func.outputs) f.write('## Side Effects:\\n\\n') table_list(f, func.sideeffects) f.write('##",
"- {}\\n'.format(callee_name, callee.brief)) else: callee_link = link(callee_name, func_page_name(callee_name)) f.write('* {} - {}\\n'.format(callee_link, callee.brief))",
"{};\\n'.format(mod_name, callee_name)) f.write('}\\n') def page_mod_index(f, code_map): f.write('# Module Index\\n\\n') f.write('\\n\\n'.format(mod_index_graph_name())) for mod_name,",
"= False table = '|location||description|\\n' table += '|:---|:---:|:---|\\n' lines = '' for line",
"that call {}\\n\\n'.format(func_name)) filt = codemap.calls(func_name) for caller_name, caller in code_map.funcs_sorted(filt): if caller.private:",
"True if func_name in test.calls: return True return False callgraph(f, code_map, mod_touches_func, func_touches_func,",
"table_list(f, func.outputs) f.write('## Side Effects:\\n\\n') table_list(f, func.sideeffects) f.write('## Callgraph:\\n\\n') f.write('\\n\\n'.format(func_graph_name(func_name))) f.write('## Functions called",
"- {}\\n'.format(caller_link, caller.brief)) f.write('\\n') # ------------------------------------------------------------------------------ # Top-level documentation builder def build_dox(code_map, output_dir):",
"mod_name, mod in code_map.mods_sorted(): mod_link = link(mod_name, mod_page_name(mod_name)) f.write('* {} - {}\\n'.format(mod_link, mod.brief))",
"Functions called by {}\\n\\n'.format(func_name)) filt = codemap.iscalledby(func) for callee_name, callee in code_map.funcs_sorted(filt): if",
"mark_mod: f.write('\\t\\tcolor = lightblue;\\n') else: f.write('\\t\\tcolor = grey;\\n') f.write('\\t\\tlabel = \"Module {}\";\\n'.format(mod_name)) for",
"in f.calls: return True if f_name in func.calls: return True return False #",
"# Top-level documentation builder def build_dox(code_map, output_dir): f = sys.stdout # Module index",
"elif findEq > 0: has_table = True name = line[:findEq].lstrip().rstrip() desc = line[findEq",
"{\\n') for mod_name, mod in code_map.mods_sorted(mod_filter): f.write('\\tsubgraph cluster_{} {{\\n'.format(mod_name)) f.write('\\t\\tnode [style=filled, color=white];\\n') f.write('\\t\\tstyle",
"<gh_stars>1-10 #!/usr/bin/env python3 import os import sys import scanner import codemap # ------------------------------------------------------------------------------",
"func.calls: return True return False # Filter for modules that are, are called",
"findPtr = line.find('->') findEq = line.find('=') if findPtr > 0: has_table = True",
"code_map, mod_filter, func_filter, mark_mod=None, mark_func=None): f.write('digraph Callgraph {\\n') for mod_name, mod in code_map.mods_sorted(mod_filter):",
"mod_name, mod in code_map.mods_sorted(): for callee_name in mod.calls: f.write('\\t{} -> {};\\n'.format(mod_name, callee_name)) f.write('}\\n')",
"mod_name, mod in code_map.mods_sorted(): filename = os.path.join(output_dir, mod_page_name(mod_name)) with open(filename, 'w') as f:",
"mod_page_name(callee_name)) f.write('* {} - {}\\n'.format(callee_link, callee.brief)) f.write('\\n') f.write('## Modules that call {}\\n\\n'.format(mod_name)) filt",
"filename = os.path.join(output_dir, func_index_name()) with open(filename, 'w') as f: page_func_index(f, code_map) filename =",
"{}\\n'.format(caller_name, caller.brief)) f.write('\\n') def graph_function(f, code_map, func_name, func): # Filter for modules that",
"False # Filter for functions that are or are callers/callees of func def",
"if mod_name in code_map.mods[test_name].calls: return True return False callgraph(f, code_map, mod_touches_mod, func_touches_mod, mark_mod=mod_name)",
"{} - {}\\n'.format(caller_link, caller.brief)) f.write('\\n') # ------------------------------------------------------------------------------ # Top-level documentation builder def build_dox(code_map,",
"func_name, func in code_map.funcs_sorted(filt): func_link = link(func_name, func_page_name(func_name)) f.write(' * {} - {}\\n'.format(func_link,",
"os.path.join(output_dir, func_page_name(func_name)) with open(filename, 'w') as f: page_function(f, code_map, func_name, func) filename =",
"Callgraph]({}.png)\\n\\n'.format(func_index_graph_name())) for mod_name, mod in code_map.mods_sorted(): mod_link = link(mod_name, mod_page_name(mod_name)) f.write('* Module {}",
"mod_name: return True if test_name in mod.calls: return True if mod_name in code_map.mods[test_name].calls:",
"that are, are called by, or call a module def mod_touches_mod(kv): test_name =",
"func_filter, mark_mod=None, mark_func=None): f.write('digraph Callgraph {\\n') for mod_name, mod in code_map.mods_sorted(mod_filter): f.write('\\tsubgraph cluster_{}",
"lambda f : inmod(f) and ispub(f) for func_name, func in code_map.funcs_sorted(filt): func_link =",
"mod_graph_name(mod_name)) with open(filename, 'w') as f: graph_module(f, code_map, mod_name, mod) os.system('dot -Tpng -O",
"mod.functions: func = code_map.funcs[func_name] if func_name in test.calls: return True if test_name in",
"mod_touches_func(kv): test_name = kv[0] test = kv[1] if test_name == func.module: return True",
"{}\\n'.format(mod_link, mod.brief)) def graph_func_index(f, code_map): def all_mods(kv): return True def public_funcs(kv): return not",
"call {}\\n\\n'.format(func_name)) filt = codemap.calls(func_name) for caller_name, caller in code_map.funcs_sorted(filt): if caller.private: f.write('*",
"= os.path.join(output_dir, mod_graph_name(mod_name)) with open(filename, 'w') as f: graph_module(f, code_map, mod_name, mod) os.system('dot",
"[style=filled, color=white];\\n') f.write('\\t\\tstyle = filled;\\n') if mod_name == mark_mod: f.write('\\t\\tcolor = lightblue;\\n') else:",
"[color=lightblue];\\n'.format(func_name)) elif func.private: f.write('{} [color=lightgrey];\\n'.format(func_name)) for callee_name in func.calls: callee = code_map.funcs[callee_name] if",
"f.write('\\t\\tlabel = \"Module {}\";\\n'.format(mod_name)) for func_name in mod.functions: func = code_map.funcs[func_name] if func_filter((func_name,",
"-> {};\\n'.format(func_name, callee_name)) f.write('}\\n') # ------------------------------------------------------------------------------ # Output file builders def graph_mod_index(f, code_map):",
"callee.brief)) f.write('\\n') f.write('## Modules that call {}\\n\\n'.format(mod_name)) filt = codemap.calls(mod_name) for caller_name, caller",
"f.write('## Public Functions:\\n\\n') inmod = codemap.inmodule(mod_name) ispub = codemap.ispublic() filt = lambda f",
"filename = os.path.join(output_dir, mod_index_graph_name()) with open(filename, 'w') as f: graph_mod_index(f, code_map) os.system('dot -Tpng",
"f.calls: return True if f_name in func.calls: return True return False # Filter",
"contain callers/callees of func def mod_touches_func(kv): test_name = kv[0] test = kv[1] if",
"def func_index_name(): return 'Function-Index.md' def func_index_graph_name(): return 'func_index_graph.dot' def mod_index_name(): return 'Module-Index.md' def",
"lines += '* {}\\n'.format(line) if (not has_table) and (not has_lines): f.write('None\\n\\n') elif has_table:",
"callgraph(f, code_map, mod_filter, func_filter, mark_mod=None, mark_func=None): f.write('digraph Callgraph {\\n') for mod_name, mod in",
"func_name: return True if test_name in func.calls: return True if func_name in test.calls:",
"functions that are in, are called by, or call a module def func_touches_mod(kv):",
"with open(filename, 'w') as f: graph_function(f, code_map, func_name, func) os.system('dot -Tpng -O {}'.format(filename))",
"'* {}\\n'.format(line) if (not has_table) and (not has_lines): f.write('None\\n\\n') elif has_table: f.write('{}\\n'.format(table)) elif",
"Module {} - {}:\\n'.format(mod_link, mod.brief)) inmod = codemap.inmodule(mod_name) ispub = codemap.ispublic() filt =",
"def callgraph(f, code_map, mod_filter, func_filter, mark_mod=None, mark_func=None): f.write('digraph Callgraph {\\n') for mod_name, mod",
"func in code_map.funcs_sorted(ispub): filename = os.path.join(output_dir, func_page_name(func_name)) with open(filename, 'w') as f: page_function(f,",
"code_map.mods[test_name].calls: return True return False callgraph(f, code_map, mod_touches_mod, func_touches_mod, mark_mod=mod_name) def page_module(f, code_map,",
"return True if func_name in test.calls: return True return False callgraph(f, code_map, mod_touches_func,",
"= codemap.iscalledby(mod) for callee_name, callee in code_map.mods_sorted(filt): callee_link = link(callee_name, mod_page_name(callee_name)) f.write('* {}",
"open(filename, 'w') as f: page_mod_index(f, code_map) filename = os.path.join(output_dir, mod_index_graph_name()) with open(filename, 'w')",
"func_touches_func, mark_func=func_name) def page_function(f, code_map, func_name, func): mod_link = link(func.module, mod_page_name(func.module)) f.write('# Function",
"f.write('\\n\\n'.format(mod_index_graph_name())) for mod_name, mod in code_map.mods_sorted(): mod_link = link(mod_name, mod_page_name(mod_name)) f.write('* {}",
"for func_name, func in code_map.funcs_sorted(filt): func_link = link(func_name, func_page_name(func_name)) f.write(' * {} -",
"code_map.funcs[callee_name] if not func_filter((callee_name, callee)): continue f.write('\\t{} -> {};\\n'.format(func_name, callee_name)) f.write('}\\n') # ------------------------------------------------------------------------------",
"for modules that are, are called by, or call a module def mod_touches_mod(kv):",
"func = code_map.funcs[func_name] if func_filter((func_name, func)): f.write('\\t\\t{};\\n'.format(func_name)) f.write('\\t}\\n') for func_name, func in code_map.funcs_sorted(func_filter):",
": inmod(f) and ispub(f) for func_name, func in code_map.funcs_sorted(filt): func_link = link(func_name, func_page_name(func_name))",
"f.write('\\n') f.write('## Modules that call {}\\n\\n'.format(mod_name)) filt = codemap.calls(mod_name) for caller_name, caller in",
"for func_name, func in code_map.funcs_sorted(ispub): filename = os.path.join(output_dir, func_page_name(func_name)) with open(filename, 'w') as",
"func_name in test.calls: return True if test_name in func.calls: return True return False",
"Module pages for mod_name, mod in code_map.mods_sorted(): filename = os.path.join(output_dir, mod_page_name(mod_name)) with open(filename,",
"Detail:\\n\\n') f.write('{}\\n\\n'.format(mod.detail)) f.write('## Callgraph:\\n\\n') f.write('\\n\\n'.format(mod_graph_name(mod_name))) f.write('## Public Functions:\\n\\n') inmod = codemap.inmodule(mod_name) ispub =",
"test_name = kv[0] test = kv[1] if test_name == mod_name: return True if",
"if func_name in f.calls: return True if f_name in func.calls: return True return",
"Callgraph {\\n') for mod_name, mod in code_map.mods_sorted(mod_filter): f.write('\\tsubgraph cluster_{} {{\\n'.format(mod_name)) f.write('\\t\\tnode [style=filled, color=white];\\n')",
"ispub = codemap.ispublic() filt = lambda f : inmod(f) and ispub(f) for func_name,",
"test.calls: return True return False callgraph(f, code_map, mod_touches_func, func_touches_func, mark_func=func_name) def page_function(f, code_map,",
"line_list: findPtr = line.find('->') findEq = line.find('=') if findPtr > 0: has_table =",
"0: has_table = True name = line[:findPtr].lstrip().rstrip() desc = line[findPtr + 2:].lstrip().rstrip() table",
"inmod(f) and ispub(f) for func_name, func in code_map.funcs_sorted(filt): func_link = link(func_name, func_page_name(func_name)) f.write('",
"f: graph_mod_index(f, code_map) os.system('dot -Tpng -O {}'.format(filename)) # Function index page filename =",
"filename = os.path.join(output_dir, func_index_graph_name()) with open(filename, 'w') as f: graph_func_index(f, code_map) os.system('dot -Tpng",
"f.write('## Side Effects:\\n\\n') table_list(f, func.sideeffects) f.write('## Callgraph:\\n\\n') f.write('\\n\\n'.format(func_graph_name(func_name))) f.write('## Functions called by {}\\n\\n'.format(func_name))",
"graph_func_index(f, code_map): def all_mods(kv): return True def public_funcs(kv): return not kv[1].private callgraph(f, code_map,",
"callee_name, callee in code_map.mods_sorted(filt): callee_link = link(callee_name, mod_page_name(callee_name)) f.write('* {} - {}\\n'.format(callee_link, callee.brief))",
"== func_name: return True if test_name in func.calls: return True if func_name in",
"callee.brief)) f.write('\\n') f.write('## Functions that call {}\\n\\n'.format(func_name)) filt = codemap.calls(func_name) for caller_name, caller",
"caller_name, caller in code_map.mods_sorted(filt): caller_link = link(caller_name, mod_page_name(caller_name)) f.write('* {} - {}\\n'.format(caller_name, caller.brief))",
"codemap.calls(func_name) for caller_name, caller in code_map.funcs_sorted(filt): if caller.private: f.write('* {} - {}\\n'.format(caller_name, caller.brief))",
"code_map = codemap.CodeMap() builder = codemap.MapBuilder(code_map) for token in scanner.scan_project('./src'): builder.absorb_token(token) build_dox(code_map, './doc/vos64.wiki')",
"elif has_lines: f.write('{}\\n'.format(lines)) def callgraph(f, code_map, mod_filter, func_filter, mark_mod=None, mark_func=None): f.write('digraph Callgraph {\\n')",
"= grey;\\n') f.write('\\t\\tlabel = \"Module {}\";\\n'.format(mod_name)) for func_name in mod.functions: func = code_map.funcs[func_name]",
"lines = '' for line in line_list: findPtr = line.find('->') findEq = line.find('=')",
"------------------------------------------------------------------------------ # Parameterized output filenames def func_index_name(): return 'Function-Index.md' def func_index_graph_name(): return 'func_index_graph.dot'",
"[color=lightgrey];\\n'.format(func_name)) for callee_name in func.calls: callee = code_map.funcs[callee_name] if not func_filter((callee_name, callee)): continue",
"for functions that are in, are called by, or call a module def",
"text) def table_list(f, line_list): has_table = False has_lines = False table = '|location||description|\\n'",
"in code_map.mods_sorted(): mod_link = link(mod_name, mod_page_name(mod_name)) f.write('* Module {} - {}:\\n'.format(mod_link, mod.brief)) inmod",
"return True if f_name in func.calls: return True return False # Filter for",
"filename): return '[{}]({})'.format(text, text) def table_list(f, line_list): has_table = False has_lines = False",
"= link(func.module, mod_page_name(func.module)) f.write('# Function {}.{}\\n\\n'.format(mod_link, func_name)) f.write('{}\\n\\n'.format(func.brief)) f.write('## Detail:\\n\\n') f.write('{}\\n\\n'.format(func.detail)) f.write('## Pass:\\n\\n')",
"- {}\\n'.format(callee_link, callee.brief)) f.write('\\n') f.write('## Modules that call {}\\n\\n'.format(mod_name)) filt = codemap.calls(mod_name) for",
"mod_page_name(func.module)) f.write('# Function {}.{}\\n\\n'.format(mod_link, func_name)) f.write('{}\\n\\n'.format(func.brief)) f.write('## Detail:\\n\\n') f.write('{}\\n\\n'.format(func.detail)) f.write('## Pass:\\n\\n') table_list(f, func.inputs)",
"return True return False # Filter for functions that are or are callers/callees",
"sys import scanner import codemap # ------------------------------------------------------------------------------ # Parameterized output filenames def func_index_name():",
"page filename = os.path.join(output_dir, func_index_name()) with open(filename, 'w') as f: page_func_index(f, code_map) filename",
"-O {}'.format(filename)) # Module pages for mod_name, mod in code_map.mods_sorted(): filename = os.path.join(output_dir,",
"= link(func_name, func_page_name(func_name)) f.write('* {} - {}\\n'.format(func_link, func.brief)) f.write('\\n') f.write('## Modules called by",
"or call a module def func_touches_mod(kv): test_name = kv[0] test = kv[1] if",
"True return False # Filter for modules that are, are called by, or",
"False callgraph(f, code_map, mod_touches_func, func_touches_func, mark_func=func_name) def page_function(f, code_map, func_name, func): mod_link =",
"{}'.format(filename)) # Function pages def ispub(kv): return not kv[1].private for func_name, func in",
"mod in code_map.mods_sorted(): mod_link = link(mod_name, mod_page_name(mod_name)) f.write('* Module {} - {}:\\n'.format(mod_link, mod.brief))",
"{}'.format(filename)) # Function index page filename = os.path.join(output_dir, func_index_name()) with open(filename, 'w') as",
"f.write('digraph Callgraph {\\n') for mod_name, mod in code_map.mods_sorted(mod_filter): f.write('\\tsubgraph cluster_{} {{\\n'.format(mod_name)) f.write('\\t\\tnode [style=filled,",
"desc = line[findEq + 2:].lstrip().rstrip() table += '|`{}`|=|{}|\\n'.format(name, desc) elif line != '':",
"mod.calls: return True if mod_name in code_map.mods[test_name].calls: return True return False callgraph(f, code_map,",
"os import sys import scanner import codemap # ------------------------------------------------------------------------------ # Parameterized output filenames",
"= line.find('->') findEq = line.find('=') if findPtr > 0: has_table = True name",
"for func_name in mod.functions: func = code_map.funcs[func_name] if func_filter((func_name, func)): f.write('\\t\\t{};\\n'.format(func_name)) f.write('\\t}\\n') for",
"has_table: f.write('{}\\n'.format(table)) elif has_lines: f.write('{}\\n'.format(lines)) def callgraph(f, code_map, mod_filter, func_filter, mark_mod=None, mark_func=None): f.write('digraph",
"code_map.mods_sorted(mod_filter): f.write('\\tsubgraph cluster_{} {{\\n'.format(mod_name)) f.write('\\t\\tnode [style=filled, color=white];\\n') f.write('\\t\\tstyle = filled;\\n') if mod_name ==",
"f.write('\\tsubgraph cluster_{} {{\\n'.format(mod_name)) f.write('\\t\\tnode [style=filled, color=white];\\n') f.write('\\t\\tstyle = filled;\\n') if mod_name == mark_mod:",
"kv[1].private callgraph(f, code_map, all_mods, public_funcs) def page_func_index(f, code_map): f.write('# Function Index\\n\\n') f.write('\\n\\n'.format(func_index_graph_name()))",
"# ------------------------------------------------------------------------------ # Output file builders def graph_mod_index(f, code_map): f.write('digraph Callgraph {\\n') for",
"callee_link = link(callee_name, mod_page_name(callee_name)) f.write('* {} - {}\\n'.format(callee_link, callee.brief)) f.write('\\n') f.write('## Modules that",
"'|`{}`|=|{}|\\n'.format(name, desc) elif line != '': has_lines = True lines += '* {}\\n'.format(line)",
"= lightblue;\\n') else: f.write('\\t\\tcolor = grey;\\n') f.write('\\t\\tlabel = \"Module {}\";\\n'.format(mod_name)) for func_name in",
"if not func_filter((callee_name, callee)): continue f.write('\\t{} -> {};\\n'.format(func_name, callee_name)) f.write('}\\n') # ------------------------------------------------------------------------------ #",
"func_page_name(caller_name)) f.write('* {} - {}\\n'.format(caller_link, caller.brief)) f.write('\\n') # ------------------------------------------------------------------------------ # Top-level documentation builder",
"{\\n') for mod_name, mod in code_map.mods_sorted(): for callee_name in mod.calls: f.write('\\t{} -> {};\\n'.format(mod_name,",
"in code_map.mods[test_name].calls: return True return False callgraph(f, code_map, mod_touches_mod, func_touches_mod, mark_mod=mod_name) def page_module(f,",
"Callgraph:\\n\\n') f.write('\\n\\n'.format(mod_graph_name(mod_name))) f.write('## Public Functions:\\n\\n') inmod = codemap.inmodule(mod_name) ispub = codemap.ispublic() filt =",
"mod_name, mod): # Filter for functions that are in, are called by, or",
"in code_map.mods_sorted(mod_filter): f.write('\\tsubgraph cluster_{} {{\\n'.format(mod_name)) f.write('\\t\\tnode [style=filled, color=white];\\n') f.write('\\t\\tstyle = filled;\\n') if mod_name",
"{}\\n'.format(func_link, func.brief)) f.write('\\n') f.write('## Modules called by {}\\n\\n'.format(mod_name)) filt = codemap.iscalledby(mod) for callee_name,",
"f.write('None\\n\\n') elif has_table: f.write('{}\\n'.format(table)) elif has_lines: f.write('{}\\n'.format(lines)) def callgraph(f, code_map, mod_filter, func_filter, mark_mod=None,",
"= filled;\\n') if mod_name == mark_mod: f.write('\\t\\tcolor = lightblue;\\n') else: f.write('\\t\\tcolor = grey;\\n')",
"Module index page filename = os.path.join(output_dir, mod_index_name()) with open(filename, 'w') as f: page_mod_index(f,",
"== mark_mod: f.write('\\t\\tcolor = lightblue;\\n') else: f.write('\\t\\tcolor = grey;\\n') f.write('\\t\\tlabel = \"Module {}\";\\n'.format(mod_name))",
"'mod_index_graph.dot' def func_page_name(func_name): return os.path.join('funcs', '{}.md'.format(func_name)) def func_graph_name(func_name): return os.path.join('funcs', '{}.dot'.format(func_name)) def mod_page_name(mod_name):",
"if test_name in mod.functions: return True for func_name in mod.functions: func = code_map.funcs[func_name]",
"'Module-Index.md' def mod_index_graph_name(): return 'mod_index_graph.dot' def func_page_name(func_name): return os.path.join('funcs', '{}.md'.format(func_name)) def func_graph_name(func_name): return",
"f.write('## Functions that call {}\\n\\n'.format(func_name)) filt = codemap.calls(func_name) for caller_name, caller in code_map.funcs_sorted(filt):",
"os.path.join('funcs', '{}.md'.format(func_name)) def func_graph_name(func_name): return os.path.join('funcs', '{}.dot'.format(func_name)) def mod_page_name(mod_name): return os.path.join('mods', '{}.md'.format(mod_name)) def",
"graph_function(f, code_map, func_name, func) os.system('dot -Tpng -O {}'.format(filename)) # ------------------------------------------------------------------------------ def test(): pass",
"{{\\n'.format(mod_name)) f.write('\\t\\tnode [style=filled, color=white];\\n') f.write('\\t\\tstyle = filled;\\n') if mod_name == mark_mod: f.write('\\t\\tcolor =",
"True if test_name in mod.calls: return True if mod_name in code_map.mods[test_name].calls: return True",
"line[findPtr + 2:].lstrip().rstrip() table += '|`{}`|->|{}|\\n'.format(name, desc) elif findEq > 0: has_table =",
"page_module(f, code_map, mod_name, mod): f.write('# Module {}\\n\\n'.format(mod_name)) f.write('{}\\n\\n'.format(mod.brief)) f.write('## Detail:\\n\\n') f.write('{}\\n\\n'.format(mod.detail)) f.write('## Callgraph:\\n\\n')",
"f.write('\\n\\n'.format(func_index_graph_name())) for mod_name, mod in code_map.mods_sorted(): mod_link = link(mod_name, mod_page_name(mod_name)) f.write('* Module",
"f.write('{} [color=lightblue];\\n'.format(func_name)) elif func.private: f.write('{} [color=lightgrey];\\n'.format(func_name)) for callee_name in func.calls: callee = code_map.funcs[callee_name]",
"mark_mod=None, mark_func=None): f.write('digraph Callgraph {\\n') for mod_name, mod in code_map.mods_sorted(mod_filter): f.write('\\tsubgraph cluster_{} {{\\n'.format(mod_name))",
"return os.path.join('mods', '{}.dot'.format(mod_name)) # ------------------------------------------------------------------------------ # Helpful builder functions def link(text, filename): return",
"'w') as f: page_mod_index(f, code_map) filename = os.path.join(output_dir, mod_index_graph_name()) with open(filename, 'w') as",
"mod) os.system('dot -Tpng -O {}'.format(filename)) # Function pages def ispub(kv): return not kv[1].private",
"0: has_table = True name = line[:findEq].lstrip().rstrip() desc = line[findEq + 2:].lstrip().rstrip() table",
"mod_touches_mod(kv): test_name = kv[0] test = kv[1] if test_name == mod_name: return True",
"with open(filename, 'w') as f: page_mod_index(f, code_map) filename = os.path.join(output_dir, mod_index_graph_name()) with open(filename,",
"build_dox(code_map, output_dir): f = sys.stdout # Module index page filename = os.path.join(output_dir, mod_index_name())",
"def mod_graph_name(mod_name): return os.path.join('mods', '{}.dot'.format(mod_name)) # ------------------------------------------------------------------------------ # Helpful builder functions def link(text,",
"(not has_table) and (not has_lines): f.write('None\\n\\n') elif has_table: f.write('{}\\n'.format(table)) elif has_lines: f.write('{}\\n'.format(lines)) def",
"func.calls: callee = code_map.funcs[callee_name] if not func_filter((callee_name, callee)): continue f.write('\\t{} -> {};\\n'.format(func_name, callee_name))",
"'w') as f: page_module(f, code_map, mod_name, mod) filename = os.path.join(output_dir, mod_graph_name(mod_name)) with open(filename,",
"ispub(f) for func_name, func in code_map.funcs_sorted(filt): func_link = link(func_name, func_page_name(func_name)) f.write('* {} -",
"mod_link = link(mod_name, mod_page_name(mod_name)) f.write('* {} - {}\\n'.format(mod_link, mod.brief)) def graph_func_index(f, code_map): def",
"f_name in func.calls: return True return False # Filter for functions that are",
"\"Module {}\";\\n'.format(mod_name)) for func_name in mod.functions: func = code_map.funcs[func_name] if func_filter((func_name, func)): f.write('\\t\\t{};\\n'.format(func_name))",
"builder def build_dox(code_map, output_dir): f = sys.stdout # Module index page filename =",
"Functions:\\n\\n') inmod = codemap.inmodule(mod_name) ispub = codemap.ispublic() filt = lambda f : inmod(f)",
"that contain or contain callers/callees of func def mod_touches_func(kv): test_name = kv[0] test",
"in func.calls: return True if func_name in test.calls: return True return False callgraph(f,",
"of func def func_touches_func(kv): test_name = kv[0] test = kv[1] if test_name ==",
"= line[findEq + 2:].lstrip().rstrip() table += '|`{}`|=|{}|\\n'.format(name, desc) elif line != '': has_lines",
"callee in code_map.mods_sorted(filt): callee_link = link(callee_name, mod_page_name(callee_name)) f.write('* {} - {}\\n'.format(callee_link, callee.brief)) f.write('\\n')",
"= line[:findPtr].lstrip().rstrip() desc = line[findPtr + 2:].lstrip().rstrip() table += '|`{}`|->|{}|\\n'.format(name, desc) elif findEq",
"-Tpng -O {}'.format(filename)) # Module pages for mod_name, mod in code_map.mods_sorted(): filename =",
"open(filename, 'w') as f: page_function(f, code_map, func_name, func) filename = os.path.join(output_dir, func_graph_name(func_name)) with",
"= os.path.join(output_dir, func_graph_name(func_name)) with open(filename, 'w') as f: graph_function(f, code_map, func_name, func) os.system('dot",
"f.write('* {} - {}\\n'.format(func_link, func.brief)) f.write('\\n') f.write('## Modules called by {}\\n\\n'.format(mod_name)) filt =",
"in code_map.mods_sorted(): mod_link = link(mod_name, mod_page_name(mod_name)) f.write('* {} - {}\\n'.format(mod_link, mod.brief)) def graph_func_index(f,",
"desc = line[findPtr + 2:].lstrip().rstrip() table += '|`{}`|->|{}|\\n'.format(name, desc) elif findEq > 0:",
"def mod_index_graph_name(): return 'mod_index_graph.dot' def func_page_name(func_name): return os.path.join('funcs', '{}.md'.format(func_name)) def func_graph_name(func_name): return os.path.join('funcs',",
"for func_name, func in code_map.funcs_sorted(filt): func_link = link(func_name, func_page_name(func_name)) f.write('* {} - {}\\n'.format(func_link,",
"= True name = line[:findEq].lstrip().rstrip() desc = line[findEq + 2:].lstrip().rstrip() table += '|`{}`|=|{}|\\n'.format(name,",
"# Output file builders def graph_mod_index(f, code_map): f.write('digraph Callgraph {\\n') for mod_name, mod",
"if func_name in test.calls: return True if test_name in func.calls: return True return",
"------------------------------------------------------------------------------ # Helpful builder functions def link(text, filename): return '[{}]({})'.format(text, text) def table_list(f,",
"table += '|:---|:---:|:---|\\n' lines = '' for line in line_list: findPtr = line.find('->')",
"f.write('\\t\\tcolor = grey;\\n') f.write('\\t\\tlabel = \"Module {}\";\\n'.format(mod_name)) for func_name in mod.functions: func =",
"{}\\n'.format(func_link, func.brief)) def graph_module(f, code_map, mod_name, mod): # Filter for functions that are",
"in test.calls: return True if test_name in func.calls: return True return False #",
"and ispub(f) for func_name, func in code_map.funcs_sorted(filt): func_link = link(func_name, func_page_name(func_name)) f.write(' *",
"= os.path.join(output_dir, func_index_name()) with open(filename, 'w') as f: page_func_index(f, code_map) filename = os.path.join(output_dir,",
"func_index_name(): return 'Function-Index.md' def func_index_graph_name(): return 'func_index_graph.dot' def mod_index_name(): return 'Module-Index.md' def mod_index_graph_name():",
"== mod_name: return True if test_name in mod.calls: return True if mod_name in",
"test_name = kv[0] test = kv[1] if test_name in mod.functions: return True for",
"page_module(f, code_map, mod_name, mod) filename = os.path.join(output_dir, mod_graph_name(mod_name)) with open(filename, 'w') as f:",
"2:].lstrip().rstrip() table += '|`{}`|->|{}|\\n'.format(name, desc) elif findEq > 0: has_table = True name",
"if func_name == mark_func: f.write('{} [color=lightblue];\\n'.format(func_name)) elif func.private: f.write('{} [color=lightgrey];\\n'.format(func_name)) for callee_name in",
"= code_map.funcs[f_name] if func_name in f.calls: return True if f_name in func.calls: return",
"f.write('* {} - {}\\n'.format(callee_link, callee.brief)) f.write('\\n') f.write('## Functions that call {}\\n\\n'.format(func_name)) filt =",
"'w') as f: graph_func_index(f, code_map) os.system('dot -Tpng -O {}'.format(filename)) # Module pages for",
"or are callers/callees of func def func_touches_func(kv): test_name = kv[0] test = kv[1]",
"page_func_index(f, code_map): f.write('# Function Index\\n\\n') f.write('\\n\\n'.format(func_index_graph_name())) for mod_name, mod in code_map.mods_sorted(): mod_link",
"caller.brief)) f.write('\\n') # ------------------------------------------------------------------------------ # Top-level documentation builder def build_dox(code_map, output_dir): f =",
"def func_index_graph_name(): return 'func_index_graph.dot' def mod_index_name(): return 'Module-Index.md' def mod_index_graph_name(): return 'mod_index_graph.dot' def",
"= os.path.join(output_dir, mod_index_name()) with open(filename, 'w') as f: page_mod_index(f, code_map) filename = os.path.join(output_dir,",
"for callee_name, callee in code_map.mods_sorted(filt): callee_link = link(callee_name, mod_page_name(callee_name)) f.write('* {} - {}\\n'.format(callee_link,",
"def main(): code_map = codemap.CodeMap() builder = codemap.MapBuilder(code_map) for token in scanner.scan_project('./src'): builder.absorb_token(token)",
"else: f.write('\\t\\tcolor = grey;\\n') f.write('\\t\\tlabel = \"Module {}\";\\n'.format(mod_name)) for func_name in mod.functions: func",
"line.find('=') if findPtr > 0: has_table = True name = line[:findPtr].lstrip().rstrip() desc =",
"os.system('dot -Tpng -O {}'.format(filename)) # Function pages def ispub(kv): return not kv[1].private for",
"filenames def func_index_name(): return 'Function-Index.md' def func_index_graph_name(): return 'func_index_graph.dot' def mod_index_name(): return 'Module-Index.md'",
"builders def graph_mod_index(f, code_map): f.write('digraph Callgraph {\\n') for mod_name, mod in code_map.mods_sorted(): for",
"= os.path.join(output_dir, mod_page_name(mod_name)) with open(filename, 'w') as f: page_module(f, code_map, mod_name, mod) filename",
"with open(filename, 'w') as f: graph_module(f, code_map, mod_name, mod) os.system('dot -Tpng -O {}'.format(filename))",
"------------------------------------------------------------------------------ def test(): pass def main(): code_map = codemap.CodeMap() builder = codemap.MapBuilder(code_map) for",
"func.calls: return True return False # Filter for functions that are or are",
"with open(filename, 'w') as f: page_module(f, code_map, mod_name, mod) filename = os.path.join(output_dir, mod_graph_name(mod_name))",
"filt = codemap.iscalledby(mod) for callee_name, callee in code_map.mods_sorted(filt): callee_link = link(callee_name, mod_page_name(callee_name)) f.write('*",
"by, or call a module def func_touches_mod(kv): test_name = kv[0] test = kv[1]",
"# Parameterized output filenames def func_index_name(): return 'Function-Index.md' def func_index_graph_name(): return 'func_index_graph.dot' def",
"!= '': has_lines = True lines += '* {}\\n'.format(line) if (not has_table) and",
"os.path.join('funcs', '{}.dot'.format(func_name)) def mod_page_name(mod_name): return os.path.join('mods', '{}.md'.format(mod_name)) def mod_graph_name(mod_name): return os.path.join('mods', '{}.dot'.format(mod_name)) #",
"filt = lambda f : inmod(f) and ispub(f) for func_name, func in code_map.funcs_sorted(filt):",
"code_map, mod_name, mod): f.write('# Module {}\\n\\n'.format(mod_name)) f.write('{}\\n\\n'.format(mod.brief)) f.write('## Detail:\\n\\n') f.write('{}\\n\\n'.format(mod.detail)) f.write('## Callgraph:\\n\\n') f.write('\\n\\n'.format(mod_graph_name(mod_name)))",
"f.write('## Pass:\\n\\n') table_list(f, func.inputs) f.write('## Return:\\n\\n') table_list(f, func.outputs) f.write('## Side Effects:\\n\\n') table_list(f, func.sideeffects)",
"callee.private: f.write('* {} - {}\\n'.format(callee_name, callee.brief)) else: callee_link = link(callee_name, func_page_name(callee_name)) f.write('* {}",
"pages def ispub(kv): return not kv[1].private for func_name, func in code_map.funcs_sorted(ispub): filename =",
"line != '': has_lines = True lines += '* {}\\n'.format(line) if (not has_table)",
"caller.brief)) f.write('\\n') def graph_function(f, code_map, func_name, func): # Filter for modules that contain",
"Output file builders def graph_mod_index(f, code_map): f.write('digraph Callgraph {\\n') for mod_name, mod in",
"with open(filename, 'w') as f: graph_func_index(f, code_map) os.system('dot -Tpng -O {}'.format(filename)) # Module",
"file builders def graph_mod_index(f, code_map): f.write('digraph Callgraph {\\n') for mod_name, mod in code_map.mods_sorted():",
"filename = os.path.join(output_dir, mod_graph_name(mod_name)) with open(filename, 'w') as f: graph_module(f, code_map, mod_name, mod)",
"- {}\\n'.format(callee_link, callee.brief)) f.write('\\n') f.write('## Functions that call {}\\n\\n'.format(func_name)) filt = codemap.calls(func_name) for",
"func) filename = os.path.join(output_dir, func_graph_name(func_name)) with open(filename, 'w') as f: graph_function(f, code_map, func_name,",
"mod_page_name(caller_name)) f.write('* {} - {}\\n'.format(caller_name, caller.brief)) f.write('\\n') def graph_function(f, code_map, func_name, func): #",
"func_name in mod.functions: func = code_map.funcs[func_name] if func_name in test.calls: return True if",
"elif line != '': has_lines = True lines += '* {}\\n'.format(line) if (not",
"codemap.iscalledby(func) for callee_name, callee in code_map.funcs_sorted(filt): if callee.private: f.write('* {} - {}\\n'.format(callee_name, callee.brief))",
"== mark_func: f.write('{} [color=lightblue];\\n'.format(func_name)) elif func.private: f.write('{} [color=lightgrey];\\n'.format(func_name)) for callee_name in func.calls: callee",
"# ------------------------------------------------------------------------------ # Parameterized output filenames def func_index_name(): return 'Function-Index.md' def func_index_graph_name(): return",
"code_map.funcs_sorted(filt): if callee.private: f.write('* {} - {}\\n'.format(callee_name, callee.brief)) else: callee_link = link(callee_name, func_page_name(callee_name))",
"in func.calls: callee = code_map.funcs[callee_name] if not func_filter((callee_name, callee)): continue f.write('\\t{} -> {};\\n'.format(func_name,",
"func_link = link(func_name, func_page_name(func_name)) f.write('* {} - {}\\n'.format(func_link, func.brief)) f.write('\\n') f.write('## Modules called",
"caller_link = link(caller_name, mod_page_name(caller_name)) f.write('* {} - {}\\n'.format(caller_name, caller.brief)) f.write('\\n') def graph_function(f, code_map,",
"code_map, func_name, func) os.system('dot -Tpng -O {}'.format(filename)) # ------------------------------------------------------------------------------ def test(): pass def",
"func_page_name(func_name)) f.write(' * {} - {}\\n'.format(func_link, func.brief)) def graph_module(f, code_map, mod_name, mod): #",
"def link(text, filename): return '[{}]({})'.format(text, text) def table_list(f, line_list): has_table = False has_lines",
"'|:---|:---:|:---|\\n' lines = '' for line in line_list: findPtr = line.find('->') findEq =",
"codemap # ------------------------------------------------------------------------------ # Parameterized output filenames def func_index_name(): return 'Function-Index.md' def func_index_graph_name():",
"link(caller_name, mod_page_name(caller_name)) f.write('* {} - {}\\n'.format(caller_name, caller.brief)) f.write('\\n') def graph_function(f, code_map, func_name, func):",
"{}:\\n'.format(mod_link, mod.brief)) inmod = codemap.inmodule(mod_name) ispub = codemap.ispublic() filt = lambda f :",
"code_map, mod_name, mod): # Filter for functions that are in, are called by,",
"index page filename = os.path.join(output_dir, func_index_name()) with open(filename, 'w') as f: page_func_index(f, code_map)",
"= kv[0] test = kv[1] if test_name == mod_name: return True if test_name",
"as f: graph_mod_index(f, code_map) os.system('dot -Tpng -O {}'.format(filename)) # Function index page filename",
"'func_index_graph.dot' def mod_index_name(): return 'Module-Index.md' def mod_index_graph_name(): return 'mod_index_graph.dot' def func_page_name(func_name): return os.path.join('funcs',",
"= False has_lines = False table = '|location||description|\\n' table += '|:---|:---:|:---|\\n' lines =",
"func)): f.write('\\t\\t{};\\n'.format(func_name)) f.write('\\t}\\n') for func_name, func in code_map.funcs_sorted(func_filter): if func_name == mark_func: f.write('{}",
"True if f_name in func.calls: return True return False # Filter for functions",
"func_name)) f.write('{}\\n\\n'.format(func.brief)) f.write('## Detail:\\n\\n') f.write('{}\\n\\n'.format(func.detail)) f.write('## Pass:\\n\\n') table_list(f, func.inputs) f.write('## Return:\\n\\n') table_list(f, func.outputs)",
"mod_name, mod) os.system('dot -Tpng -O {}'.format(filename)) # Function pages def ispub(kv): return not",
"code_map, mod_touches_mod, func_touches_mod, mark_mod=mod_name) def page_module(f, code_map, mod_name, mod): f.write('# Module {}\\n\\n'.format(mod_name)) f.write('{}\\n\\n'.format(mod.brief))",
"os.path.join(output_dir, func_graph_name(func_name)) with open(filename, 'w') as f: graph_function(f, code_map, func_name, func) os.system('dot -Tpng",
"def mod_touches_mod(kv): test_name = kv[0] test = kv[1] if test_name == mod_name: return",
"builder = codemap.MapBuilder(code_map) for token in scanner.scan_project('./src'): builder.absorb_token(token) build_dox(code_map, './doc/vos64.wiki') if __name__ ==",
"code_map.mods_sorted(): for callee_name in mod.calls: f.write('\\t{} -> {};\\n'.format(mod_name, callee_name)) f.write('}\\n') def page_mod_index(f, code_map):",
"#!/usr/bin/env python3 import os import sys import scanner import codemap # ------------------------------------------------------------------------------ #",
"page_function(f, code_map, func_name, func) filename = os.path.join(output_dir, func_graph_name(func_name)) with open(filename, 'w') as f:",
"def all_mods(kv): return True def public_funcs(kv): return not kv[1].private callgraph(f, code_map, all_mods, public_funcs)",
"def graph_module(f, code_map, mod_name, mod): # Filter for functions that are in, are",
"not kv[1].private for func_name, func in code_map.funcs_sorted(ispub): filename = os.path.join(output_dir, func_page_name(func_name)) with open(filename,",
"func def mod_touches_func(kv): test_name = kv[0] test = kv[1] if test_name == func.module:",
"f_name in test.functions: f = code_map.funcs[f_name] if func_name in f.calls: return True if",
"grey;\\n') f.write('\\t\\tlabel = \"Module {}\";\\n'.format(mod_name)) for func_name in mod.functions: func = code_map.funcs[func_name] if",
"func_name, func in code_map.funcs_sorted(filt): func_link = link(func_name, func_page_name(func_name)) f.write('* {} - {}\\n'.format(func_link, func.brief))",
"link(callee_name, mod_page_name(callee_name)) f.write('* {} - {}\\n'.format(callee_link, callee.brief)) f.write('\\n') f.write('## Modules that call {}\\n\\n'.format(mod_name))",
"os.path.join(output_dir, func_index_graph_name()) with open(filename, 'w') as f: graph_func_index(f, code_map) os.system('dot -Tpng -O {}'.format(filename))",
"-Tpng -O {}'.format(filename)) # Function pages def ispub(kv): return not kv[1].private for func_name,",
"callee_name)) f.write('}\\n') # ------------------------------------------------------------------------------ # Output file builders def graph_mod_index(f, code_map): f.write('digraph Callgraph",
"{} - {}\\n'.format(caller_name, caller.brief)) else: caller_link = link(caller_name, func_page_name(caller_name)) f.write('* {} - {}\\n'.format(caller_link,",
"caller in code_map.funcs_sorted(filt): if caller.private: f.write('* {} - {}\\n'.format(caller_name, caller.brief)) else: caller_link =",
"as f: graph_module(f, code_map, mod_name, mod) os.system('dot -Tpng -O {}'.format(filename)) # Function pages",
"f: graph_function(f, code_map, func_name, func) os.system('dot -Tpng -O {}'.format(filename)) # ------------------------------------------------------------------------------ def test():",
"all_mods(kv): return True def public_funcs(kv): return not kv[1].private callgraph(f, code_map, all_mods, public_funcs) def",
"f.write('## Modules called by {}\\n\\n'.format(mod_name)) filt = codemap.iscalledby(mod) for callee_name, callee in code_map.mods_sorted(filt):",
"True for f_name in test.functions: f = code_map.funcs[f_name] if func_name in f.calls: return",
"caller.brief)) else: caller_link = link(caller_name, func_page_name(caller_name)) f.write('* {} - {}\\n'.format(caller_link, caller.brief)) f.write('\\n') #",
"test_name == mod_name: return True if test_name in mod.calls: return True if mod_name",
"code_map, func_name, func): mod_link = link(func.module, mod_page_name(func.module)) f.write('# Function {}.{}\\n\\n'.format(mod_link, func_name)) f.write('{}\\n\\n'.format(func.brief)) f.write('##",
"func_name in mod.functions: func = code_map.funcs[func_name] if func_filter((func_name, func)): f.write('\\t\\t{};\\n'.format(func_name)) f.write('\\t}\\n') for func_name,",
"sys.stdout # Module index page filename = os.path.join(output_dir, mod_index_name()) with open(filename, 'w') as",
"False table = '|location||description|\\n' table += '|:---|:---:|:---|\\n' lines = '' for line in",
"False callgraph(f, code_map, mod_touches_mod, func_touches_mod, mark_mod=mod_name) def page_module(f, code_map, mod_name, mod): f.write('# Module",
"for modules that contain or contain callers/callees of func def mod_touches_func(kv): test_name =",
"os.path.join(output_dir, mod_index_graph_name()) with open(filename, 'w') as f: graph_mod_index(f, code_map) os.system('dot -Tpng -O {}'.format(filename))",
"test_name in func.calls: return True if func_name in test.calls: return True return False",
"has_lines): f.write('None\\n\\n') elif has_table: f.write('{}\\n'.format(table)) elif has_lines: f.write('{}\\n'.format(lines)) def callgraph(f, code_map, mod_filter, func_filter,",
"{} - {}\\n'.format(caller_name, caller.brief)) f.write('\\n') def graph_function(f, code_map, func_name, func): # Filter for",
"'': has_lines = True lines += '* {}\\n'.format(line) if (not has_table) and (not",
"f = code_map.funcs[f_name] if func_name in f.calls: return True if f_name in func.calls:",
"test_name in mod.functions: return True for func_name in mod.functions: func = code_map.funcs[func_name] if",
"= code_map.funcs[func_name] if func_filter((func_name, func)): f.write('\\t\\t{};\\n'.format(func_name)) f.write('\\t}\\n') for func_name, func in code_map.funcs_sorted(func_filter): if",
"link(func_name, func_page_name(func_name)) f.write('* {} - {}\\n'.format(func_link, func.brief)) f.write('\\n') f.write('## Modules called by {}\\n\\n'.format(mod_name))",
"open(filename, 'w') as f: graph_func_index(f, code_map) os.system('dot -Tpng -O {}'.format(filename)) # Module pages",
"return 'mod_index_graph.dot' def func_page_name(func_name): return os.path.join('funcs', '{}.md'.format(func_name)) def func_graph_name(func_name): return os.path.join('funcs', '{}.dot'.format(func_name)) def",
"has_table = True name = line[:findEq].lstrip().rstrip() desc = line[findEq + 2:].lstrip().rstrip() table +=",
"return os.path.join('funcs', '{}.dot'.format(func_name)) def mod_page_name(mod_name): return os.path.join('mods', '{}.md'.format(mod_name)) def mod_graph_name(mod_name): return os.path.join('mods', '{}.dot'.format(mod_name))",
"in mod.functions: func = code_map.funcs[func_name] if func_filter((func_name, func)): f.write('\\t\\t{};\\n'.format(func_name)) f.write('\\t}\\n') for func_name, func",
"for caller_name, caller in code_map.funcs_sorted(filt): if caller.private: f.write('* {} - {}\\n'.format(caller_name, caller.brief)) else:",
"= code_map.funcs[callee_name] if not func_filter((callee_name, callee)): continue f.write('\\t{} -> {};\\n'.format(func_name, callee_name)) f.write('}\\n') #",
"func_name in test.calls: return True return False callgraph(f, code_map, mod_touches_func, func_touches_func, mark_func=func_name) def",
"Functions that call {}\\n\\n'.format(func_name)) filt = codemap.calls(func_name) for caller_name, caller in code_map.funcs_sorted(filt): if",
"f.write('{}\\n\\n'.format(mod.brief)) f.write('## Detail:\\n\\n') f.write('{}\\n\\n'.format(mod.detail)) f.write('## Callgraph:\\n\\n') f.write('\\n\\n'.format(mod_graph_name(mod_name))) f.write('## Public Functions:\\n\\n') inmod = codemap.inmodule(mod_name)",
"'{}.dot'.format(func_name)) def mod_page_name(mod_name): return os.path.join('mods', '{}.md'.format(mod_name)) def mod_graph_name(mod_name): return os.path.join('mods', '{}.dot'.format(mod_name)) # ------------------------------------------------------------------------------",
"f.write('\\n\\n'.format(func_graph_name(func_name))) f.write('## Functions called by {}\\n\\n'.format(func_name)) filt = codemap.iscalledby(func) for callee_name, callee in",
"f: graph_func_index(f, code_map) os.system('dot -Tpng -O {}'.format(filename)) # Module pages for mod_name, mod",
"Index\\n\\n') f.write('\\n\\n'.format(mod_index_graph_name())) for mod_name, mod in code_map.mods_sorted(): mod_link = link(mod_name, mod_page_name(mod_name)) f.write('*",
"test.functions: f = code_map.funcs[f_name] if func_name in f.calls: return True if f_name in",
"func_page_name(func_name): return os.path.join('funcs', '{}.md'.format(func_name)) def func_graph_name(func_name): return os.path.join('funcs', '{}.dot'.format(func_name)) def mod_page_name(mod_name): return os.path.join('mods',",
"caller_name, caller in code_map.funcs_sorted(filt): if caller.private: f.write('* {} - {}\\n'.format(caller_name, caller.brief)) else: caller_link",
"code_map) filename = os.path.join(output_dir, mod_index_graph_name()) with open(filename, 'w') as f: graph_mod_index(f, code_map) os.system('dot",
"= codemap.calls(mod_name) for caller_name, caller in code_map.mods_sorted(filt): caller_link = link(caller_name, mod_page_name(caller_name)) f.write('* {}",
"mod_name == mark_mod: f.write('\\t\\tcolor = lightblue;\\n') else: f.write('\\t\\tcolor = grey;\\n') f.write('\\t\\tlabel = \"Module",
"callgraph(f, code_map, mod_touches_func, func_touches_func, mark_func=func_name) def page_function(f, code_map, func_name, func): mod_link = link(func.module,",
"return True if mod_name in code_map.mods[test_name].calls: return True return False callgraph(f, code_map, mod_touches_mod,",
"callee_name in func.calls: callee = code_map.funcs[callee_name] if not func_filter((callee_name, callee)): continue f.write('\\t{} ->",
"def public_funcs(kv): return not kv[1].private callgraph(f, code_map, all_mods, public_funcs) def page_func_index(f, code_map): f.write('#",
"# Filter for functions that are in, are called by, or call a",
"line in line_list: findPtr = line.find('->') findEq = line.find('=') if findPtr > 0:",
"# ------------------------------------------------------------------------------ def test(): pass def main(): code_map = codemap.CodeMap() builder = codemap.MapBuilder(code_map)",
"# Function pages def ispub(kv): return not kv[1].private for func_name, func in code_map.funcs_sorted(ispub):",
"or call a module def mod_touches_mod(kv): test_name = kv[0] test = kv[1] if",
"def page_mod_index(f, code_map): f.write('# Module Index\\n\\n') f.write('\\n\\n'.format(mod_index_graph_name())) for mod_name, mod in code_map.mods_sorted():",
"kv[1] if test_name == mod_name: return True if test_name in mod.calls: return True",
"are, are called by, or call a module def mod_touches_mod(kv): test_name = kv[0]",
"mod_touches_mod, func_touches_mod, mark_mod=mod_name) def page_module(f, code_map, mod_name, mod): f.write('# Module {}\\n\\n'.format(mod_name)) f.write('{}\\n\\n'.format(mod.brief)) f.write('##",
"has_table) and (not has_lines): f.write('None\\n\\n') elif has_table: f.write('{}\\n'.format(table)) elif has_lines: f.write('{}\\n'.format(lines)) def callgraph(f,",
"Function pages def ispub(kv): return not kv[1].private for func_name, func in code_map.funcs_sorted(ispub): filename",
"= os.path.join(output_dir, func_page_name(func_name)) with open(filename, 'w') as f: page_function(f, code_map, func_name, func) filename",
"in mod.calls: f.write('\\t{} -> {};\\n'.format(mod_name, callee_name)) f.write('}\\n') def page_mod_index(f, code_map): f.write('# Module Index\\n\\n')",
"= code_map.funcs[func_name] if func_name in test.calls: return True if test_name in func.calls: return",
"test.calls: return True if test_name in func.calls: return True return False # Filter",
"f.write('{}\\n'.format(lines)) def callgraph(f, code_map, mod_filter, func_filter, mark_mod=None, mark_func=None): f.write('digraph Callgraph {\\n') for mod_name,",
"f.write('* {} - {}\\n'.format(caller_name, caller.brief)) else: caller_link = link(caller_name, func_page_name(caller_name)) f.write('* {} -",
"= codemap.CodeMap() builder = codemap.MapBuilder(code_map) for token in scanner.scan_project('./src'): builder.absorb_token(token) build_dox(code_map, './doc/vos64.wiki') if",
"'[{}]({})'.format(text, text) def table_list(f, line_list): has_table = False has_lines = False table =",
"page_mod_index(f, code_map): f.write('# Module Index\\n\\n') f.write('\\n\\n'.format(mod_index_graph_name())) for mod_name, mod in code_map.mods_sorted(): mod_link",
"func_index_graph_name(): return 'func_index_graph.dot' def mod_index_name(): return 'Module-Index.md' def mod_index_graph_name(): return 'mod_index_graph.dot' def func_page_name(func_name):",
"func_touches_mod(kv): test_name = kv[0] test = kv[1] if test_name in mod.functions: return True",
"by {}\\n\\n'.format(mod_name)) filt = codemap.iscalledby(mod) for callee_name, callee in code_map.mods_sorted(filt): callee_link = link(callee_name,",
"= '' for line in line_list: findPtr = line.find('->') findEq = line.find('=') if",
"in func.calls: return True return False # Filter for functions that are or",
"code_map): f.write('digraph Callgraph {\\n') for mod_name, mod in code_map.mods_sorted(): for callee_name in mod.calls:",
"by, or call a module def mod_touches_mod(kv): test_name = kv[0] test = kv[1]",
"= link(func_name, func_page_name(func_name)) f.write(' * {} - {}\\n'.format(func_link, func.brief)) def graph_module(f, code_map, mod_name,",
"func_name, func in code_map.funcs_sorted(ispub): filename = os.path.join(output_dir, func_page_name(func_name)) with open(filename, 'w') as f:",
"if f_name in func.calls: return True return False # Filter for functions that",
"for mod_name, mod in code_map.mods_sorted(): mod_link = link(mod_name, mod_page_name(mod_name)) f.write('* Module {} -",
"if func_filter((func_name, func)): f.write('\\t\\t{};\\n'.format(func_name)) f.write('\\t}\\n') for func_name, func in code_map.funcs_sorted(func_filter): if func_name ==",
"f.write('\\t}\\n') for func_name, func in code_map.funcs_sorted(func_filter): if func_name == mark_func: f.write('{} [color=lightblue];\\n'.format(func_name)) elif",
"for functions that are or are callers/callees of func def func_touches_func(kv): test_name =",
"Module Index\\n\\n') f.write('\\n\\n'.format(mod_index_graph_name())) for mod_name, mod in code_map.mods_sorted(): mod_link = link(mod_name, mod_page_name(mod_name))",
"mod_page_name(mod_name)) with open(filename, 'w') as f: page_module(f, code_map, mod_name, mod) filename = os.path.join(output_dir,",
"code_map.funcs_sorted(func_filter): if func_name == mark_func: f.write('{} [color=lightblue];\\n'.format(func_name)) elif func.private: f.write('{} [color=lightgrey];\\n'.format(func_name)) for callee_name",
"mod_name, mod): f.write('# Module {}\\n\\n'.format(mod_name)) f.write('{}\\n\\n'.format(mod.brief)) f.write('## Detail:\\n\\n') f.write('{}\\n\\n'.format(mod.detail)) f.write('## Callgraph:\\n\\n') f.write('\\n\\n'.format(mod_graph_name(mod_name))) f.write('##",
"{}\\n'.format(caller_link, caller.brief)) f.write('\\n') # ------------------------------------------------------------------------------ # Top-level documentation builder def build_dox(code_map, output_dir): f",
"are callers/callees of func def func_touches_func(kv): test_name = kv[0] test = kv[1] if",
"code_map) os.system('dot -Tpng -O {}'.format(filename)) # Function index page filename = os.path.join(output_dir, func_index_name())",
"link(callee_name, func_page_name(callee_name)) f.write('* {} - {}\\n'.format(callee_link, callee.brief)) f.write('\\n') f.write('## Functions that call {}\\n\\n'.format(func_name))",
"= kv[0] test = kv[1] if test_name == func_name: return True if test_name",
"or contain callers/callees of func def mod_touches_func(kv): test_name = kv[0] test = kv[1]",
"# Filter for modules that are, are called by, or call a module",
"mod_name, mod) filename = os.path.join(output_dir, mod_graph_name(mod_name)) with open(filename, 'w') as f: graph_module(f, code_map,",
"func_name == mark_func: f.write('{} [color=lightblue];\\n'.format(func_name)) elif func.private: f.write('{} [color=lightgrey];\\n'.format(func_name)) for callee_name in func.calls:",
"callgraph(f, code_map, mod_touches_mod, func_touches_mod, mark_mod=mod_name) def page_module(f, code_map, mod_name, mod): f.write('# Module {}\\n\\n'.format(mod_name))",
"f.write('\\n') def graph_function(f, code_map, func_name, func): # Filter for modules that contain or",
"def page_module(f, code_map, mod_name, mod): f.write('# Module {}\\n\\n'.format(mod_name)) f.write('{}\\n\\n'.format(mod.brief)) f.write('## Detail:\\n\\n') f.write('{}\\n\\n'.format(mod.detail)) f.write('##",
"code_map.funcs[f_name] if func_name in f.calls: return True if f_name in func.calls: return True",
"mod_filter, func_filter, mark_mod=None, mark_func=None): f.write('digraph Callgraph {\\n') for mod_name, mod in code_map.mods_sorted(mod_filter): f.write('\\tsubgraph",
"func_graph_name(func_name)) with open(filename, 'w') as f: graph_function(f, code_map, func_name, func) os.system('dot -Tpng -O",
"{} - {}\\n'.format(func_link, func.brief)) def graph_module(f, code_map, mod_name, mod): # Filter for functions",
"Filter for modules that are, are called by, or call a module def",
"def func_touches_func(kv): test_name = kv[0] test = kv[1] if test_name == func_name: return",
"f.write('* {} - {}\\n'.format(mod_link, mod.brief)) def graph_func_index(f, code_map): def all_mods(kv): return True def",
"{}\";\\n'.format(mod_name)) for func_name in mod.functions: func = code_map.funcs[func_name] if func_filter((func_name, func)): f.write('\\t\\t{};\\n'.format(func_name)) f.write('\\t}\\n')",
"not func_filter((callee_name, callee)): continue f.write('\\t{} -> {};\\n'.format(func_name, callee_name)) f.write('}\\n') # ------------------------------------------------------------------------------ # Output",
"= link(callee_name, func_page_name(callee_name)) f.write('* {} - {}\\n'.format(callee_link, callee.brief)) f.write('\\n') f.write('## Functions that call",
"mod_index_graph_name()) with open(filename, 'w') as f: graph_mod_index(f, code_map) os.system('dot -Tpng -O {}'.format(filename)) #",
"graph_module(f, code_map, mod_name, mod): # Filter for functions that are in, are called",
"of func def mod_touches_func(kv): test_name = kv[0] test = kv[1] if test_name ==",
"func.outputs) f.write('## Side Effects:\\n\\n') table_list(f, func.sideeffects) f.write('## Callgraph:\\n\\n') f.write('\\n\\n'.format(func_graph_name(func_name))) f.write('## Functions called by",
"are or are callers/callees of func def func_touches_func(kv): test_name = kv[0] test =",
"code_map.funcs_sorted(filt): func_link = link(func_name, func_page_name(func_name)) f.write(' * {} - {}\\n'.format(func_link, func.brief)) def graph_module(f,",
"graph_mod_index(f, code_map) os.system('dot -Tpng -O {}'.format(filename)) # Function index page filename = os.path.join(output_dir,",
"if findPtr > 0: has_table = True name = line[:findPtr].lstrip().rstrip() desc = line[findPtr",
"func_page_name(callee_name)) f.write('* {} - {}\\n'.format(callee_link, callee.brief)) f.write('\\n') f.write('## Functions that call {}\\n\\n'.format(func_name)) filt",
"{} - {}:\\n'.format(mod_link, mod.brief)) inmod = codemap.inmodule(mod_name) ispub = codemap.ispublic() filt = lambda",
"= link(mod_name, mod_page_name(mod_name)) f.write('* {} - {}\\n'.format(mod_link, mod.brief)) def graph_func_index(f, code_map): def all_mods(kv):",
"Module {}\\n\\n'.format(mod_name)) f.write('{}\\n\\n'.format(mod.brief)) f.write('## Detail:\\n\\n') f.write('{}\\n\\n'.format(mod.detail)) f.write('## Callgraph:\\n\\n') f.write('\\n\\n'.format(mod_graph_name(mod_name))) f.write('## Public Functions:\\n\\n') inmod",
"f.write('## Detail:\\n\\n') f.write('{}\\n\\n'.format(func.detail)) f.write('## Pass:\\n\\n') table_list(f, func.inputs) f.write('## Return:\\n\\n') table_list(f, func.outputs) f.write('## Side",
"builder functions def link(text, filename): return '[{}]({})'.format(text, text) def table_list(f, line_list): has_table =",
"def func_touches_mod(kv): test_name = kv[0] test = kv[1] if test_name in mod.functions: return",
"f.write('{}\\n\\n'.format(func.brief)) f.write('## Detail:\\n\\n') f.write('{}\\n\\n'.format(func.detail)) f.write('## Pass:\\n\\n') table_list(f, func.inputs) f.write('## Return:\\n\\n') table_list(f, func.outputs) f.write('##",
"Return:\\n\\n') table_list(f, func.outputs) f.write('## Side Effects:\\n\\n') table_list(f, func.sideeffects) f.write('## Callgraph:\\n\\n') f.write('\\n\\n'.format(func_graph_name(func_name))) f.write('## Functions",
"documentation builder def build_dox(code_map, output_dir): f = sys.stdout # Module index page filename",
"mod.brief)) inmod = codemap.inmodule(mod_name) ispub = codemap.ispublic() filt = lambda f : inmod(f)",
"kv[1] if test_name == func_name: return True if test_name in func.calls: return True",
"as f: graph_func_index(f, code_map) os.system('dot -Tpng -O {}'.format(filename)) # Module pages for mod_name,",
"if (not has_table) and (not has_lines): f.write('None\\n\\n') elif has_table: f.write('{}\\n'.format(table)) elif has_lines: f.write('{}\\n'.format(lines))",
"codemap.calls(mod_name) for caller_name, caller in code_map.mods_sorted(filt): caller_link = link(caller_name, mod_page_name(caller_name)) f.write('* {} -",
"import codemap # ------------------------------------------------------------------------------ # Parameterized output filenames def func_index_name(): return 'Function-Index.md' def",
"callee in code_map.funcs_sorted(filt): if callee.private: f.write('* {} - {}\\n'.format(callee_name, callee.brief)) else: callee_link =",
"if test_name in mod.calls: return True if mod_name in code_map.mods[test_name].calls: return True return",
"callee = code_map.funcs[callee_name] if not func_filter((callee_name, callee)): continue f.write('\\t{} -> {};\\n'.format(func_name, callee_name)) f.write('}\\n')",
"f: page_module(f, code_map, mod_name, mod) filename = os.path.join(output_dir, mod_graph_name(mod_name)) with open(filename, 'w') as",
"func_graph_name(func_name): return os.path.join('funcs', '{}.dot'.format(func_name)) def mod_page_name(mod_name): return os.path.join('mods', '{}.md'.format(mod_name)) def mod_graph_name(mod_name): return os.path.join('mods',",
"{}.{}\\n\\n'.format(mod_link, func_name)) f.write('{}\\n\\n'.format(func.brief)) f.write('## Detail:\\n\\n') f.write('{}\\n\\n'.format(func.detail)) f.write('## Pass:\\n\\n') table_list(f, func.inputs) f.write('## Return:\\n\\n') table_list(f,",
"mod_touches_func, func_touches_func, mark_func=func_name) def page_function(f, code_map, func_name, func): mod_link = link(func.module, mod_page_name(func.module)) f.write('#",
"link(mod_name, mod_page_name(mod_name)) f.write('* Module {} - {}:\\n'.format(mod_link, mod.brief)) inmod = codemap.inmodule(mod_name) ispub =",
"= link(callee_name, mod_page_name(callee_name)) f.write('* {} - {}\\n'.format(callee_link, callee.brief)) f.write('\\n') f.write('## Modules that call",
"test = kv[1] if test_name == mod_name: return True if test_name in mod.calls:",
"Top-level documentation builder def build_dox(code_map, output_dir): f = sys.stdout # Module index page",
"os.system('dot -Tpng -O {}'.format(filename)) # Module pages for mod_name, mod in code_map.mods_sorted(): filename",
"has_lines = True lines += '* {}\\n'.format(line) if (not has_table) and (not has_lines):",
"test = kv[1] if test_name == func.module: return True for f_name in test.functions:",
"has_table = False has_lines = False table = '|location||description|\\n' table += '|:---|:---:|:---|\\n' lines",
"name = line[:findPtr].lstrip().rstrip() desc = line[findPtr + 2:].lstrip().rstrip() table += '|`{}`|->|{}|\\n'.format(name, desc) elif",
"func_index_graph_name()) with open(filename, 'w') as f: graph_func_index(f, code_map) os.system('dot -Tpng -O {}'.format(filename)) #",
"return 'Function-Index.md' def func_index_graph_name(): return 'func_index_graph.dot' def mod_index_name(): return 'Module-Index.md' def mod_index_graph_name(): return",
"and (not has_lines): f.write('None\\n\\n') elif has_table: f.write('{}\\n'.format(table)) elif has_lines: f.write('{}\\n'.format(lines)) def callgraph(f, code_map,",
"Function index page filename = os.path.join(output_dir, func_index_name()) with open(filename, 'w') as f: page_func_index(f,",
"link(mod_name, mod_page_name(mod_name)) f.write('* {} - {}\\n'.format(mod_link, mod.brief)) def graph_func_index(f, code_map): def all_mods(kv): return",
"------------------------------------------------------------------------------ # Top-level documentation builder def build_dox(code_map, output_dir): f = sys.stdout # Module",
"if test_name == mod_name: return True if test_name in mod.calls: return True if",
"graph_func_index(f, code_map) os.system('dot -Tpng -O {}'.format(filename)) # Module pages for mod_name, mod in",
"code_map) filename = os.path.join(output_dir, func_index_graph_name()) with open(filename, 'w') as f: graph_func_index(f, code_map) os.system('dot",
"f.write('# Module {}\\n\\n'.format(mod_name)) f.write('{}\\n\\n'.format(mod.brief)) f.write('## Detail:\\n\\n') f.write('{}\\n\\n'.format(mod.detail)) f.write('## Callgraph:\\n\\n') f.write('\\n\\n'.format(mod_graph_name(mod_name))) f.write('## Public Functions:\\n\\n')",
"func = code_map.funcs[func_name] if func_name in test.calls: return True if test_name in func.calls:",
"call a module def mod_touches_mod(kv): test_name = kv[0] test = kv[1] if test_name",
"with open(filename, 'w') as f: page_function(f, code_map, func_name, func) filename = os.path.join(output_dir, func_graph_name(func_name))",
"-Tpng -O {}'.format(filename)) # ------------------------------------------------------------------------------ def test(): pass def main(): code_map = codemap.CodeMap()",
"functions def link(text, filename): return '[{}]({})'.format(text, text) def table_list(f, line_list): has_table = False",
"call a module def func_touches_mod(kv): test_name = kv[0] test = kv[1] if test_name",
"if test_name in func.calls: return True return False # Filter for modules that",
"- {}\\n'.format(func_link, func.brief)) f.write('\\n') f.write('## Modules called by {}\\n\\n'.format(mod_name)) filt = codemap.iscalledby(mod) for",
"table_list(f, func.inputs) f.write('## Return:\\n\\n') table_list(f, func.outputs) f.write('## Side Effects:\\n\\n') table_list(f, func.sideeffects) f.write('## Callgraph:\\n\\n')",
"called by {}\\n\\n'.format(func_name)) filt = codemap.iscalledby(func) for callee_name, callee in code_map.funcs_sorted(filt): if callee.private:",
"'w') as f: page_func_index(f, code_map) filename = os.path.join(output_dir, func_index_graph_name()) with open(filename, 'w') as",
"{}'.format(filename)) # Module pages for mod_name, mod in code_map.mods_sorted(): filename = os.path.join(output_dir, mod_page_name(mod_name))",
"f.write('}\\n') def page_mod_index(f, code_map): f.write('# Module Index\\n\\n') f.write('\\n\\n'.format(mod_index_graph_name())) for mod_name, mod in",
"os.path.join(output_dir, mod_graph_name(mod_name)) with open(filename, 'w') as f: graph_module(f, code_map, mod_name, mod) os.system('dot -Tpng",
"f.write('\\t\\t{};\\n'.format(func_name)) f.write('\\t}\\n') for func_name, func in code_map.funcs_sorted(func_filter): if func_name == mark_func: f.write('{} [color=lightblue];\\n'.format(func_name))",
"has_lines = False table = '|location||description|\\n' table += '|:---|:---:|:---|\\n' lines = '' for",
"module def mod_touches_mod(kv): test_name = kv[0] test = kv[1] if test_name == mod_name:",
"mod): f.write('# Module {}\\n\\n'.format(mod_name)) f.write('{}\\n\\n'.format(mod.brief)) f.write('## Detail:\\n\\n') f.write('{}\\n\\n'.format(mod.detail)) f.write('## Callgraph:\\n\\n') f.write('\\n\\n'.format(mod_graph_name(mod_name))) f.write('## Public",
"mod) filename = os.path.join(output_dir, mod_graph_name(mod_name)) with open(filename, 'w') as f: graph_module(f, code_map, mod_name,",
"mod_index_graph_name(): return 'mod_index_graph.dot' def func_page_name(func_name): return os.path.join('funcs', '{}.md'.format(func_name)) def func_graph_name(func_name): return os.path.join('funcs', '{}.dot'.format(func_name))",
"+= '|:---|:---:|:---|\\n' lines = '' for line in line_list: findPtr = line.find('->') findEq",
"in code_map.funcs_sorted(filt): if callee.private: f.write('* {} - {}\\n'.format(callee_name, callee.brief)) else: callee_link = link(callee_name,",
"graph_mod_index(f, code_map): f.write('digraph Callgraph {\\n') for mod_name, mod in code_map.mods_sorted(): for callee_name in",
"{} - {}\\n'.format(callee_link, callee.brief)) f.write('\\n') f.write('## Modules that call {}\\n\\n'.format(mod_name)) filt = codemap.calls(mod_name)",
"{} - {}\\n'.format(callee_name, callee.brief)) else: callee_link = link(callee_name, func_page_name(callee_name)) f.write('* {} - {}\\n'.format(callee_link,",
"-O {}'.format(filename)) # Function pages def ispub(kv): return not kv[1].private for func_name, func",
"mark_func=func_name) def page_function(f, code_map, func_name, func): mod_link = link(func.module, mod_page_name(func.module)) f.write('# Function {}.{}\\n\\n'.format(mod_link,",
"True name = line[:findEq].lstrip().rstrip() desc = line[findEq + 2:].lstrip().rstrip() table += '|`{}`|=|{}|\\n'.format(name, desc)",
"True def public_funcs(kv): return not kv[1].private callgraph(f, code_map, all_mods, public_funcs) def page_func_index(f, code_map):",
"inmod = codemap.inmodule(mod_name) ispub = codemap.ispublic() filt = lambda f : inmod(f) and",
"in mod.functions: return True for func_name in mod.functions: func = code_map.funcs[func_name] if func_name",
"in code_map.mods_sorted(filt): callee_link = link(callee_name, mod_page_name(callee_name)) f.write('* {} - {}\\n'.format(callee_link, callee.brief)) f.write('\\n') f.write('##",
"Modules that call {}\\n\\n'.format(mod_name)) filt = codemap.calls(mod_name) for caller_name, caller in code_map.mods_sorted(filt): caller_link",
"'|`{}`|->|{}|\\n'.format(name, desc) elif findEq > 0: has_table = True name = line[:findEq].lstrip().rstrip() desc",
"as f: page_module(f, code_map, mod_name, mod) filename = os.path.join(output_dir, mod_graph_name(mod_name)) with open(filename, 'w')",
"f.write('# Module Index\\n\\n') f.write('\\n\\n'.format(mod_index_graph_name())) for mod_name, mod in code_map.mods_sorted(): mod_link = link(mod_name,",
"f.write('\\n\\n'.format(mod_graph_name(mod_name))) f.write('## Public Functions:\\n\\n') inmod = codemap.inmodule(mod_name) ispub = codemap.ispublic() filt = lambda",
"code_map.funcs_sorted(filt): func_link = link(func_name, func_page_name(func_name)) f.write('* {} - {}\\n'.format(func_link, func.brief)) f.write('\\n') f.write('## Modules",
"os.system('dot -Tpng -O {}'.format(filename)) # ------------------------------------------------------------------------------ def test(): pass def main(): code_map =",
"in code_map.funcs_sorted(ispub): filename = os.path.join(output_dir, func_page_name(func_name)) with open(filename, 'w') as f: page_function(f, code_map,",
"kv[1].private for func_name, func in code_map.funcs_sorted(ispub): filename = os.path.join(output_dir, func_page_name(func_name)) with open(filename, 'w')",
"- {}\\n'.format(caller_name, caller.brief)) f.write('\\n') def graph_function(f, code_map, func_name, func): # Filter for modules",
"Detail:\\n\\n') f.write('{}\\n\\n'.format(func.detail)) f.write('## Pass:\\n\\n') table_list(f, func.inputs) f.write('## Return:\\n\\n') table_list(f, func.outputs) f.write('## Side Effects:\\n\\n')",
"as f: page_func_index(f, code_map) filename = os.path.join(output_dir, func_index_graph_name()) with open(filename, 'w') as f:",
"= kv[1] if test_name == mod_name: return True if test_name in mod.calls: return",
"'w') as f: graph_function(f, code_map, func_name, func) os.system('dot -Tpng -O {}'.format(filename)) # ------------------------------------------------------------------------------",
"functions that are or are callers/callees of func def func_touches_func(kv): test_name = kv[0]",
"callee_link = link(callee_name, func_page_name(callee_name)) f.write('* {} - {}\\n'.format(callee_link, callee.brief)) f.write('\\n') f.write('## Functions that",
"def func_page_name(func_name): return os.path.join('funcs', '{}.md'.format(func_name)) def func_graph_name(func_name): return os.path.join('funcs', '{}.dot'.format(func_name)) def mod_page_name(mod_name): return",
"codemap.iscalledby(mod) for callee_name, callee in code_map.mods_sorted(filt): callee_link = link(callee_name, mod_page_name(callee_name)) f.write('* {} -",
"func.inputs) f.write('## Return:\\n\\n') table_list(f, func.outputs) f.write('## Side Effects:\\n\\n') table_list(f, func.sideeffects) f.write('## Callgraph:\\n\\n') f.write('\\n\\n'.format(func_graph_name(func_name)))",
"{}\\n'.format(callee_link, callee.brief)) f.write('\\n') f.write('## Functions that call {}\\n\\n'.format(func_name)) filt = codemap.calls(func_name) for caller_name,",
"findEq > 0: has_table = True name = line[:findEq].lstrip().rstrip() desc = line[findEq +",
"= kv[1] if test_name in mod.functions: return True for func_name in mod.functions: func",
"{} - {}\\n'.format(func_link, func.brief)) f.write('\\n') f.write('## Modules called by {}\\n\\n'.format(mod_name)) filt = codemap.iscalledby(mod)",
"code_map): f.write('# Function Index\\n\\n') f.write('\\n\\n'.format(func_index_graph_name())) for mod_name, mod in code_map.mods_sorted(): mod_link =",
"= \"Module {}\";\\n'.format(mod_name)) for func_name in mod.functions: func = code_map.funcs[func_name] if func_filter((func_name, func)):",
"f: graph_module(f, code_map, mod_name, mod) os.system('dot -Tpng -O {}'.format(filename)) # Function pages def",
"return not kv[1].private for func_name, func in code_map.funcs_sorted(ispub): filename = os.path.join(output_dir, func_page_name(func_name)) with",
"link(func.module, mod_page_name(func.module)) f.write('# Function {}.{}\\n\\n'.format(mod_link, func_name)) f.write('{}\\n\\n'.format(func.brief)) f.write('## Detail:\\n\\n') f.write('{}\\n\\n'.format(func.detail)) f.write('## Pass:\\n\\n') table_list(f,",
"{}'.format(filename)) # ------------------------------------------------------------------------------ def test(): pass def main(): code_map = codemap.CodeMap() builder =",
"# Function index page filename = os.path.join(output_dir, func_index_name()) with open(filename, 'w') as f:",
"not kv[1].private callgraph(f, code_map, all_mods, public_funcs) def page_func_index(f, code_map): f.write('# Function Index\\n\\n') f.write('![Full",
"return False callgraph(f, code_map, mod_touches_mod, func_touches_mod, mark_mod=mod_name) def page_module(f, code_map, mod_name, mod): f.write('#",
"f.write('* {} - {}\\n'.format(callee_name, callee.brief)) else: callee_link = link(callee_name, func_page_name(callee_name)) f.write('* {} -",
"in test.calls: return True return False callgraph(f, code_map, mod_touches_func, func_touches_func, mark_func=func_name) def page_function(f,",
"for func_name, func in code_map.funcs_sorted(func_filter): if func_name == mark_func: f.write('{} [color=lightblue];\\n'.format(func_name)) elif func.private:",
"callee.brief)) else: callee_link = link(callee_name, func_page_name(callee_name)) f.write('* {} - {}\\n'.format(callee_link, callee.brief)) f.write('\\n') f.write('##",
"'w') as f: graph_mod_index(f, code_map) os.system('dot -Tpng -O {}'.format(filename)) # Function index page",
"mod.functions: return True for func_name in mod.functions: func = code_map.funcs[func_name] if func_name in",
"func in code_map.funcs_sorted(filt): func_link = link(func_name, func_page_name(func_name)) f.write(' * {} - {}\\n'.format(func_link, func.brief))",
"table_list(f, line_list): has_table = False has_lines = False table = '|location||description|\\n' table +=",
"if test_name in func.calls: return True if func_name in test.calls: return True return",
"{}\\n'.format(caller_name, caller.brief)) else: caller_link = link(caller_name, func_page_name(caller_name)) f.write('* {} - {}\\n'.format(caller_link, caller.brief)) f.write('\\n')",
"as f: graph_function(f, code_map, func_name, func) os.system('dot -Tpng -O {}'.format(filename)) # ------------------------------------------------------------------------------ def",
"os.system('dot -Tpng -O {}'.format(filename)) # Function index page filename = os.path.join(output_dir, func_index_name()) with",
"filt = codemap.calls(mod_name) for caller_name, caller in code_map.mods_sorted(filt): caller_link = link(caller_name, mod_page_name(caller_name)) f.write('*",
"= link(caller_name, func_page_name(caller_name)) f.write('* {} - {}\\n'.format(caller_link, caller.brief)) f.write('\\n') # ------------------------------------------------------------------------------ # Top-level",
"f.write('# Function Index\\n\\n') f.write('\\n\\n'.format(func_index_graph_name())) for mod_name, mod in code_map.mods_sorted(): mod_link = link(mod_name,",
"def graph_mod_index(f, code_map): f.write('digraph Callgraph {\\n') for mod_name, mod in code_map.mods_sorted(): for callee_name",
"callgraph(f, code_map, all_mods, public_funcs) def page_func_index(f, code_map): f.write('# Function Index\\n\\n') f.write('\\n\\n'.format(func_index_graph_name())) for",
"{}\\n'.format(line) if (not has_table) and (not has_lines): f.write('None\\n\\n') elif has_table: f.write('{}\\n'.format(table)) elif has_lines:",
"= kv[1] if test_name == func.module: return True for f_name in test.functions: f",
"pass def main(): code_map = codemap.CodeMap() builder = codemap.MapBuilder(code_map) for token in scanner.scan_project('./src'):",
"test_name in mod.calls: return True if mod_name in code_map.mods[test_name].calls: return True return False",
"as f: page_function(f, code_map, func_name, func) filename = os.path.join(output_dir, func_graph_name(func_name)) with open(filename, 'w')",
"are called by, or call a module def func_touches_mod(kv): test_name = kv[0] test",
"in mod.functions: func = code_map.funcs[func_name] if func_name in test.calls: return True if test_name",
"call {}\\n\\n'.format(mod_name)) filt = codemap.calls(mod_name) for caller_name, caller in code_map.mods_sorted(filt): caller_link = link(caller_name,",
"def ispub(kv): return not kv[1].private for func_name, func in code_map.funcs_sorted(ispub): filename = os.path.join(output_dir,"
] |
[
"on a first-order ' + 'radiative-transfer model describing a rough surface' + 'covered",
"refer to the LICENSE file \"\"\" from setuptools import setup #from setuptools import",
"your license as you wish (should match \"license\" above) #~ 'License :: OSI",
":: Atmospheric Science', # Pick your license as you wish (should match \"license\"",
"import setup #from setuptools import find_packages from rt1 import __version__ setup(name='rt1', version=__version__, description='RT1",
"Scientific/Engineering :: Atmospheric Science', # Pick your license as you wish (should match",
"#~ license='APACHE 2', url='https://github.com/TUW-GEO/rt1', long_description=('A module to perform forward-simulation and ' + 'parameter-inversion",
"radiative transfer model', packages=['rt1'], package_dir={'rt1': 'rt1'}, include_package_data=False, author=\"<NAME>\", author_email='<EMAIL>', maintainer='<NAME>', maintainer_email='<EMAIL>', #~ license='APACHE",
"For COPYING and LICENSE details, please refer to the LICENSE file \"\"\" from",
"See https://pypi.python.org/pypi?%3Aaction=list_classifiers classifiers=[ 'Intended Audience :: Science/Research', 'Topic :: Scientific/Engineering :: Atmospheric Science',",
"from rt1 import __version__ setup(name='rt1', version=__version__, description='RT1 - bistatic single scattering radiative transfer",
"\"sympy>=1.4\", \"scipy>=1.2\", \"pandas>=0.24\", \"matplotlib>=3.0\"], extras_require={'symengine' : [\"symengine>=0.4\"]}, keywords=[\"physics\", \"radiative transfer\"], # See https://pypi.python.org/pypi?%3Aaction=list_classifiers",
"url='https://github.com/TUW-GEO/rt1', long_description=('A module to perform forward-simulation and ' + 'parameter-inversion of incidence-angle dependent",
"a first-order ' + 'radiative-transfer model describing a rough surface' + 'covered by",
"Atmospheric Science', # Pick your license as you wish (should match \"license\" above)",
"the LICENSE file \"\"\" from setuptools import setup #from setuptools import find_packages from",
"LICENSE file \"\"\" from setuptools import setup #from setuptools import find_packages from rt1",
"as you wish (should match \"license\" above) #~ 'License :: OSI Approved ::",
"transfer model', packages=['rt1'], package_dir={'rt1': 'rt1'}, include_package_data=False, author=\"<NAME>\", author_email='<EMAIL>', maintainer='<NAME>', maintainer_email='<EMAIL>', #~ license='APACHE 2',",
"import __version__ setup(name='rt1', version=__version__, description='RT1 - bistatic single scattering radiative transfer model', packages=['rt1'],",
"match \"license\" above) #~ 'License :: OSI Approved :: MIT License', 'Programming Language",
"model describing a rough surface' + 'covered by a homogeneous layer of scattering'",
":: Science/Research', 'Topic :: Scientific/Engineering :: Atmospheric Science', # Pick your license as",
"you wish (should match \"license\" above) #~ 'License :: OSI Approved :: MIT",
"+ 'covered by a homogeneous layer of scattering' + 'media.'), install_requires=[\"numpy>=1.16\", \"sympy>=1.4\", \"scipy>=1.2\",",
"perform forward-simulation and ' + 'parameter-inversion of incidence-angle dependent ' + 'backscatter observations",
"transfer\"], # See https://pypi.python.org/pypi?%3Aaction=list_classifiers classifiers=[ 'Intended Audience :: Science/Research', 'Topic :: Scientific/Engineering ::",
"author_email='<EMAIL>', maintainer='<NAME>', maintainer_email='<EMAIL>', #~ license='APACHE 2', url='https://github.com/TUW-GEO/rt1', long_description=('A module to perform forward-simulation and",
"# Pick your license as you wish (should match \"license\" above) #~ 'License",
"rt1 import __version__ setup(name='rt1', version=__version__, description='RT1 - bistatic single scattering radiative transfer model',",
"layer of scattering' + 'media.'), install_requires=[\"numpy>=1.16\", \"sympy>=1.4\", \"scipy>=1.2\", \"pandas>=0.24\", \"matplotlib>=3.0\"], extras_require={'symengine' : [\"symengine>=0.4\"]},",
"# -*- coding: UTF-8 -*- \"\"\" This file is part of RT1. (c)",
"#~ 'License :: OSI Approved :: MIT License', 'Programming Language :: Python ::",
"\"matplotlib>=3.0\"], extras_require={'symengine' : [\"symengine>=0.4\"]}, keywords=[\"physics\", \"radiative transfer\"], # See https://pypi.python.org/pypi?%3Aaction=list_classifiers classifiers=[ 'Intended Audience",
"author=\"<NAME>\", author_email='<EMAIL>', maintainer='<NAME>', maintainer_email='<EMAIL>', #~ license='APACHE 2', url='https://github.com/TUW-GEO/rt1', long_description=('A module to perform forward-simulation",
"license as you wish (should match \"license\" above) #~ 'License :: OSI Approved",
"description='RT1 - bistatic single scattering radiative transfer model', packages=['rt1'], package_dir={'rt1': 'rt1'}, include_package_data=False, author=\"<NAME>\",",
"Science', # Pick your license as you wish (should match \"license\" above) #~",
"rough surface' + 'covered by a homogeneous layer of scattering' + 'media.'), install_requires=[\"numpy>=1.16\",",
"dependent ' + 'backscatter observations based on a first-order ' + 'radiative-transfer model",
"file is part of RT1. (c) 2016- <NAME> For COPYING and LICENSE details,",
"\"\"\" This file is part of RT1. (c) 2016- <NAME> For COPYING and",
"is part of RT1. (c) 2016- <NAME> For COPYING and LICENSE details, please",
"setuptools import find_packages from rt1 import __version__ setup(name='rt1', version=__version__, description='RT1 - bistatic single",
"to the LICENSE file \"\"\" from setuptools import setup #from setuptools import find_packages",
"https://pypi.python.org/pypi?%3Aaction=list_classifiers classifiers=[ 'Intended Audience :: Science/Research', 'Topic :: Scientific/Engineering :: Atmospheric Science', #",
"<NAME> For COPYING and LICENSE details, please refer to the LICENSE file \"\"\"",
"2016- <NAME> For COPYING and LICENSE details, please refer to the LICENSE file",
"of incidence-angle dependent ' + 'backscatter observations based on a first-order ' +",
"surface' + 'covered by a homogeneous layer of scattering' + 'media.'), install_requires=[\"numpy>=1.16\", \"sympy>=1.4\",",
"UTF-8 -*- \"\"\" This file is part of RT1. (c) 2016- <NAME> For",
"coding: UTF-8 -*- \"\"\" This file is part of RT1. (c) 2016- <NAME>",
"a homogeneous layer of scattering' + 'media.'), install_requires=[\"numpy>=1.16\", \"sympy>=1.4\", \"scipy>=1.2\", \"pandas>=0.24\", \"matplotlib>=3.0\"], extras_require={'symengine'",
"#from setuptools import find_packages from rt1 import __version__ setup(name='rt1', version=__version__, description='RT1 - bistatic",
"Pick your license as you wish (should match \"license\" above) #~ 'License ::",
"+ 'media.'), install_requires=[\"numpy>=1.16\", \"sympy>=1.4\", \"scipy>=1.2\", \"pandas>=0.24\", \"matplotlib>=3.0\"], extras_require={'symengine' : [\"symengine>=0.4\"]}, keywords=[\"physics\", \"radiative transfer\"],",
":: OSI Approved :: MIT License', 'Programming Language :: Python :: 3.7' ],",
"of RT1. (c) 2016- <NAME> For COPYING and LICENSE details, please refer to",
"based on a first-order ' + 'radiative-transfer model describing a rough surface' +",
"details, please refer to the LICENSE file \"\"\" from setuptools import setup #from",
"This file is part of RT1. (c) 2016- <NAME> For COPYING and LICENSE",
"import find_packages from rt1 import __version__ setup(name='rt1', version=__version__, description='RT1 - bistatic single scattering",
"long_description=('A module to perform forward-simulation and ' + 'parameter-inversion of incidence-angle dependent '",
"please refer to the LICENSE file \"\"\" from setuptools import setup #from setuptools",
"keywords=[\"physics\", \"radiative transfer\"], # See https://pypi.python.org/pypi?%3Aaction=list_classifiers classifiers=[ 'Intended Audience :: Science/Research', 'Topic ::",
"Science/Research', 'Topic :: Scientific/Engineering :: Atmospheric Science', # Pick your license as you",
"(c) 2016- <NAME> For COPYING and LICENSE details, please refer to the LICENSE",
"maintainer='<NAME>', maintainer_email='<EMAIL>', #~ license='APACHE 2', url='https://github.com/TUW-GEO/rt1', long_description=('A module to perform forward-simulation and '",
"homogeneous layer of scattering' + 'media.'), install_requires=[\"numpy>=1.16\", \"sympy>=1.4\", \"scipy>=1.2\", \"pandas>=0.24\", \"matplotlib>=3.0\"], extras_require={'symengine' :",
"setup(name='rt1', version=__version__, description='RT1 - bistatic single scattering radiative transfer model', packages=['rt1'], package_dir={'rt1': 'rt1'},",
"by a homogeneous layer of scattering' + 'media.'), install_requires=[\"numpy>=1.16\", \"sympy>=1.4\", \"scipy>=1.2\", \"pandas>=0.24\", \"matplotlib>=3.0\"],",
"above) #~ 'License :: OSI Approved :: MIT License', 'Programming Language :: Python",
"\"license\" above) #~ 'License :: OSI Approved :: MIT License', 'Programming Language ::",
"COPYING and LICENSE details, please refer to the LICENSE file \"\"\" from setuptools",
"single scattering radiative transfer model', packages=['rt1'], package_dir={'rt1': 'rt1'}, include_package_data=False, author=\"<NAME>\", author_email='<EMAIL>', maintainer='<NAME>', maintainer_email='<EMAIL>',",
"part of RT1. (c) 2016- <NAME> For COPYING and LICENSE details, please refer",
"classifiers=[ 'Intended Audience :: Science/Research', 'Topic :: Scientific/Engineering :: Atmospheric Science', # Pick",
"' + 'backscatter observations based on a first-order ' + 'radiative-transfer model describing",
"setuptools import setup #from setuptools import find_packages from rt1 import __version__ setup(name='rt1', version=__version__,",
"- bistatic single scattering radiative transfer model', packages=['rt1'], package_dir={'rt1': 'rt1'}, include_package_data=False, author=\"<NAME>\", author_email='<EMAIL>',",
"setup #from setuptools import find_packages from rt1 import __version__ setup(name='rt1', version=__version__, description='RT1 -",
"find_packages from rt1 import __version__ setup(name='rt1', version=__version__, description='RT1 - bistatic single scattering radiative",
"+ 'parameter-inversion of incidence-angle dependent ' + 'backscatter observations based on a first-order",
"and ' + 'parameter-inversion of incidence-angle dependent ' + 'backscatter observations based on",
"' + 'radiative-transfer model describing a rough surface' + 'covered by a homogeneous",
"'covered by a homogeneous layer of scattering' + 'media.'), install_requires=[\"numpy>=1.16\", \"sympy>=1.4\", \"scipy>=1.2\", \"pandas>=0.24\",",
"maintainer_email='<EMAIL>', #~ license='APACHE 2', url='https://github.com/TUW-GEO/rt1', long_description=('A module to perform forward-simulation and ' +",
"scattering radiative transfer model', packages=['rt1'], package_dir={'rt1': 'rt1'}, include_package_data=False, author=\"<NAME>\", author_email='<EMAIL>', maintainer='<NAME>', maintainer_email='<EMAIL>', #~",
"include_package_data=False, author=\"<NAME>\", author_email='<EMAIL>', maintainer='<NAME>', maintainer_email='<EMAIL>', #~ license='APACHE 2', url='https://github.com/TUW-GEO/rt1', long_description=('A module to perform",
"scattering' + 'media.'), install_requires=[\"numpy>=1.16\", \"sympy>=1.4\", \"scipy>=1.2\", \"pandas>=0.24\", \"matplotlib>=3.0\"], extras_require={'symengine' : [\"symengine>=0.4\"]}, keywords=[\"physics\", \"radiative",
"license='APACHE 2', url='https://github.com/TUW-GEO/rt1', long_description=('A module to perform forward-simulation and ' + 'parameter-inversion of",
"module to perform forward-simulation and ' + 'parameter-inversion of incidence-angle dependent ' +",
"forward-simulation and ' + 'parameter-inversion of incidence-angle dependent ' + 'backscatter observations based",
"of scattering' + 'media.'), install_requires=[\"numpy>=1.16\", \"sympy>=1.4\", \"scipy>=1.2\", \"pandas>=0.24\", \"matplotlib>=3.0\"], extras_require={'symengine' : [\"symengine>=0.4\"]}, keywords=[\"physics\",",
"(should match \"license\" above) #~ 'License :: OSI Approved :: MIT License', 'Programming",
"\"scipy>=1.2\", \"pandas>=0.24\", \"matplotlib>=3.0\"], extras_require={'symengine' : [\"symengine>=0.4\"]}, keywords=[\"physics\", \"radiative transfer\"], # See https://pypi.python.org/pypi?%3Aaction=list_classifiers classifiers=[",
"packages=['rt1'], package_dir={'rt1': 'rt1'}, include_package_data=False, author=\"<NAME>\", author_email='<EMAIL>', maintainer='<NAME>', maintainer_email='<EMAIL>', #~ license='APACHE 2', url='https://github.com/TUW-GEO/rt1', long_description=('A",
"package_dir={'rt1': 'rt1'}, include_package_data=False, author=\"<NAME>\", author_email='<EMAIL>', maintainer='<NAME>', maintainer_email='<EMAIL>', #~ license='APACHE 2', url='https://github.com/TUW-GEO/rt1', long_description=('A module",
"'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 3.7'",
"file \"\"\" from setuptools import setup #from setuptools import find_packages from rt1 import",
"+ 'backscatter observations based on a first-order ' + 'radiative-transfer model describing a",
": [\"symengine>=0.4\"]}, keywords=[\"physics\", \"radiative transfer\"], # See https://pypi.python.org/pypi?%3Aaction=list_classifiers classifiers=[ 'Intended Audience :: Science/Research',",
"LICENSE details, please refer to the LICENSE file \"\"\" from setuptools import setup",
":: Scientific/Engineering :: Atmospheric Science', # Pick your license as you wish (should",
"'backscatter observations based on a first-order ' + 'radiative-transfer model describing a rough",
"2', url='https://github.com/TUW-GEO/rt1', long_description=('A module to perform forward-simulation and ' + 'parameter-inversion of incidence-angle",
"\"pandas>=0.24\", \"matplotlib>=3.0\"], extras_require={'symengine' : [\"symengine>=0.4\"]}, keywords=[\"physics\", \"radiative transfer\"], # See https://pypi.python.org/pypi?%3Aaction=list_classifiers classifiers=[ 'Intended",
"# See https://pypi.python.org/pypi?%3Aaction=list_classifiers classifiers=[ 'Intended Audience :: Science/Research', 'Topic :: Scientific/Engineering :: Atmospheric",
"+ 'radiative-transfer model describing a rough surface' + 'covered by a homogeneous layer",
"bistatic single scattering radiative transfer model', packages=['rt1'], package_dir={'rt1': 'rt1'}, include_package_data=False, author=\"<NAME>\", author_email='<EMAIL>', maintainer='<NAME>',",
"'media.'), install_requires=[\"numpy>=1.16\", \"sympy>=1.4\", \"scipy>=1.2\", \"pandas>=0.24\", \"matplotlib>=3.0\"], extras_require={'symengine' : [\"symengine>=0.4\"]}, keywords=[\"physics\", \"radiative transfer\"], #",
"install_requires=[\"numpy>=1.16\", \"sympy>=1.4\", \"scipy>=1.2\", \"pandas>=0.24\", \"matplotlib>=3.0\"], extras_require={'symengine' : [\"symengine>=0.4\"]}, keywords=[\"physics\", \"radiative transfer\"], # See",
"first-order ' + 'radiative-transfer model describing a rough surface' + 'covered by a",
"__version__ setup(name='rt1', version=__version__, description='RT1 - bistatic single scattering radiative transfer model', packages=['rt1'], package_dir={'rt1':",
"describing a rough surface' + 'covered by a homogeneous layer of scattering' +",
"wish (should match \"license\" above) #~ 'License :: OSI Approved :: MIT License',",
"'rt1'}, include_package_data=False, author=\"<NAME>\", author_email='<EMAIL>', maintainer='<NAME>', maintainer_email='<EMAIL>', #~ license='APACHE 2', url='https://github.com/TUW-GEO/rt1', long_description=('A module to",
"RT1. (c) 2016- <NAME> For COPYING and LICENSE details, please refer to the",
"OSI Approved :: MIT License', 'Programming Language :: Python :: 3.7' ], )",
"extras_require={'symengine' : [\"symengine>=0.4\"]}, keywords=[\"physics\", \"radiative transfer\"], # See https://pypi.python.org/pypi?%3Aaction=list_classifiers classifiers=[ 'Intended Audience ::",
"-*- \"\"\" This file is part of RT1. (c) 2016- <NAME> For COPYING",
"version=__version__, description='RT1 - bistatic single scattering radiative transfer model', packages=['rt1'], package_dir={'rt1': 'rt1'}, include_package_data=False,",
"\"\"\" from setuptools import setup #from setuptools import find_packages from rt1 import __version__",
"model', packages=['rt1'], package_dir={'rt1': 'rt1'}, include_package_data=False, author=\"<NAME>\", author_email='<EMAIL>', maintainer='<NAME>', maintainer_email='<EMAIL>', #~ license='APACHE 2', url='https://github.com/TUW-GEO/rt1',",
"to perform forward-simulation and ' + 'parameter-inversion of incidence-angle dependent ' + 'backscatter",
"'Topic :: Scientific/Engineering :: Atmospheric Science', # Pick your license as you wish",
"Audience :: Science/Research', 'Topic :: Scientific/Engineering :: Atmospheric Science', # Pick your license",
"'Intended Audience :: Science/Research', 'Topic :: Scientific/Engineering :: Atmospheric Science', # Pick your",
"incidence-angle dependent ' + 'backscatter observations based on a first-order ' + 'radiative-transfer",
"' + 'parameter-inversion of incidence-angle dependent ' + 'backscatter observations based on a",
"-*- coding: UTF-8 -*- \"\"\" This file is part of RT1. (c) 2016-",
"'radiative-transfer model describing a rough surface' + 'covered by a homogeneous layer of",
"'parameter-inversion of incidence-angle dependent ' + 'backscatter observations based on a first-order '",
"a rough surface' + 'covered by a homogeneous layer of scattering' + 'media.'),",
"[\"symengine>=0.4\"]}, keywords=[\"physics\", \"radiative transfer\"], # See https://pypi.python.org/pypi?%3Aaction=list_classifiers classifiers=[ 'Intended Audience :: Science/Research', 'Topic",
"\"radiative transfer\"], # See https://pypi.python.org/pypi?%3Aaction=list_classifiers classifiers=[ 'Intended Audience :: Science/Research', 'Topic :: Scientific/Engineering",
"and LICENSE details, please refer to the LICENSE file \"\"\" from setuptools import",
"from setuptools import setup #from setuptools import find_packages from rt1 import __version__ setup(name='rt1',",
"observations based on a first-order ' + 'radiative-transfer model describing a rough surface'"
] |
[
"pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union, overload from .. import",
"_utilities.get_resource_args_opts(VPCArgs, pulumi.ResourceOptions, *args, **kwargs) if resource_args is not None: __self__._internal_init(resource_name, opts, **resource_args.__dict__) else:",
"Optional[pulumi.Input[str]]): pulumi.set(self, \"name\", value) @property @pulumi.getter def remark(self) -> Optional[pulumi.Input[str]]: \"\"\" The remarks",
"not edit by hand unless you're certain you know what you are doing!",
"**kwargs) def _internal_init(__self__, resource_name: str, opts: Optional[pulumi.ResourceOptions] = None, cidr_blocks: Optional[pulumi.Input[Sequence[pulumi.Input[str]]]] = None,",
"None, remark: Optional[pulumi.Input[str]] = None, tag: Optional[pulumi.Input[str]] = None, update_time: Optional[pulumi.Input[str]] = None)",
"not None: pulumi.set(__self__, \"tag\", tag) if update_time is not None: pulumi.set(__self__, \"update_time\", update_time)",
"value: Optional[pulumi.Input[Sequence[pulumi.Input[str]]]]): pulumi.set(self, \"cidr_blocks\", value) @property @pulumi.getter(name=\"createTime\") def create_time(self) -> Optional[pulumi.Input[str]]: \"\"\" The",
"_VPCState.__new__(_VPCState) __props__.__dict__[\"cidr_blocks\"] = cidr_blocks __props__.__dict__[\"create_time\"] = create_time __props__.__dict__[\"name\"] = name __props__.__dict__[\"network_infos\"] = network_infos",
"None, remark: Optional[pulumi.Input[str]] = None, tag: Optional[pulumi.Input[str]] = None, __props__=None): if opts is",
"time string. :param pulumi.Input[Sequence[pulumi.Input['VPCNetworkInfoArgs']]] network_infos: It is a nested type which documented below.",
"pulumi.ResourceOptions(id=id)) __props__ = _VPCState.__new__(_VPCState) __props__.__dict__[\"cidr_blocks\"] = cidr_blocks __props__.__dict__[\"create_time\"] = create_time __props__.__dict__[\"name\"] = name",
"remark(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, \"remark\", value) @property @pulumi.getter def tag(self) -> Optional[pulumi.Input[str]]: \"\"\"",
"``` ## Import VPC can be imported using the `id`, e.g. ```sh $",
"remark(self) -> Optional[pulumi.Input[str]]: \"\"\" The remarks of the VPC. (Default: `\"\"`). \"\"\" return",
"-> pulumi.Output[str]: \"\"\" The time of creation for VPC, formatted in RFC3339 time",
"update_time: Optional[pulumi.Input[str]] = None): \"\"\" Input properties used for looking up and filtering",
"Optional[pulumi.Input[Sequence[pulumi.Input[str]]]] = None, name: Optional[pulumi.Input[str]] = None, remark: Optional[pulumi.Input[str]] = None, tag: Optional[pulumi.Input[str]]",
"a nested type which documented below. \"\"\" return pulumi.get(self, \"network_infos\") @property @pulumi.getter def",
"Optional[pulumi.Input[str]] = None, tag: Optional[pulumi.Input[str]] = None, __props__=None): \"\"\" Provides a VPC resource.",
"TypeError('Expected resource options to be a ResourceOptions instance') if opts.version is None: opts.version",
"def __init__(__self__, resource_name: str, *args, **kwargs): resource_args, opts = _utilities.get_resource_args_opts(VPCArgs, pulumi.ResourceOptions, *args, **kwargs)",
"pulumi.set(__self__, \"create_time\", create_time) if name is not None: pulumi.set(__self__, \"name\", name) if network_infos",
"tag __props__.__dict__[\"update_time\"] = update_time return VPC(resource_name, opts=opts, __props__=__props__) @property @pulumi.getter(name=\"cidrBlocks\") def cidr_blocks(self) ->",
"RFC3339 time string. :param pulumi.Input[Sequence[pulumi.Input[pulumi.InputType['VPCNetworkInfoArgs']]]] network_infos: It is a nested type which documented",
"__init__(__self__, *, cidr_blocks: Optional[pulumi.Input[Sequence[pulumi.Input[str]]]] = None, create_time: Optional[pulumi.Input[str]] = None, name: Optional[pulumi.Input[str]] =",
"name is not None: pulumi.set(__self__, \"name\", name) if network_infos is not None: pulumi.set(__self__,",
"cidr_blocks(self) -> Optional[pulumi.Input[Sequence[pulumi.Input[str]]]]: \"\"\" The CIDR blocks of VPC. \"\"\" return pulumi.get(self, \"cidr_blocks\")",
"a nested type which documented below. \"\"\" return pulumi.get(self, \"network_infos\") @network_infos.setter def network_infos(self,",
"@tag.setter def tag(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, \"tag\", value) @property @pulumi.getter(name=\"updateTime\") def update_time(self) ->",
"or a empty string is filled in, then default tag will be assigned.",
"\"cidr_blocks\", value) @property @pulumi.getter def name(self) -> Optional[pulumi.Input[str]]: return pulumi.get(self, \"name\") @name.setter def",
"pulumi.set(self, \"network_infos\", value) @property @pulumi.getter def remark(self) -> Optional[pulumi.Input[str]]: \"\"\" The remarks of",
"\"tag\", value) @property @pulumi.getter(name=\"updateTime\") def update_time(self) -> Optional[pulumi.Input[str]]: \"\"\" The time whenever there",
"VPC, formatted in RFC3339 time string. \"\"\" return pulumi.get(self, \"create_time\") @create_time.setter def create_time(self,",
"tag will be assigned. (Default: `Default`). \"\"\" ... @overload def __init__(__self__, resource_name: str,",
"them at the same time. ## Example Usage ```python import pulumi import pulumi_ucloud",
"```python import pulumi import pulumi_ucloud as ucloud example = ucloud.vpc.VPC(\"example\", cidr_blocks=[\"192.168.0.0/16\"], tag=\"tf-example\") ```",
"__props__ is not None: raise TypeError('__props__ is only valid when passed in combination",
"@pulumi.getter(name=\"cidrBlocks\") def cidr_blocks(self) -> pulumi.Input[Sequence[pulumi.Input[str]]]: \"\"\" The CIDR blocks of VPC. \"\"\" return",
"def get(resource_name: str, id: pulumi.Input[str], opts: Optional[pulumi.ResourceOptions] = None, cidr_blocks: Optional[pulumi.Input[Sequence[pulumi.Input[str]]]] = None,",
"filled in, then default tag will be assigned. (Default: `Default`). \"\"\" return pulumi.get(self,",
"pulumi.set(self, \"cidr_blocks\", value) @property @pulumi.getter def name(self) -> Optional[pulumi.Input[str]]: return pulumi.get(self, \"name\") @name.setter",
"def __init__(__self__, *, cidr_blocks: pulumi.Input[Sequence[pulumi.Input[str]]], name: Optional[pulumi.Input[str]] = None, remark: Optional[pulumi.Input[str]] = None,",
"cidr_blocks __props__.__dict__[\"name\"] = name __props__.__dict__[\"remark\"] = remark __props__.__dict__[\"tag\"] = tag __props__.__dict__[\"create_time\"] = None",
"network_infos: Optional[pulumi.Input[Sequence[pulumi.Input[pulumi.InputType['VPCNetworkInfoArgs']]]]] = None, remark: Optional[pulumi.Input[str]] = None, tag: Optional[pulumi.Input[str]] = None, update_time:",
"string is filled in, then default tag will be assigned. (Default: `Default`). \"\"\"",
"can only be created or deleted, can not perform both of them at",
"ucloud example = ucloud.vpc.VPC(\"example\", cidr_blocks=[\"192.168.0.0/16\"], tag=\"tf-example\") ``` ## Import VPC can be imported",
"in RFC3339 time string. \"\"\" return pulumi.get(self, \"create_time\") @create_time.setter def create_time(self, value: Optional[pulumi.Input[str]]):",
"*** # *** Do not edit by hand unless you're certain you know",
"only be created or deleted, can not perform both of them at the",
"-> Optional[pulumi.Input[str]]: \"\"\" The remarks of the VPC. (Default: `\"\"`). \"\"\" return pulumi.get(self,",
"pulumi.set(__self__, \"cidr_blocks\", cidr_blocks) if create_time is not None: pulumi.set(__self__, \"create_time\", create_time) if name",
"class _VPCState: def __init__(__self__, *, cidr_blocks: Optional[pulumi.Input[Sequence[pulumi.Input[str]]]] = None, create_time: Optional[pulumi.Input[str]] = None,",
"``` :param str resource_name: The name of the resource. :param pulumi.ResourceOptions opts: Options",
"remark) if tag is not None: pulumi.set(__self__, \"tag\", tag) @property @pulumi.getter(name=\"cidrBlocks\") def cidr_blocks(self)",
"The remarks of the VPC. (Default: `\"\"`). \"\"\" return pulumi.get(self, \"remark\") @remark.setter def",
"ID of the resource to lookup. :param pulumi.ResourceOptions opts: Options for the resource.",
"\"\"\" if cidr_blocks is not None: pulumi.set(__self__, \"cidr_blocks\", cidr_blocks) if create_time is not",
"\"cidr_blocks\") @cidr_blocks.setter def cidr_blocks(self, value: Optional[pulumi.Input[Sequence[pulumi.Input[str]]]]): pulumi.set(self, \"cidr_blocks\", value) @property @pulumi.getter(name=\"createTime\") def create_time(self)",
"`\"\"`). :param pulumi.Input[str] tag: A tag assigned to VPC, which contains at most",
"can be imported using the `id`, e.g. ```sh $ pulumi import ucloud:vpc/vPC:VPC example",
"\"\"\" return pulumi.get(self, \"remark\") @property @pulumi.getter def tag(self) -> pulumi.Output[Optional[str]]: \"\"\" A tag",
"super(VPC, __self__).__init__( 'ucloud:vpc/vPC:VPC', resource_name, __props__, opts) @staticmethod def get(resource_name: str, id: pulumi.Input[str], opts:",
"def _internal_init(__self__, resource_name: str, opts: Optional[pulumi.ResourceOptions] = None, cidr_blocks: Optional[pulumi.Input[Sequence[pulumi.Input[str]]]] = None, name:",
"of the VPC. (Default: `\"\"`). \"\"\" return pulumi.get(self, \"remark\") @remark.setter def remark(self, value:",
"\"\"\" Provides a VPC resource. > **Note** The network segment can only be",
"@network_infos.setter def network_infos(self, value: Optional[pulumi.Input[Sequence[pulumi.Input['VPCNetworkInfoArgs']]]]): pulumi.set(self, \"network_infos\", value) @property @pulumi.getter def remark(self) ->",
"*, cidr_blocks: pulumi.Input[Sequence[pulumi.Input[str]]], name: Optional[pulumi.Input[str]] = None, remark: Optional[pulumi.Input[str]] = None, tag: Optional[pulumi.Input[str]]",
"VPCArgs, opts: Optional[pulumi.ResourceOptions] = None): \"\"\" Provides a VPC resource. > **Note** The",
"Optional[pulumi.Input[Sequence[pulumi.Input[str]]]] = None, create_time: Optional[pulumi.Input[str]] = None, name: Optional[pulumi.Input[str]] = None, network_infos: Optional[pulumi.Input[Sequence[pulumi.Input[pulumi.InputType['VPCNetworkInfoArgs']]]]]",
"can not perform both of them at the same time. ## Example Usage",
"`Default`). \"\"\" return pulumi.get(self, \"tag\") @tag.setter def tag(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, \"tag\", value)",
"not filled in or a empty string is filled in, then default tag",
"@cidr_blocks.setter def cidr_blocks(self, value: Optional[pulumi.Input[Sequence[pulumi.Input[str]]]]): pulumi.set(self, \"cidr_blocks\", value) @property @pulumi.getter(name=\"createTime\") def create_time(self) ->",
"__props__.__dict__[\"update_time\"] = update_time return VPC(resource_name, opts=opts, __props__=__props__) @property @pulumi.getter(name=\"cidrBlocks\") def cidr_blocks(self) -> pulumi.Output[Sequence[str]]:",
"only support Chinese, English, numbers, '-', '_', and '.'. If it is not",
"is not filled in or a empty string is filled in, then default",
"__props__.__dict__[\"update_time\"] = None super(VPC, __self__).__init__( 'ucloud:vpc/vPC:VPC', resource_name, __props__, opts) @staticmethod def get(resource_name: str,",
"The CIDR blocks of VPC. \"\"\" return pulumi.get(self, \"cidr_blocks\") @property @pulumi.getter(name=\"createTime\") def create_time(self)",
"passed in combination with a valid opts.id to get an existing resource') __props__",
"> **Note** The network segment can only be created or deleted, can not",
"= None, tag: Optional[pulumi.Input[str]] = None, update_time: Optional[pulumi.Input[str]] = None) -> 'VPC': \"\"\"",
"if cidr_blocks is None and not opts.urn: raise TypeError(\"Missing required property 'cidr_blocks'\") __props__.__dict__[\"cidr_blocks\"]",
"resource's state with the given name, id, and optional extra properties used to",
"@name.setter def name(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, \"name\", value) @property @pulumi.getter(name=\"networkInfos\") def network_infos(self) ->",
"this resource's properties. :param pulumi.ResourceOptions opts: Options for the resource. \"\"\" ... def",
"__props__.__dict__[\"cidr_blocks\"] = cidr_blocks __props__.__dict__[\"name\"] = name __props__.__dict__[\"remark\"] = remark __props__.__dict__[\"tag\"] = tag __props__.__dict__[\"create_time\"]",
"= None, tag: Optional[pulumi.Input[str]] = None, update_time: Optional[pulumi.Input[str]] = None): \"\"\" Input properties",
"@property @pulumi.getter(name=\"updateTime\") def update_time(self) -> pulumi.Output[str]: \"\"\" The time whenever there is a",
"VPC. (Default: `\"\"`). :param pulumi.Input[str] tag: A tag assigned to VPC, which contains",
"below. \"\"\" return pulumi.get(self, \"network_infos\") @property @pulumi.getter def remark(self) -> pulumi.Output[str]: \"\"\" The",
"and '.'. If it is not filled in or a empty string is",
"def name(self) -> Optional[pulumi.Input[str]]: return pulumi.get(self, \"name\") @name.setter def name(self, value: Optional[pulumi.Input[str]]): pulumi.set(self,",
"empty string is filled in, then default tag will be assigned. (Default: `Default`).",
"create_time: The time of creation for VPC, formatted in RFC3339 time string. :param",
"tag is not None: pulumi.set(__self__, \"tag\", tag) @property @pulumi.getter(name=\"cidrBlocks\") def cidr_blocks(self) -> pulumi.Input[Sequence[pulumi.Input[str]]]:",
"is not None: pulumi.set(__self__, \"cidr_blocks\", cidr_blocks) if create_time is not None: pulumi.set(__self__, \"create_time\",",
"\"cidr_blocks\", value) @property @pulumi.getter(name=\"createTime\") def create_time(self) -> Optional[pulumi.Input[str]]: \"\"\" The time of creation",
"\"name\", value) @property @pulumi.getter(name=\"networkInfos\") def network_infos(self) -> Optional[pulumi.Input[Sequence[pulumi.Input['VPCNetworkInfoArgs']]]]: \"\"\" It is a nested",
"None, name: Optional[pulumi.Input[str]] = None, remark: Optional[pulumi.Input[str]] = None, tag: Optional[pulumi.Input[str]] = None,",
"value) @pulumi.input_type class _VPCState: def __init__(__self__, *, cidr_blocks: Optional[pulumi.Input[Sequence[pulumi.Input[str]]]] = None, create_time: Optional[pulumi.Input[str]]",
"perform both of them at the same time. ## Example Usage ```python import",
"uvnet-abc123456 ``` :param str resource_name: The name of the resource. :param pulumi.ResourceOptions opts:",
"**kwargs) if resource_args is not None: __self__._internal_init(resource_name, opts, **resource_args.__dict__) else: __self__._internal_init(resource_name, *args, **kwargs)",
"state with the given name, id, and optional extra properties used to qualify",
"= None, name: Optional[pulumi.Input[str]] = None, remark: Optional[pulumi.Input[str]] = None, tag: Optional[pulumi.Input[str]] =",
"formatted in RFC3339 time string. \"\"\" return pulumi.get(self, \"update_time\") @update_time.setter def update_time(self, value:",
"-> Optional[pulumi.Input[str]]: \"\"\" The time whenever there is a change made to VPC,",
"= None) -> 'VPC': \"\"\" Get an existing VPC resource's state with the",
"id: The unique provider ID of the resource to lookup. :param pulumi.ResourceOptions opts:",
"@create_time.setter def create_time(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, \"create_time\", value) @property @pulumi.getter def name(self) ->",
"to VPC, formatted in RFC3339 time string. \"\"\" opts = pulumi.ResourceOptions.merge(opts, pulumi.ResourceOptions(id=id)) __props__",
"tag: Optional[pulumi.Input[str]] = None, update_time: Optional[pulumi.Input[str]] = None): \"\"\" Input properties used for",
"raise TypeError(\"Missing required property 'cidr_blocks'\") __props__.__dict__[\"cidr_blocks\"] = cidr_blocks __props__.__dict__[\"name\"] = name __props__.__dict__[\"remark\"] =",
"cidr_blocks is not None: pulumi.set(__self__, \"cidr_blocks\", cidr_blocks) if create_time is not None: pulumi.set(__self__,",
"(tfgen) Tool. *** # *** Do not edit by hand unless you're certain",
"opts = pulumi.ResourceOptions.merge(opts, pulumi.ResourceOptions(id=id)) __props__ = _VPCState.__new__(_VPCState) __props__.__dict__[\"cidr_blocks\"] = cidr_blocks __props__.__dict__[\"create_time\"] = create_time",
"to VPC, which contains at most 63 characters and only support Chinese, English,",
"id: pulumi.Input[str], opts: Optional[pulumi.ResourceOptions] = None, cidr_blocks: Optional[pulumi.Input[Sequence[pulumi.Input[str]]]] = None, create_time: Optional[pulumi.Input[str]] =",
"Optional[pulumi.Input[str]]): pulumi.set(self, \"create_time\", value) @property @pulumi.getter def name(self) -> Optional[pulumi.Input[str]]: return pulumi.get(self, \"name\")",
"# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen)",
"resource_name: str, args: VPCArgs, opts: Optional[pulumi.ResourceOptions] = None): \"\"\" Provides a VPC resource.",
"options to be a ResourceOptions instance') if opts.version is None: opts.version = _utilities.get_version()",
"if __props__ is not None: raise TypeError('__props__ is only valid when passed in",
"Optional[pulumi.Input[str]]: \"\"\" A tag assigned to VPC, which contains at most 63 characters",
"= None, create_time: Optional[pulumi.Input[str]] = None, name: Optional[pulumi.Input[str]] = None, network_infos: Optional[pulumi.Input[Sequence[pulumi.Input['VPCNetworkInfoArgs']]]] =",
"= pulumi.ResourceOptions.merge(opts, pulumi.ResourceOptions(id=id)) __props__ = _VPCState.__new__(_VPCState) __props__.__dict__[\"cidr_blocks\"] = cidr_blocks __props__.__dict__[\"create_time\"] = create_time __props__.__dict__[\"name\"]",
"\"remark\") @property @pulumi.getter def tag(self) -> pulumi.Output[Optional[str]]: \"\"\" A tag assigned to VPC,",
"return pulumi.get(self, \"remark\") @property @pulumi.getter def tag(self) -> pulumi.Output[Optional[str]]: \"\"\" A tag assigned",
"= ucloud.vpc.VPC(\"example\", cidr_blocks=[\"192.168.0.0/16\"], tag=\"tf-example\") ``` ## Import VPC can be imported using the",
":param pulumi.Input[str] create_time: The time of creation for VPC, formatted in RFC3339 time",
"documented below. \"\"\" return pulumi.get(self, \"network_infos\") @network_infos.setter def network_infos(self, value: Optional[pulumi.Input[Sequence[pulumi.Input['VPCNetworkInfoArgs']]]]): pulumi.set(self, \"network_infos\",",
"\"create_time\") @create_time.setter def create_time(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, \"create_time\", value) @property @pulumi.getter def name(self)",
"Input properties used for looking up and filtering VPC resources. :param pulumi.Input[Sequence[pulumi.Input[str]]] cidr_blocks:",
"update_time is not None: pulumi.set(__self__, \"update_time\", update_time) @property @pulumi.getter(name=\"cidrBlocks\") def cidr_blocks(self) -> Optional[pulumi.Input[Sequence[pulumi.Input[str]]]]:",
"to VPC, formatted in RFC3339 time string. \"\"\" if cidr_blocks is not None:",
"assigned. (Default: `Default`). \"\"\" pulumi.set(__self__, \"cidr_blocks\", cidr_blocks) if name is not None: pulumi.set(__self__,",
"pulumi import ucloud:vpc/vPC:VPC example uvnet-abc123456 ``` :param str resource_name: The name of the",
"= None, create_time: Optional[pulumi.Input[str]] = None, name: Optional[pulumi.Input[str]] = None, network_infos: Optional[pulumi.Input[Sequence[pulumi.Input[pulumi.InputType['VPCNetworkInfoArgs']]]]] =",
"__all__ = ['VPCArgs', 'VPC'] @pulumi.input_type class VPCArgs: def __init__(__self__, *, cidr_blocks: pulumi.Input[Sequence[pulumi.Input[str]]], name:",
"def tag(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, \"tag\", value) @property @pulumi.getter(name=\"updateTime\") def update_time(self) -> Optional[pulumi.Input[str]]:",
"VPC. (Default: `\"\"`). \"\"\" return pulumi.get(self, \"remark\") @remark.setter def remark(self, value: Optional[pulumi.Input[str]]): pulumi.set(self,",
"import Any, Mapping, Optional, Sequence, Union, overload from .. import _utilities from .",
"None: __self__._internal_init(resource_name, opts, **resource_args.__dict__) else: __self__._internal_init(resource_name, *args, **kwargs) def _internal_init(__self__, resource_name: str, opts:",
"__props__.__dict__[\"create_time\"] = None __props__.__dict__[\"network_infos\"] = None __props__.__dict__[\"update_time\"] = None super(VPC, __self__).__init__( 'ucloud:vpc/vPC:VPC', resource_name,",
"pulumi.set(__self__, \"name\", name) if network_infos is not None: pulumi.set(__self__, \"network_infos\", network_infos) if remark",
"the VPC. (Default: `\"\"`). :param pulumi.Input[str] tag: A tag assigned to VPC, which",
"pulumi.Input[Sequence[pulumi.Input[str]]] cidr_blocks: The CIDR blocks of VPC. :param pulumi.Input[str] create_time: The time of",
"return pulumi.get(self, \"remark\") @remark.setter def remark(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, \"remark\", value) @property @pulumi.getter",
"or deleted, can not perform both of them at the same time. ##",
"\"\"\" It is a nested type which documented below. \"\"\" return pulumi.get(self, \"network_infos\")",
"deleted, can not perform both of them at the same time. ## Example",
"the given name, id, and optional extra properties used to qualify the lookup.",
"pulumi.get(self, \"create_time\") @property @pulumi.getter def name(self) -> pulumi.Output[str]: return pulumi.get(self, \"name\") @property @pulumi.getter(name=\"networkInfos\")",
"def __init__(__self__, resource_name: str, args: VPCArgs, opts: Optional[pulumi.ResourceOptions] = None): \"\"\" Provides a",
"be created or deleted, can not perform both of them at the same",
"tag) if update_time is not None: pulumi.set(__self__, \"update_time\", update_time) @property @pulumi.getter(name=\"cidrBlocks\") def cidr_blocks(self)",
"= None): \"\"\" Provides a VPC resource. > **Note** The network segment can",
"unique provider ID of the resource to lookup. :param pulumi.ResourceOptions opts: Options for",
"(Default: `Default`). \"\"\" return pulumi.get(self, \"tag\") @property @pulumi.getter(name=\"updateTime\") def update_time(self) -> pulumi.Output[str]: \"\"\"",
"is a change made to VPC, formatted in RFC3339 time string. \"\"\" return",
"filled in, then default tag will be assigned. (Default: `Default`). \"\"\" ... @overload",
"pulumi.Input[str] id: The unique provider ID of the resource to lookup. :param pulumi.ResourceOptions",
"tag: Optional[pulumi.Input[str]] = None): \"\"\" The set of arguments for constructing a VPC",
"from .. import _utilities from . import outputs from ._inputs import * __all__",
"resource_name, __props__, opts) @staticmethod def get(resource_name: str, id: pulumi.Input[str], opts: Optional[pulumi.ResourceOptions] = None,",
"Optional[pulumi.Input[str]] = None, remark: Optional[pulumi.Input[str]] = None, tag: Optional[pulumi.Input[str]] = None, __props__=None): if",
"Optional[pulumi.Input[str]] = None): \"\"\" The set of arguments for constructing a VPC resource.",
"@overload def __init__(__self__, resource_name: str, opts: Optional[pulumi.ResourceOptions] = None, cidr_blocks: Optional[pulumi.Input[Sequence[pulumi.Input[str]]]] = None,",
"is not None: pulumi.set(__self__, \"tag\", tag) if update_time is not None: pulumi.set(__self__, \"update_time\",",
"to use to populate this resource's properties. :param pulumi.ResourceOptions opts: Options for the",
"value: Optional[pulumi.Input[str]]): pulumi.set(self, \"tag\", value) @pulumi.input_type class _VPCState: def __init__(__self__, *, cidr_blocks: Optional[pulumi.Input[Sequence[pulumi.Input[str]]]]",
"name(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, \"name\", value) @property @pulumi.getter(name=\"networkInfos\") def network_infos(self) -> Optional[pulumi.Input[Sequence[pulumi.Input['VPCNetworkInfoArgs']]]]: \"\"\"",
"= None super(VPC, __self__).__init__( 'ucloud:vpc/vPC:VPC', resource_name, __props__, opts) @staticmethod def get(resource_name: str, id:",
"of the resulting resource. :param pulumi.Input[str] id: The unique provider ID of the",
"\"network_infos\") @network_infos.setter def network_infos(self, value: Optional[pulumi.Input[Sequence[pulumi.Input['VPCNetworkInfoArgs']]]]): pulumi.set(self, \"network_infos\", value) @property @pulumi.getter def remark(self)",
"'VPC': \"\"\" Get an existing VPC resource's state with the given name, id,",
"-> Optional[pulumi.Input[Sequence[pulumi.Input[str]]]]: \"\"\" The CIDR blocks of VPC. \"\"\" return pulumi.get(self, \"cidr_blocks\") @cidr_blocks.setter",
"opts = _utilities.get_resource_args_opts(VPCArgs, pulumi.ResourceOptions, *args, **kwargs) if resource_args is not None: __self__._internal_init(resource_name, opts,",
"CIDR blocks of VPC. :param pulumi.Input[str] create_time: The time of creation for VPC,",
"tag: Optional[pulumi.Input[str]] = None, __props__=None): \"\"\" Provides a VPC resource. > **Note** The",
"at most 63 characters and only support Chinese, English, numbers, '-', '_', and",
":param pulumi.Input[Sequence[pulumi.Input[str]]] cidr_blocks: The CIDR blocks of VPC. :param pulumi.Input[str] create_time: The time",
"segment can only be created or deleted, can not perform both of them",
"is None: opts = pulumi.ResourceOptions() if not isinstance(opts, pulumi.ResourceOptions): raise TypeError('Expected resource options",
"@property @pulumi.getter def name(self) -> pulumi.Output[str]: return pulumi.get(self, \"name\") @property @pulumi.getter(name=\"networkInfos\") def network_infos(self)",
"instance') if opts.version is None: opts.version = _utilities.get_version() if opts.id is None: if",
"opts.id is None: if __props__ is not None: raise TypeError('__props__ is only valid",
"resource. \"\"\" ... def __init__(__self__, resource_name: str, *args, **kwargs): resource_args, opts = _utilities.get_resource_args_opts(VPCArgs,",
"resource_name: str, *args, **kwargs): resource_args, opts = _utilities.get_resource_args_opts(VPCArgs, pulumi.ResourceOptions, *args, **kwargs) if resource_args",
"63 characters and only support Chinese, English, numbers, '-', '_', and '.'. If",
"value: pulumi.Input[Sequence[pulumi.Input[str]]]): pulumi.set(self, \"cidr_blocks\", value) @property @pulumi.getter def name(self) -> Optional[pulumi.Input[str]]: return pulumi.get(self,",
"def remark(self) -> Optional[pulumi.Input[str]]: \"\"\" The remarks of the VPC. (Default: `\"\"`). \"\"\"",
"used for looking up and filtering VPC resources. :param pulumi.Input[Sequence[pulumi.Input[str]]] cidr_blocks: The CIDR",
"def update_time(self) -> Optional[pulumi.Input[str]]: \"\"\" The time whenever there is a change made",
"*args, **kwargs) def _internal_init(__self__, resource_name: str, opts: Optional[pulumi.ResourceOptions] = None, cidr_blocks: Optional[pulumi.Input[Sequence[pulumi.Input[str]]]] =",
"tag=\"tf-example\") ``` ## Import VPC can be imported using the `id`, e.g. ```sh",
"cidr_blocks: The CIDR blocks of VPC. :param pulumi.Input[str] remark: The remarks of the",
"str, id: pulumi.Input[str], opts: Optional[pulumi.ResourceOptions] = None, cidr_blocks: Optional[pulumi.Input[Sequence[pulumi.Input[str]]]] = None, create_time: Optional[pulumi.Input[str]]",
"\"name\", name) if remark is not None: pulumi.set(__self__, \"remark\", remark) if tag is",
"resulting resource. :param pulumi.Input[str] id: The unique provider ID of the resource to",
"VPC, formatted in RFC3339 time string. \"\"\" return pulumi.get(self, \"create_time\") @property @pulumi.getter def",
"will be assigned. (Default: `Default`). \"\"\" return pulumi.get(self, \"tag\") @property @pulumi.getter(name=\"updateTime\") def update_time(self)",
"= None, update_time: Optional[pulumi.Input[str]] = None): \"\"\" Input properties used for looking up",
"is a nested type which documented below. :param pulumi.Input[str] remark: The remarks of",
"\"update_time\", update_time) @property @pulumi.getter(name=\"cidrBlocks\") def cidr_blocks(self) -> Optional[pulumi.Input[Sequence[pulumi.Input[str]]]]: \"\"\" The CIDR blocks of",
"type which documented below. :param pulumi.Input[str] remark: The remarks of the VPC. (Default:",
"None): \"\"\" The set of arguments for constructing a VPC resource. :param pulumi.Input[Sequence[pulumi.Input[str]]]",
"None: opts = pulumi.ResourceOptions() if not isinstance(opts, pulumi.ResourceOptions): raise TypeError('Expected resource options to",
"pulumi.ResourceOptions opts: Options for the resource. :param pulumi.Input[Sequence[pulumi.Input[str]]] cidr_blocks: The CIDR blocks of",
"CIDR blocks of VPC. \"\"\" return pulumi.get(self, \"cidr_blocks\") @cidr_blocks.setter def cidr_blocks(self, value: pulumi.Input[Sequence[pulumi.Input[str]]]):",
"\"\"\" Input properties used for looking up and filtering VPC resources. :param pulumi.Input[Sequence[pulumi.Input[str]]]",
"cidr_blocks: Optional[pulumi.Input[Sequence[pulumi.Input[str]]]] = None, name: Optional[pulumi.Input[str]] = None, remark: Optional[pulumi.Input[str]] = None, tag:",
"class VPCArgs: def __init__(__self__, *, cidr_blocks: pulumi.Input[Sequence[pulumi.Input[str]]], name: Optional[pulumi.Input[str]] = None, remark: Optional[pulumi.Input[str]]",
"tag will be assigned. (Default: `Default`). \"\"\" return pulumi.get(self, \"tag\") @property @pulumi.getter(name=\"updateTime\") def",
"the `id`, e.g. ```sh $ pulumi import ucloud:vpc/vPC:VPC example uvnet-abc123456 ``` :param str",
"of creation for VPC, formatted in RFC3339 time string. :param pulumi.Input[Sequence[pulumi.Input[pulumi.InputType['VPCNetworkInfoArgs']]]] network_infos: It",
"optional extra properties used to qualify the lookup. :param str resource_name: The unique",
"pulumi.set(__self__, \"tag\", tag) if update_time is not None: pulumi.set(__self__, \"update_time\", update_time) @property @pulumi.getter(name=\"cidrBlocks\")",
"__props__=None): \"\"\" Provides a VPC resource. > **Note** The network segment can only",
"remark: Optional[pulumi.Input[str]] = None, tag: Optional[pulumi.Input[str]] = None, update_time: Optional[pulumi.Input[str]] = None) ->",
"then default tag will be assigned. (Default: `Default`). \"\"\" pulumi.set(__self__, \"cidr_blocks\", cidr_blocks) if",
"the resource. :param pulumi.Input[Sequence[pulumi.Input[str]]] cidr_blocks: The CIDR blocks of VPC. :param pulumi.Input[str] remark:",
"with a valid opts.id to get an existing resource') __props__ = VPCArgs.__new__(VPCArgs) if",
"formatted in RFC3339 time string. :param pulumi.Input[Sequence[pulumi.Input['VPCNetworkInfoArgs']]] network_infos: It is a nested type",
"to be a ResourceOptions instance') if opts.version is None: opts.version = _utilities.get_version() if",
"None super(VPC, __self__).__init__( 'ucloud:vpc/vPC:VPC', resource_name, __props__, opts) @staticmethod def get(resource_name: str, id: pulumi.Input[str],",
"of the resource to lookup. :param pulumi.ResourceOptions opts: Options for the resource. :param",
"documented below. :param pulumi.Input[str] remark: The remarks of the VPC. (Default: `\"\"`). :param",
"@remark.setter def remark(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, \"remark\", value) @property @pulumi.getter def tag(self) ->",
"__props__.__dict__[\"network_infos\"] = None __props__.__dict__[\"update_time\"] = None super(VPC, __self__).__init__( 'ucloud:vpc/vPC:VPC', resource_name, __props__, opts) @staticmethod",
"Terraform Bridge (tfgen) Tool. *** # *** Do not edit by hand unless",
"remark __props__.__dict__[\"tag\"] = tag __props__.__dict__[\"create_time\"] = None __props__.__dict__[\"network_infos\"] = None __props__.__dict__[\"update_time\"] = None",
"Optional[pulumi.Input[str]]: \"\"\" The time whenever there is a change made to VPC, formatted",
"Optional[pulumi.ResourceOptions] = None, cidr_blocks: Optional[pulumi.Input[Sequence[pulumi.Input[str]]]] = None, name: Optional[pulumi.Input[str]] = None, remark: Optional[pulumi.Input[str]]",
"= None, name: Optional[pulumi.Input[str]] = None, network_infos: Optional[pulumi.Input[Sequence[pulumi.Input['VPCNetworkInfoArgs']]]] = None, remark: Optional[pulumi.Input[str]] =",
"to VPC, formatted in RFC3339 time string. \"\"\" return pulumi.get(self, \"update_time\") @update_time.setter def",
"the lookup. :param str resource_name: The unique name of the resulting resource. :param",
"looking up and filtering VPC resources. :param pulumi.Input[Sequence[pulumi.Input[str]]] cidr_blocks: The CIDR blocks of",
"creation for VPC, formatted in RFC3339 time string. \"\"\" return pulumi.get(self, \"create_time\") @property",
"class VPC(pulumi.CustomResource): @overload def __init__(__self__, resource_name: str, opts: Optional[pulumi.ResourceOptions] = None, cidr_blocks: Optional[pulumi.Input[Sequence[pulumi.Input[str]]]]",
"from . import outputs from ._inputs import * __all__ = ['VPCArgs', 'VPC'] @pulumi.input_type",
"\"remark\") @remark.setter def remark(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, \"remark\", value) @property @pulumi.getter def tag(self)",
"lookup. :param str resource_name: The unique name of the resulting resource. :param pulumi.Input[str]",
"in RFC3339 time string. :param pulumi.Input[Sequence[pulumi.Input[pulumi.InputType['VPCNetworkInfoArgs']]]] network_infos: It is a nested type which",
"Provides a VPC resource. > **Note** The network segment can only be created",
"CIDR blocks of VPC. :param pulumi.Input[str] remark: The remarks of the VPC. (Default:",
"@pulumi.input_type class VPCArgs: def __init__(__self__, *, cidr_blocks: pulumi.Input[Sequence[pulumi.Input[str]]], name: Optional[pulumi.Input[str]] = None, remark:",
"@pulumi.getter def remark(self) -> pulumi.Output[str]: \"\"\" The remarks of the VPC. (Default: `\"\"`).",
"cidr_blocks: The CIDR blocks of VPC. :param pulumi.Input[str] create_time: The time of creation",
"@pulumi.getter(name=\"networkInfos\") def network_infos(self) -> Optional[pulumi.Input[Sequence[pulumi.Input['VPCNetworkInfoArgs']]]]: \"\"\" It is a nested type which documented",
"`\"\"`). \"\"\" return pulumi.get(self, \"remark\") @remark.setter def remark(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, \"remark\", value)",
"resource. > **Note** The network segment can only be created or deleted, can",
"pulumi.Input[Sequence[pulumi.Input[str]]]): pulumi.set(self, \"cidr_blocks\", value) @property @pulumi.getter def name(self) -> Optional[pulumi.Input[str]]: return pulumi.get(self, \"name\")",
"__props__.__dict__[\"remark\"] = remark __props__.__dict__[\"tag\"] = tag __props__.__dict__[\"update_time\"] = update_time return VPC(resource_name, opts=opts, __props__=__props__)",
"(Default: `\"\"`). \"\"\" return pulumi.get(self, \"remark\") @property @pulumi.getter def tag(self) -> pulumi.Output[Optional[str]]: \"\"\"",
"from typing import Any, Mapping, Optional, Sequence, Union, overload from .. import _utilities",
"property 'cidr_blocks'\") __props__.__dict__[\"cidr_blocks\"] = cidr_blocks __props__.__dict__[\"name\"] = name __props__.__dict__[\"remark\"] = remark __props__.__dict__[\"tag\"] =",
"assigned. (Default: `Default`). \"\"\" return pulumi.get(self, \"tag\") @property @pulumi.getter(name=\"updateTime\") def update_time(self) -> pulumi.Output[str]:",
"Optional[pulumi.Input[str]] = None, name: Optional[pulumi.Input[str]] = None, network_infos: Optional[pulumi.Input[Sequence[pulumi.Input[pulumi.InputType['VPCNetworkInfoArgs']]]]] = None, remark: Optional[pulumi.Input[str]]",
"VPC resource. > **Note** The network segment can only be created or deleted,",
"@pulumi.getter(name=\"updateTime\") def update_time(self) -> Optional[pulumi.Input[str]]: \"\"\" The time whenever there is a change",
"`Default`). :param pulumi.Input[str] update_time: The time whenever there is a change made to",
"None, __props__=None): if opts is None: opts = pulumi.ResourceOptions() if not isinstance(opts, pulumi.ResourceOptions):",
"= ['VPCArgs', 'VPC'] @pulumi.input_type class VPCArgs: def __init__(__self__, *, cidr_blocks: pulumi.Input[Sequence[pulumi.Input[str]]], name: Optional[pulumi.Input[str]]",
"VPC. \"\"\" return pulumi.get(self, \"cidr_blocks\") @cidr_blocks.setter def cidr_blocks(self, value: pulumi.Input[Sequence[pulumi.Input[str]]]): pulumi.set(self, \"cidr_blocks\", value)",
"extra properties used to qualify the lookup. :param str resource_name: The unique name",
"\"name\") @name.setter def name(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, \"name\", value) @property @pulumi.getter def remark(self)",
"Chinese, English, numbers, '-', '_', and '.'. If it is not filled in",
"\"tag\") @tag.setter def tag(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, \"tag\", value) @pulumi.input_type class _VPCState: def",
"imported using the `id`, e.g. ```sh $ pulumi import ucloud:vpc/vPC:VPC example uvnet-abc123456 ```",
"= None, __props__=None): if opts is None: opts = pulumi.ResourceOptions() if not isinstance(opts,",
"VPCArgs.__new__(VPCArgs) if cidr_blocks is None and not opts.urn: raise TypeError(\"Missing required property 'cidr_blocks'\")",
"you're certain you know what you are doing! *** import warnings import pulumi",
"not None: pulumi.set(__self__, \"name\", name) if remark is not None: pulumi.set(__self__, \"remark\", remark)",
"opts: Optional[pulumi.ResourceOptions] = None, cidr_blocks: Optional[pulumi.Input[Sequence[pulumi.Input[str]]]] = None, name: Optional[pulumi.Input[str]] = None, remark:",
"unless you're certain you know what you are doing! *** import warnings import",
"value) @property @pulumi.getter def remark(self) -> Optional[pulumi.Input[str]]: \"\"\" The remarks of the VPC.",
"up and filtering VPC resources. :param pulumi.Input[Sequence[pulumi.Input[str]]] cidr_blocks: The CIDR blocks of VPC.",
"given name, id, and optional extra properties used to qualify the lookup. :param",
"network_infos(self) -> Optional[pulumi.Input[Sequence[pulumi.Input['VPCNetworkInfoArgs']]]]: \"\"\" It is a nested type which documented below. \"\"\"",
"get an existing resource') __props__ = VPCArgs.__new__(VPCArgs) if cidr_blocks is None and not",
"in, then default tag will be assigned. (Default: `Default`). :param pulumi.Input[str] update_time: The",
"populate this resource's properties. :param pulumi.ResourceOptions opts: Options for the resource. \"\"\" ...",
"import outputs from ._inputs import * __all__ = ['VPCArgs', 'VPC'] @pulumi.input_type class VPCArgs:",
"the resource. \"\"\" ... def __init__(__self__, resource_name: str, *args, **kwargs): resource_args, opts =",
":param pulumi.Input[str] update_time: The time whenever there is a change made to VPC,",
"not None: pulumi.set(__self__, \"network_infos\", network_infos) if remark is not None: pulumi.set(__self__, \"remark\", remark)",
"in, then default tag will be assigned. (Default: `Default`). \"\"\" return pulumi.get(self, \"tag\")",
"Optional[pulumi.Input[str]] = None, update_time: Optional[pulumi.Input[str]] = None) -> 'VPC': \"\"\" Get an existing",
"string. \"\"\" if cidr_blocks is not None: pulumi.set(__self__, \"cidr_blocks\", cidr_blocks) if create_time is",
"VPC resources. :param pulumi.Input[Sequence[pulumi.Input[str]]] cidr_blocks: The CIDR blocks of VPC. :param pulumi.Input[str] create_time:",
"update_time(self) -> pulumi.Output[str]: \"\"\" The time whenever there is a change made to",
"__props__.__dict__[\"cidr_blocks\"] = cidr_blocks __props__.__dict__[\"create_time\"] = create_time __props__.__dict__[\"name\"] = name __props__.__dict__[\"network_infos\"] = network_infos __props__.__dict__[\"remark\"]",
"= None, __props__=None): \"\"\" Provides a VPC resource. > **Note** The network segment",
"the Pulumi Terraform Bridge (tfgen) Tool. *** # *** Do not edit by",
"['VPCArgs', 'VPC'] @pulumi.input_type class VPCArgs: def __init__(__self__, *, cidr_blocks: pulumi.Input[Sequence[pulumi.Input[str]]], name: Optional[pulumi.Input[str]] =",
"is not None: __self__._internal_init(resource_name, opts, **resource_args.__dict__) else: __self__._internal_init(resource_name, *args, **kwargs) def _internal_init(__self__, resource_name:",
"= name __props__.__dict__[\"network_infos\"] = network_infos __props__.__dict__[\"remark\"] = remark __props__.__dict__[\"tag\"] = tag __props__.__dict__[\"update_time\"] =",
"(Default: `Default`). \"\"\" pulumi.set(__self__, \"cidr_blocks\", cidr_blocks) if name is not None: pulumi.set(__self__, \"name\",",
"__init__(__self__, resource_name: str, *args, **kwargs): resource_args, opts = _utilities.get_resource_args_opts(VPCArgs, pulumi.ResourceOptions, *args, **kwargs) if",
"for the resource. \"\"\" ... def __init__(__self__, resource_name: str, *args, **kwargs): resource_args, opts",
"pulumi.Output[str]: \"\"\" The remarks of the VPC. (Default: `\"\"`). \"\"\" return pulumi.get(self, \"remark\")",
"Optional[pulumi.Input[str]] = None, name: Optional[pulumi.Input[str]] = None, network_infos: Optional[pulumi.Input[Sequence[pulumi.Input['VPCNetworkInfoArgs']]]] = None, remark: Optional[pulumi.Input[str]]",
"if tag is not None: pulumi.set(__self__, \"tag\", tag) @property @pulumi.getter(name=\"cidrBlocks\") def cidr_blocks(self) ->",
"return pulumi.get(self, \"name\") @property @pulumi.getter(name=\"networkInfos\") def network_infos(self) -> pulumi.Output[Sequence['outputs.VPCNetworkInfo']]: \"\"\" It is a",
"resource. :param pulumi.Input[str] id: The unique provider ID of the resource to lookup.",
"blocks of VPC. \"\"\" return pulumi.get(self, \"cidr_blocks\") @cidr_blocks.setter def cidr_blocks(self, value: Optional[pulumi.Input[Sequence[pulumi.Input[str]]]]): pulumi.set(self,",
"pulumi.get(self, \"cidr_blocks\") @cidr_blocks.setter def cidr_blocks(self, value: Optional[pulumi.Input[Sequence[pulumi.Input[str]]]]): pulumi.set(self, \"cidr_blocks\", value) @property @pulumi.getter(name=\"createTime\") def",
"Optional[pulumi.Input[str]]): pulumi.set(self, \"update_time\", value) class VPC(pulumi.CustomResource): @overload def __init__(__self__, resource_name: str, opts: Optional[pulumi.ResourceOptions]",
"uvnet-abc123456 ``` :param str resource_name: The name of the resource. :param VPCArgs args:",
"Optional[pulumi.Input[str]] = None, network_infos: Optional[pulumi.Input[Sequence[pulumi.Input['VPCNetworkInfoArgs']]]] = None, remark: Optional[pulumi.Input[str]] = None, tag: Optional[pulumi.Input[str]]",
"ResourceOptions instance') if opts.version is None: opts.version = _utilities.get_version() if opts.id is None:",
"a change made to VPC, formatted in RFC3339 time string. \"\"\" if cidr_blocks",
"VPC, formatted in RFC3339 time string. :param pulumi.Input[Sequence[pulumi.Input['VPCNetworkInfoArgs']]] network_infos: It is a nested",
"@property @pulumi.getter(name=\"updateTime\") def update_time(self) -> Optional[pulumi.Input[str]]: \"\"\" The time whenever there is a",
"= None, tag: Optional[pulumi.Input[str]] = None, __props__=None): if opts is None: opts =",
"remark __props__.__dict__[\"tag\"] = tag __props__.__dict__[\"update_time\"] = update_time return VPC(resource_name, opts=opts, __props__=__props__) @property @pulumi.getter(name=\"cidrBlocks\")",
"\"name\") @property @pulumi.getter(name=\"networkInfos\") def network_infos(self) -> pulumi.Output[Sequence['outputs.VPCNetworkInfo']]: \"\"\" It is a nested type",
"@property @pulumi.getter def name(self) -> Optional[pulumi.Input[str]]: return pulumi.get(self, \"name\") @name.setter def name(self, value:",
"pulumi.set(__self__, \"remark\", remark) if tag is not None: pulumi.set(__self__, \"tag\", tag) if update_time",
"in, then default tag will be assigned. (Default: `Default`). \"\"\" pulumi.set(__self__, \"cidr_blocks\", cidr_blocks)",
"name of the resource. :param VPCArgs args: The arguments to use to populate",
"opts.id to get an existing resource') __props__ = VPCArgs.__new__(VPCArgs) if cidr_blocks is None",
"unique name of the resulting resource. :param pulumi.Input[str] id: The unique provider ID",
"value) @property @pulumi.getter(name=\"updateTime\") def update_time(self) -> Optional[pulumi.Input[str]]: \"\"\" The time whenever there is",
"by hand unless you're certain you know what you are doing! *** import",
"of creation for VPC, formatted in RFC3339 time string. :param pulumi.Input[Sequence[pulumi.Input['VPCNetworkInfoArgs']]] network_infos: It",
"if create_time is not None: pulumi.set(__self__, \"create_time\", create_time) if name is not None:",
"*** import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional,",
"tag will be assigned. (Default: `Default`). \"\"\" return pulumi.get(self, \"tag\") @tag.setter def tag(self,",
"you are doing! *** import warnings import pulumi import pulumi.runtime from typing import",
"None) -> 'VPC': \"\"\" Get an existing VPC resource's state with the given",
"it is not filled in or a empty string is filled in, then",
"pulumi.Output[Sequence[str]]: \"\"\" The CIDR blocks of VPC. \"\"\" return pulumi.get(self, \"cidr_blocks\") @property @pulumi.getter(name=\"createTime\")",
"existing resource') __props__ = VPCArgs.__new__(VPCArgs) if cidr_blocks is None and not opts.urn: raise",
"formatted in RFC3339 time string. \"\"\" return pulumi.get(self, \"create_time\") @create_time.setter def create_time(self, value:",
"remark(self) -> pulumi.Output[str]: \"\"\" The remarks of the VPC. (Default: `\"\"`). \"\"\" return",
"\"\"\" The remarks of the VPC. (Default: `\"\"`). \"\"\" return pulumi.get(self, \"remark\") @property",
"__props__ = VPCArgs.__new__(VPCArgs) if cidr_blocks is None and not opts.urn: raise TypeError(\"Missing required",
"Optional[pulumi.Input[Sequence[pulumi.Input['VPCNetworkInfoArgs']]]]): pulumi.set(self, \"network_infos\", value) @property @pulumi.getter def remark(self) -> Optional[pulumi.Input[str]]: \"\"\" The remarks",
"assigned. (Default: `Default`). \"\"\" ... @overload def __init__(__self__, resource_name: str, args: VPCArgs, opts:",
"Bridge (tfgen) Tool. *** # *** Do not edit by hand unless you're",
"an existing resource') __props__ = VPCArgs.__new__(VPCArgs) if cidr_blocks is None and not opts.urn:",
"assigned. (Default: `Default`). \"\"\" return pulumi.get(self, \"tag\") @tag.setter def tag(self, value: Optional[pulumi.Input[str]]): pulumi.set(self,",
"@pulumi.getter(name=\"createTime\") def create_time(self) -> Optional[pulumi.Input[str]]: \"\"\" The time of creation for VPC, formatted",
"The set of arguments for constructing a VPC resource. :param pulumi.Input[Sequence[pulumi.Input[str]]] cidr_blocks: The",
"an existing VPC resource's state with the given name, id, and optional extra",
"\"\"\" return pulumi.get(self, \"network_infos\") @network_infos.setter def network_infos(self, value: Optional[pulumi.Input[Sequence[pulumi.Input['VPCNetworkInfoArgs']]]]): pulumi.set(self, \"network_infos\", value) @property",
":param pulumi.Input[str] tag: A tag assigned to VPC, which contains at most 63",
"remark: Optional[pulumi.Input[str]] = None, tag: Optional[pulumi.Input[str]] = None, update_time: Optional[pulumi.Input[str]] = None): \"\"\"",
"'VPC'] @pulumi.input_type class VPCArgs: def __init__(__self__, *, cidr_blocks: pulumi.Input[Sequence[pulumi.Input[str]]], name: Optional[pulumi.Input[str]] = None,",
"pulumi.set(__self__, \"cidr_blocks\", cidr_blocks) if name is not None: pulumi.set(__self__, \"name\", name) if remark",
"None: pulumi.set(__self__, \"network_infos\", network_infos) if remark is not None: pulumi.set(__self__, \"remark\", remark) if",
"Optional[pulumi.Input[str]] = None, __props__=None): \"\"\" Provides a VPC resource. > **Note** The network",
"None: pulumi.set(__self__, \"name\", name) if remark is not None: pulumi.set(__self__, \"remark\", remark) if",
"Optional[pulumi.ResourceOptions] = None): \"\"\" Provides a VPC resource. > **Note** The network segment",
"resource_args is not None: __self__._internal_init(resource_name, opts, **resource_args.__dict__) else: __self__._internal_init(resource_name, *args, **kwargs) def _internal_init(__self__,",
"be imported using the `id`, e.g. ```sh $ pulumi import ucloud:vpc/vPC:VPC example uvnet-abc123456",
"`Default`). \"\"\" pulumi.set(__self__, \"cidr_blocks\", cidr_blocks) if name is not None: pulumi.set(__self__, \"name\", name)",
"be assigned. (Default: `Default`). :param pulumi.Input[str] update_time: The time whenever there is a",
"\"tag\") @tag.setter def tag(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, \"tag\", value) @property @pulumi.getter(name=\"updateTime\") def update_time(self)",
"if name is not None: pulumi.set(__self__, \"name\", name) if network_infos is not None:",
"time string. \"\"\" return pulumi.get(self, \"update_time\") @update_time.setter def update_time(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, \"update_time\",",
"constructing a VPC resource. :param pulumi.Input[Sequence[pulumi.Input[str]]] cidr_blocks: The CIDR blocks of VPC. :param",
"time string. \"\"\" if cidr_blocks is not None: pulumi.set(__self__, \"cidr_blocks\", cidr_blocks) if create_time",
"for VPC, formatted in RFC3339 time string. \"\"\" return pulumi.get(self, \"create_time\") @create_time.setter def",
"pulumi.Input[Sequence[pulumi.Input[str]]], name: Optional[pulumi.Input[str]] = None, remark: Optional[pulumi.Input[str]] = None, tag: Optional[pulumi.Input[str]] = None):",
"network_infos(self, value: Optional[pulumi.Input[Sequence[pulumi.Input['VPCNetworkInfoArgs']]]]): pulumi.set(self, \"network_infos\", value) @property @pulumi.getter def remark(self) -> Optional[pulumi.Input[str]]: \"\"\"",
"opts) @staticmethod def get(resource_name: str, id: pulumi.Input[str], opts: Optional[pulumi.ResourceOptions] = None, cidr_blocks: Optional[pulumi.Input[Sequence[pulumi.Input[str]]]]",
"change made to VPC, formatted in RFC3339 time string. \"\"\" opts = pulumi.ResourceOptions.merge(opts,",
"@property @pulumi.getter(name=\"cidrBlocks\") def cidr_blocks(self) -> Optional[pulumi.Input[Sequence[pulumi.Input[str]]]]: \"\"\" The CIDR blocks of VPC. \"\"\"",
"\"\"\" return pulumi.get(self, \"cidr_blocks\") @property @pulumi.getter(name=\"createTime\") def create_time(self) -> pulumi.Output[str]: \"\"\" The time",
"# *** Do not edit by hand unless you're certain you know what",
"__props__.__dict__[\"tag\"] = tag __props__.__dict__[\"update_time\"] = update_time return VPC(resource_name, opts=opts, __props__=__props__) @property @pulumi.getter(name=\"cidrBlocks\") def",
"if opts.id is None: if __props__ is not None: raise TypeError('__props__ is only",
"update_time(self) -> Optional[pulumi.Input[str]]: \"\"\" The time whenever there is a change made to",
"the resulting resource. :param pulumi.Input[str] id: The unique provider ID of the resource",
"coding=utf-8 # *** WARNING: this file was generated by the Pulumi Terraform Bridge",
"is None and not opts.urn: raise TypeError(\"Missing required property 'cidr_blocks'\") __props__.__dict__[\"cidr_blocks\"] = cidr_blocks",
"string. \"\"\" return pulumi.get(self, \"create_time\") @property @pulumi.getter def name(self) -> pulumi.Output[str]: return pulumi.get(self,",
"'_', and '.'. If it is not filled in or a empty string",
"which contains at most 63 characters and only support Chinese, English, numbers, '-',",
"*** Do not edit by hand unless you're certain you know what you",
"assigned to VPC, which contains at most 63 characters and only support Chinese,",
"\"\"\" The remarks of the VPC. (Default: `\"\"`). \"\"\" return pulumi.get(self, \"remark\") @remark.setter",
"pulumi.set(__self__, \"update_time\", update_time) @property @pulumi.getter(name=\"cidrBlocks\") def cidr_blocks(self) -> Optional[pulumi.Input[Sequence[pulumi.Input[str]]]]: \"\"\" The CIDR blocks",
"import pulumi import pulumi_ucloud as ucloud example = ucloud.vpc.VPC(\"example\", cidr_blocks=[\"192.168.0.0/16\"], tag=\"tf-example\") ``` ##",
"time whenever there is a change made to VPC, formatted in RFC3339 time",
"= None __props__.__dict__[\"update_time\"] = None super(VPC, __self__).__init__( 'ucloud:vpc/vPC:VPC', resource_name, __props__, opts) @staticmethod def",
"= None, network_infos: Optional[pulumi.Input[Sequence[pulumi.Input[pulumi.InputType['VPCNetworkInfoArgs']]]]] = None, remark: Optional[pulumi.Input[str]] = None, tag: Optional[pulumi.Input[str]] =",
"args: VPCArgs, opts: Optional[pulumi.ResourceOptions] = None): \"\"\" Provides a VPC resource. > **Note**",
"pulumi_ucloud as ucloud example = ucloud.vpc.VPC(\"example\", cidr_blocks=[\"192.168.0.0/16\"], tag=\"tf-example\") ``` ## Import VPC can",
"opts.version = _utilities.get_version() if opts.id is None: if __props__ is not None: raise",
"is filled in, then default tag will be assigned. (Default: `Default`). \"\"\" pulumi.set(__self__,",
"pulumi.set(self, \"name\", value) @property @pulumi.getter def remark(self) -> Optional[pulumi.Input[str]]: \"\"\" The remarks of",
"and not opts.urn: raise TypeError(\"Missing required property 'cidr_blocks'\") __props__.__dict__[\"cidr_blocks\"] = cidr_blocks __props__.__dict__[\"name\"] =",
"None, cidr_blocks: Optional[pulumi.Input[Sequence[pulumi.Input[str]]]] = None, name: Optional[pulumi.Input[str]] = None, remark: Optional[pulumi.Input[str]] = None,",
"def network_infos(self) -> pulumi.Output[Sequence['outputs.VPCNetworkInfo']]: \"\"\" It is a nested type which documented below.",
"-> pulumi.Output[str]: \"\"\" The remarks of the VPC. (Default: `\"\"`). \"\"\" return pulumi.get(self,",
"pulumi.get(self, \"remark\") @property @pulumi.getter def tag(self) -> pulumi.Output[Optional[str]]: \"\"\" A tag assigned to",
"for the resource. :param pulumi.Input[Sequence[pulumi.Input[str]]] cidr_blocks: The CIDR blocks of VPC. :param pulumi.Input[str]",
"which documented below. \"\"\" return pulumi.get(self, \"network_infos\") @network_infos.setter def network_infos(self, value: Optional[pulumi.Input[Sequence[pulumi.Input['VPCNetworkInfoArgs']]]]): pulumi.set(self,",
"\"\"\" ... def __init__(__self__, resource_name: str, *args, **kwargs): resource_args, opts = _utilities.get_resource_args_opts(VPCArgs, pulumi.ResourceOptions,",
"= None, network_infos: Optional[pulumi.Input[Sequence[pulumi.Input['VPCNetworkInfoArgs']]]] = None, remark: Optional[pulumi.Input[str]] = None, tag: Optional[pulumi.Input[str]] =",
"if name is not None: pulumi.set(__self__, \"name\", name) if remark is not None:",
"tag will be assigned. (Default: `Default`). :param pulumi.Input[str] update_time: The time whenever there",
"return pulumi.get(self, \"network_infos\") @network_infos.setter def network_infos(self, value: Optional[pulumi.Input[Sequence[pulumi.Input['VPCNetworkInfoArgs']]]]): pulumi.set(self, \"network_infos\", value) @property @pulumi.getter",
"VPC(resource_name, opts=opts, __props__=__props__) @property @pulumi.getter(name=\"cidrBlocks\") def cidr_blocks(self) -> pulumi.Output[Sequence[str]]: \"\"\" The CIDR blocks",
"cidr_blocks __props__.__dict__[\"create_time\"] = create_time __props__.__dict__[\"name\"] = name __props__.__dict__[\"network_infos\"] = network_infos __props__.__dict__[\"remark\"] = remark",
"pulumi.set(__self__, \"remark\", remark) if tag is not None: pulumi.set(__self__, \"tag\", tag) @property @pulumi.getter(name=\"cidrBlocks\")",
"None: pulumi.set(__self__, \"cidr_blocks\", cidr_blocks) if create_time is not None: pulumi.set(__self__, \"create_time\", create_time) if",
"pulumi import pulumi_ucloud as ucloud example = ucloud.vpc.VPC(\"example\", cidr_blocks=[\"192.168.0.0/16\"], tag=\"tf-example\") ``` ## Import",
"in RFC3339 time string. \"\"\" return pulumi.get(self, \"create_time\") @property @pulumi.getter def name(self) ->",
"def update_time(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, \"update_time\", value) class VPC(pulumi.CustomResource): @overload def __init__(__self__, resource_name:",
"-> Optional[pulumi.Input[str]]: \"\"\" The time of creation for VPC, formatted in RFC3339 time",
"Usage ```python import pulumi import pulumi_ucloud as ucloud example = ucloud.vpc.VPC(\"example\", cidr_blocks=[\"192.168.0.0/16\"], tag=\"tf-example\")",
"network_infos __props__.__dict__[\"remark\"] = remark __props__.__dict__[\"tag\"] = tag __props__.__dict__[\"update_time\"] = update_time return VPC(resource_name, opts=opts,",
"of the VPC. (Default: `\"\"`). \"\"\" return pulumi.get(self, \"remark\") @property @pulumi.getter def tag(self)",
"= None, name: Optional[pulumi.Input[str]] = None, network_infos: Optional[pulumi.Input[Sequence[pulumi.Input[pulumi.InputType['VPCNetworkInfoArgs']]]]] = None, remark: Optional[pulumi.Input[str]] =",
"The remarks of the VPC. (Default: `\"\"`). \"\"\" return pulumi.get(self, \"remark\") @property @pulumi.getter",
"is not None: pulumi.set(__self__, \"create_time\", create_time) if name is not None: pulumi.set(__self__, \"name\",",
"\"tag\", value) @pulumi.input_type class _VPCState: def __init__(__self__, *, cidr_blocks: Optional[pulumi.Input[Sequence[pulumi.Input[str]]]] = None, create_time:",
"value) @property @pulumi.getter(name=\"createTime\") def create_time(self) -> Optional[pulumi.Input[str]]: \"\"\" The time of creation for",
"in RFC3339 time string. \"\"\" return pulumi.get(self, \"update_time\") @update_time.setter def update_time(self, value: Optional[pulumi.Input[str]]):",
"is a change made to VPC, formatted in RFC3339 time string. \"\"\" if",
"-> Optional[pulumi.Input[str]]: \"\"\" A tag assigned to VPC, which contains at most 63",
"will be assigned. (Default: `Default`). \"\"\" return pulumi.get(self, \"tag\") @tag.setter def tag(self, value:",
"of VPC. \"\"\" return pulumi.get(self, \"cidr_blocks\") @cidr_blocks.setter def cidr_blocks(self, value: Optional[pulumi.Input[Sequence[pulumi.Input[str]]]]): pulumi.set(self, \"cidr_blocks\",",
"Optional[pulumi.Input[str]] = None, __props__=None): if opts is None: opts = pulumi.ResourceOptions() if not",
"pulumi.set(self, \"tag\", value) @pulumi.input_type class _VPCState: def __init__(__self__, *, cidr_blocks: Optional[pulumi.Input[Sequence[pulumi.Input[str]]]] = None,",
"None: pulumi.set(__self__, \"remark\", remark) if tag is not None: pulumi.set(__self__, \"tag\", tag) @property",
"$ pulumi import ucloud:vpc/vPC:VPC example uvnet-abc123456 ``` :param str resource_name: The name of",
"Optional[pulumi.Input[Sequence[pulumi.Input['VPCNetworkInfoArgs']]]]: \"\"\" It is a nested type which documented below. \"\"\" return pulumi.get(self,",
"@pulumi.getter(name=\"updateTime\") def update_time(self) -> pulumi.Output[str]: \"\"\" The time whenever there is a change",
"\"cidr_blocks\") @cidr_blocks.setter def cidr_blocks(self, value: pulumi.Input[Sequence[pulumi.Input[str]]]): pulumi.set(self, \"cidr_blocks\", value) @property @pulumi.getter def name(self)",
"\"cidr_blocks\", cidr_blocks) if name is not None: pulumi.set(__self__, \"name\", name) if remark is",
"args: The arguments to use to populate this resource's properties. :param pulumi.ResourceOptions opts:",
"None, __props__=None): \"\"\" Provides a VPC resource. > **Note** The network segment can",
"default tag will be assigned. (Default: `Default`). \"\"\" return pulumi.get(self, \"tag\") @tag.setter def",
"is not None: pulumi.set(__self__, \"update_time\", update_time) @property @pulumi.getter(name=\"cidrBlocks\") def cidr_blocks(self) -> Optional[pulumi.Input[Sequence[pulumi.Input[str]]]]: \"\"\"",
"None, tag: Optional[pulumi.Input[str]] = None, __props__=None): \"\"\" Provides a VPC resource. > **Note**",
"use to populate this resource's properties. :param pulumi.ResourceOptions opts: Options for the resource.",
"Optional[pulumi.Input[str]] = None): \"\"\" Input properties used for looking up and filtering VPC",
"None, network_infos: Optional[pulumi.Input[Sequence[pulumi.Input[pulumi.InputType['VPCNetworkInfoArgs']]]]] = None, remark: Optional[pulumi.Input[str]] = None, tag: Optional[pulumi.Input[str]] = None,",
":param str resource_name: The name of the resource. :param pulumi.ResourceOptions opts: Options for",
"to qualify the lookup. :param str resource_name: The unique name of the resulting",
"creation for VPC, formatted in RFC3339 time string. :param pulumi.Input[Sequence[pulumi.Input['VPCNetworkInfoArgs']]] network_infos: It is",
"time of creation for VPC, formatted in RFC3339 time string. :param pulumi.Input[Sequence[pulumi.Input['VPCNetworkInfoArgs']]] network_infos:",
"VPC. :param pulumi.Input[str] remark: The remarks of the VPC. (Default: `\"\"`). :param pulumi.Input[str]",
"filled in, then default tag will be assigned. (Default: `Default`). :param pulumi.Input[str] update_time:",
"Tool. *** # *** Do not edit by hand unless you're certain you",
"(Default: `Default`). :param pulumi.Input[str] update_time: The time whenever there is a change made",
"name: Optional[pulumi.Input[str]] = None, network_infos: Optional[pulumi.Input[Sequence[pulumi.Input[pulumi.InputType['VPCNetworkInfoArgs']]]]] = None, remark: Optional[pulumi.Input[str]] = None, tag:",
"network_infos: It is a nested type which documented below. :param pulumi.Input[str] remark: The",
"RFC3339 time string. \"\"\" return pulumi.get(self, \"create_time\") @property @pulumi.getter def name(self) -> pulumi.Output[str]:",
"None: if __props__ is not None: raise TypeError('__props__ is only valid when passed",
"nested type which documented below. \"\"\" return pulumi.get(self, \"network_infos\") @property @pulumi.getter def remark(self)",
"resource options to be a ResourceOptions instance') if opts.version is None: opts.version =",
"pulumi.get(self, \"create_time\") @create_time.setter def create_time(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, \"create_time\", value) @property @pulumi.getter def",
"@pulumi.getter def name(self) -> pulumi.Output[str]: return pulumi.get(self, \"name\") @property @pulumi.getter(name=\"networkInfos\") def network_infos(self) ->",
"None, name: Optional[pulumi.Input[str]] = None, network_infos: Optional[pulumi.Input[Sequence[pulumi.Input['VPCNetworkInfoArgs']]]] = None, remark: Optional[pulumi.Input[str]] = None,",
"opts: Optional[pulumi.ResourceOptions] = None, cidr_blocks: Optional[pulumi.Input[Sequence[pulumi.Input[str]]]] = None, create_time: Optional[pulumi.Input[str]] = None, name:",
"time. ## Example Usage ```python import pulumi import pulumi_ucloud as ucloud example =",
"It is a nested type which documented below. \"\"\" return pulumi.get(self, \"network_infos\") @property",
"is not None: pulumi.set(__self__, \"name\", name) if network_infos is not None: pulumi.set(__self__, \"network_infos\",",
"edit by hand unless you're certain you know what you are doing! ***",
"name: Optional[pulumi.Input[str]] = None, network_infos: Optional[pulumi.Input[Sequence[pulumi.Input['VPCNetworkInfoArgs']]]] = None, remark: Optional[pulumi.Input[str]] = None, tag:",
"\"name\") @name.setter def name(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, \"name\", value) @property @pulumi.getter(name=\"networkInfos\") def network_infos(self)",
"tag(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, \"tag\", value) @pulumi.input_type class _VPCState: def __init__(__self__, *, cidr_blocks:",
"both of them at the same time. ## Example Usage ```python import pulumi",
"resource_name: The name of the resource. :param pulumi.ResourceOptions opts: Options for the resource.",
"time string. \"\"\" return pulumi.get(self, \"create_time\") @property @pulumi.getter def name(self) -> pulumi.Output[str]: return",
"pulumi.Input[str] update_time: The time whenever there is a change made to VPC, formatted",
"pulumi.get(self, \"name\") @name.setter def name(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, \"name\", value) @property @pulumi.getter def",
"if cidr_blocks is not None: pulumi.set(__self__, \"cidr_blocks\", cidr_blocks) if create_time is not None:",
"tag is not None: pulumi.set(__self__, \"tag\", tag) if update_time is not None: pulumi.set(__self__,",
"pulumi.get(self, \"cidr_blocks\") @property @pulumi.getter(name=\"createTime\") def create_time(self) -> pulumi.Output[str]: \"\"\" The time of creation",
"cidr_blocks) if create_time is not None: pulumi.set(__self__, \"create_time\", create_time) if name is not",
"type which documented below. \"\"\" return pulumi.get(self, \"network_infos\") @network_infos.setter def network_infos(self, value: Optional[pulumi.Input[Sequence[pulumi.Input['VPCNetworkInfoArgs']]]]):",
"\"cidr_blocks\", cidr_blocks) if create_time is not None: pulumi.set(__self__, \"create_time\", create_time) if name is",
"is not None: raise TypeError('__props__ is only valid when passed in combination with",
"if not isinstance(opts, pulumi.ResourceOptions): raise TypeError('Expected resource options to be a ResourceOptions instance')",
"= None, tag: Optional[pulumi.Input[str]] = None, __props__=None): \"\"\" Provides a VPC resource. >",
"of the resource. :param VPCArgs args: The arguments to use to populate this",
"will be assigned. (Default: `Default`). \"\"\" ... @overload def __init__(__self__, resource_name: str, args:",
"import * __all__ = ['VPCArgs', 'VPC'] @pulumi.input_type class VPCArgs: def __init__(__self__, *, cidr_blocks:",
"not None: pulumi.set(__self__, \"create_time\", create_time) if name is not None: pulumi.set(__self__, \"name\", name)",
"name of the resulting resource. :param pulumi.Input[str] id: The unique provider ID of",
"not perform both of them at the same time. ## Example Usage ```python",
"example = ucloud.vpc.VPC(\"example\", cidr_blocks=[\"192.168.0.0/16\"], tag=\"tf-example\") ``` ## Import VPC can be imported using",
"@pulumi.getter def name(self) -> Optional[pulumi.Input[str]]: return pulumi.get(self, \"name\") @name.setter def name(self, value: Optional[pulumi.Input[str]]):",
"for looking up and filtering VPC resources. :param pulumi.Input[Sequence[pulumi.Input[str]]] cidr_blocks: The CIDR blocks",
"\"tag\", tag) if update_time is not None: pulumi.set(__self__, \"update_time\", update_time) @property @pulumi.getter(name=\"cidrBlocks\") def",
"Optional[pulumi.Input[Sequence[pulumi.Input[str]]]]: \"\"\" The CIDR blocks of VPC. \"\"\" return pulumi.get(self, \"cidr_blocks\") @cidr_blocks.setter def",
"Optional[pulumi.Input[Sequence[pulumi.Input[str]]]]): pulumi.set(self, \"cidr_blocks\", value) @property @pulumi.getter(name=\"createTime\") def create_time(self) -> Optional[pulumi.Input[str]]: \"\"\" The time",
"Optional[pulumi.Input[str]] = None, network_infos: Optional[pulumi.Input[Sequence[pulumi.Input[pulumi.InputType['VPCNetworkInfoArgs']]]]] = None, remark: Optional[pulumi.Input[str]] = None, tag: Optional[pulumi.Input[str]]",
"'cidr_blocks'\") __props__.__dict__[\"cidr_blocks\"] = cidr_blocks __props__.__dict__[\"name\"] = name __props__.__dict__[\"remark\"] = remark __props__.__dict__[\"tag\"] = tag",
"pulumi.Input[Sequence[pulumi.Input[str]]] cidr_blocks: The CIDR blocks of VPC. :param pulumi.Input[str] remark: The remarks of",
"resource to lookup. :param pulumi.ResourceOptions opts: Options for the resource. :param pulumi.Input[Sequence[pulumi.Input[str]]] cidr_blocks:",
"TypeError(\"Missing required property 'cidr_blocks'\") __props__.__dict__[\"cidr_blocks\"] = cidr_blocks __props__.__dict__[\"name\"] = name __props__.__dict__[\"remark\"] = remark",
"and only support Chinese, English, numbers, '-', '_', and '.'. If it is",
"opts is None: opts = pulumi.ResourceOptions() if not isinstance(opts, pulumi.ResourceOptions): raise TypeError('Expected resource",
"def cidr_blocks(self) -> Optional[pulumi.Input[Sequence[pulumi.Input[str]]]]: \"\"\" The CIDR blocks of VPC. \"\"\" return pulumi.get(self,",
"None: pulumi.set(__self__, \"update_time\", update_time) @property @pulumi.getter(name=\"cidrBlocks\") def cidr_blocks(self) -> Optional[pulumi.Input[Sequence[pulumi.Input[str]]]]: \"\"\" The CIDR",
"None: raise TypeError('__props__ is only valid when passed in combination with a valid",
"\"\"\" return pulumi.get(self, \"cidr_blocks\") @cidr_blocks.setter def cidr_blocks(self, value: Optional[pulumi.Input[Sequence[pulumi.Input[str]]]]): pulumi.set(self, \"cidr_blocks\", value) @property",
":param VPCArgs args: The arguments to use to populate this resource's properties. :param",
"create_time: Optional[pulumi.Input[str]] = None, name: Optional[pulumi.Input[str]] = None, network_infos: Optional[pulumi.Input[Sequence[pulumi.Input[pulumi.InputType['VPCNetworkInfoArgs']]]]] = None, remark:",
"VPC(pulumi.CustomResource): @overload def __init__(__self__, resource_name: str, opts: Optional[pulumi.ResourceOptions] = None, cidr_blocks: Optional[pulumi.Input[Sequence[pulumi.Input[str]]]] =",
"is a change made to VPC, formatted in RFC3339 time string. \"\"\" opts",
"Optional[pulumi.Input[str]] = None, tag: Optional[pulumi.Input[str]] = None, update_time: Optional[pulumi.Input[str]] = None) -> 'VPC':",
"and optional extra properties used to qualify the lookup. :param str resource_name: The",
"None: pulumi.set(__self__, \"remark\", remark) if tag is not None: pulumi.set(__self__, \"tag\", tag) if",
"opts: Options for the resource. \"\"\" ... def __init__(__self__, resource_name: str, *args, **kwargs):",
"= None, cidr_blocks: Optional[pulumi.Input[Sequence[pulumi.Input[str]]]] = None, create_time: Optional[pulumi.Input[str]] = None, name: Optional[pulumi.Input[str]] =",
"default tag will be assigned. (Default: `Default`). \"\"\" ... @overload def __init__(__self__, resource_name:",
"of the VPC. (Default: `\"\"`). :param pulumi.Input[str] tag: A tag assigned to VPC,",
"= None __props__.__dict__[\"network_infos\"] = None __props__.__dict__[\"update_time\"] = None super(VPC, __self__).__init__( 'ucloud:vpc/vPC:VPC', resource_name, __props__,",
"e.g. ```sh $ pulumi import ucloud:vpc/vPC:VPC example uvnet-abc123456 ``` :param str resource_name: The",
"doing! *** import warnings import pulumi import pulumi.runtime from typing import Any, Mapping,",
"a nested type which documented below. :param pulumi.Input[str] remark: The remarks of the",
"*, cidr_blocks: Optional[pulumi.Input[Sequence[pulumi.Input[str]]]] = None, create_time: Optional[pulumi.Input[str]] = None, name: Optional[pulumi.Input[str]] = None,",
"return pulumi.get(self, \"tag\") @tag.setter def tag(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, \"tag\", value) @property @pulumi.getter(name=\"updateTime\")",
"Get an existing VPC resource's state with the given name, id, and optional",
"create_time is not None: pulumi.set(__self__, \"create_time\", create_time) if name is not None: pulumi.set(__self__,",
"@pulumi.getter def tag(self) -> pulumi.Output[Optional[str]]: \"\"\" A tag assigned to VPC, which contains",
"Optional[pulumi.Input[Sequence[pulumi.Input[str]]]] = None, create_time: Optional[pulumi.Input[str]] = None, name: Optional[pulumi.Input[str]] = None, network_infos: Optional[pulumi.Input[Sequence[pulumi.Input['VPCNetworkInfoArgs']]]]",
"resource') __props__ = VPCArgs.__new__(VPCArgs) if cidr_blocks is None and not opts.urn: raise TypeError(\"Missing",
"Optional[pulumi.Input[Sequence[pulumi.Input['VPCNetworkInfoArgs']]]] = None, remark: Optional[pulumi.Input[str]] = None, tag: Optional[pulumi.Input[str]] = None, update_time: Optional[pulumi.Input[str]]",
"\"\"\" return pulumi.get(self, \"update_time\") @update_time.setter def update_time(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, \"update_time\", value) class",
"then default tag will be assigned. (Default: `Default`). \"\"\" ... @overload def __init__(__self__,",
"Example Usage ```python import pulumi import pulumi_ucloud as ucloud example = ucloud.vpc.VPC(\"example\", cidr_blocks=[\"192.168.0.0/16\"],",
"(Default: `Default`). \"\"\" return pulumi.get(self, \"tag\") @tag.setter def tag(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, \"tag\",",
"VPC, which contains at most 63 characters and only support Chinese, English, numbers,",
"pulumi.ResourceOptions, *args, **kwargs) if resource_args is not None: __self__._internal_init(resource_name, opts, **resource_args.__dict__) else: __self__._internal_init(resource_name,",
"when passed in combination with a valid opts.id to get an existing resource')",
"None, update_time: Optional[pulumi.Input[str]] = None): \"\"\" Input properties used for looking up and",
"str, args: VPCArgs, opts: Optional[pulumi.ResourceOptions] = None): \"\"\" Provides a VPC resource. >",
"__props__.__dict__[\"tag\"] = tag __props__.__dict__[\"create_time\"] = None __props__.__dict__[\"network_infos\"] = None __props__.__dict__[\"update_time\"] = None super(VPC,",
"@property @pulumi.getter(name=\"networkInfos\") def network_infos(self) -> pulumi.Output[Sequence['outputs.VPCNetworkInfo']]: \"\"\" It is a nested type which",
"@pulumi.getter(name=\"createTime\") def create_time(self) -> pulumi.Output[str]: \"\"\" The time of creation for VPC, formatted",
"value) @property @pulumi.getter(name=\"networkInfos\") def network_infos(self) -> Optional[pulumi.Input[Sequence[pulumi.Input['VPCNetworkInfoArgs']]]]: \"\"\" It is a nested type",
"__self__).__init__( 'ucloud:vpc/vPC:VPC', resource_name, __props__, opts) @staticmethod def get(resource_name: str, id: pulumi.Input[str], opts: Optional[pulumi.ResourceOptions]",
"Import VPC can be imported using the `id`, e.g. ```sh $ pulumi import",
"opts.urn: raise TypeError(\"Missing required property 'cidr_blocks'\") __props__.__dict__[\"cidr_blocks\"] = cidr_blocks __props__.__dict__[\"name\"] = name __props__.__dict__[\"remark\"]",
"None, name: Optional[pulumi.Input[str]] = None, network_infos: Optional[pulumi.Input[Sequence[pulumi.Input[pulumi.InputType['VPCNetworkInfoArgs']]]]] = None, remark: Optional[pulumi.Input[str]] = None,",
"The unique name of the resulting resource. :param pulumi.Input[str] id: The unique provider",
"resource_name: The unique name of the resulting resource. :param pulumi.Input[str] id: The unique",
"name: Optional[pulumi.Input[str]] = None, remark: Optional[pulumi.Input[str]] = None, tag: Optional[pulumi.Input[str]] = None): \"\"\"",
"VPC can be imported using the `id`, e.g. ```sh $ pulumi import ucloud:vpc/vPC:VPC",
"Optional[pulumi.Input[str]]): pulumi.set(self, \"tag\", value) @pulumi.input_type class _VPCState: def __init__(__self__, *, cidr_blocks: Optional[pulumi.Input[Sequence[pulumi.Input[str]]]] =",
"Union, overload from .. import _utilities from . import outputs from ._inputs import",
"change made to VPC, formatted in RFC3339 time string. \"\"\" if cidr_blocks is",
"None: pulumi.set(__self__, \"tag\", tag) if update_time is not None: pulumi.set(__self__, \"update_time\", update_time) @property",
"pulumi.set(__self__, \"tag\", tag) @property @pulumi.getter(name=\"cidrBlocks\") def cidr_blocks(self) -> pulumi.Input[Sequence[pulumi.Input[str]]]: \"\"\" The CIDR blocks",
"pulumi.set(__self__, \"name\", name) if remark is not None: pulumi.set(__self__, \"remark\", remark) if tag",
"RFC3339 time string. :param pulumi.Input[Sequence[pulumi.Input['VPCNetworkInfoArgs']]] network_infos: It is a nested type which documented",
"of VPC. \"\"\" return pulumi.get(self, \"cidr_blocks\") @cidr_blocks.setter def cidr_blocks(self, value: pulumi.Input[Sequence[pulumi.Input[str]]]): pulumi.set(self, \"cidr_blocks\",",
"for constructing a VPC resource. :param pulumi.Input[Sequence[pulumi.Input[str]]] cidr_blocks: The CIDR blocks of VPC.",
"pulumi.set(self, \"update_time\", value) class VPC(pulumi.CustomResource): @overload def __init__(__self__, resource_name: str, opts: Optional[pulumi.ResourceOptions] =",
"Optional[pulumi.Input[str]] = None, remark: Optional[pulumi.Input[str]] = None, tag: Optional[pulumi.Input[str]] = None, __props__=None): \"\"\"",
"Mapping, Optional, Sequence, Union, overload from .. import _utilities from . import outputs",
"Optional, Sequence, Union, overload from .. import _utilities from . import outputs from",
"return pulumi.get(self, \"tag\") @tag.setter def tag(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, \"tag\", value) @pulumi.input_type class",
"\"remark\", value) @property @pulumi.getter def tag(self) -> Optional[pulumi.Input[str]]: \"\"\" A tag assigned to",
"_VPCState: def __init__(__self__, *, cidr_blocks: Optional[pulumi.Input[Sequence[pulumi.Input[str]]]] = None, create_time: Optional[pulumi.Input[str]] = None, name:",
"is filled in, then default tag will be assigned. (Default: `Default`). \"\"\" ...",
"the VPC. (Default: `\"\"`). \"\"\" return pulumi.get(self, \"remark\") @remark.setter def remark(self, value: Optional[pulumi.Input[str]]):",
"name(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, \"name\", value) @property @pulumi.getter def remark(self) -> Optional[pulumi.Input[str]]: \"\"\"",
"def network_infos(self) -> Optional[pulumi.Input[Sequence[pulumi.Input['VPCNetworkInfoArgs']]]]: \"\"\" It is a nested type which documented below.",
"raise TypeError('__props__ is only valid when passed in combination with a valid opts.id",
"valid when passed in combination with a valid opts.id to get an existing",
"formatted in RFC3339 time string. :param pulumi.Input[Sequence[pulumi.Input[pulumi.InputType['VPCNetworkInfoArgs']]]] network_infos: It is a nested type",
"def name(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, \"name\", value) @property @pulumi.getter(name=\"networkInfos\") def network_infos(self) -> Optional[pulumi.Input[Sequence[pulumi.Input['VPCNetworkInfoArgs']]]]:",
"name is not None: pulumi.set(__self__, \"name\", name) if remark is not None: pulumi.set(__self__,",
"(Default: `Default`). \"\"\" ... @overload def __init__(__self__, resource_name: str, args: VPCArgs, opts: Optional[pulumi.ResourceOptions]",
"\"\"\" ... @overload def __init__(__self__, resource_name: str, args: VPCArgs, opts: Optional[pulumi.ResourceOptions] = None):",
"not None: __self__._internal_init(resource_name, opts, **resource_args.__dict__) else: __self__._internal_init(resource_name, *args, **kwargs) def _internal_init(__self__, resource_name: str,",
"def remark(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, \"remark\", value) @property @pulumi.getter def tag(self) -> Optional[pulumi.Input[str]]:",
"a valid opts.id to get an existing resource') __props__ = VPCArgs.__new__(VPCArgs) if cidr_blocks",
"The time whenever there is a change made to VPC, formatted in RFC3339",
"is only valid when passed in combination with a valid opts.id to get",
"`Default`). \"\"\" return pulumi.get(self, \"tag\") @property @pulumi.getter(name=\"updateTime\") def update_time(self) -> pulumi.Output[str]: \"\"\" The",
"= None, remark: Optional[pulumi.Input[str]] = None, tag: Optional[pulumi.Input[str]] = None): \"\"\" The set",
"\"update_time\", value) class VPC(pulumi.CustomResource): @overload def __init__(__self__, resource_name: str, opts: Optional[pulumi.ResourceOptions] = None,",
"@property @pulumi.getter def remark(self) -> Optional[pulumi.Input[str]]: \"\"\" The remarks of the VPC. (Default:",
"create_time(self) -> pulumi.Output[str]: \"\"\" The time of creation for VPC, formatted in RFC3339",
"def update_time(self) -> pulumi.Output[str]: \"\"\" The time whenever there is a change made",
"network_infos(self) -> pulumi.Output[Sequence['outputs.VPCNetworkInfo']]: \"\"\" It is a nested type which documented below. \"\"\"",
"create_time(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, \"create_time\", value) @property @pulumi.getter def name(self) -> Optional[pulumi.Input[str]]: return",
"value) @property @pulumi.getter def name(self) -> Optional[pulumi.Input[str]]: return pulumi.get(self, \"name\") @name.setter def name(self,",
"is a nested type which documented below. \"\"\" return pulumi.get(self, \"network_infos\") @network_infos.setter def",
"then default tag will be assigned. (Default: `Default`). :param pulumi.Input[str] update_time: The time",
"pulumi.get(self, \"update_time\") @update_time.setter def update_time(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, \"update_time\", value) class VPC(pulumi.CustomResource): @overload",
"Optional[pulumi.Input[str]] = None, tag: Optional[pulumi.Input[str]] = None, update_time: Optional[pulumi.Input[str]] = None): \"\"\" Input",
"the resource. :param VPCArgs args: The arguments to use to populate this resource's",
"a change made to VPC, formatted in RFC3339 time string. \"\"\" opts =",
"\"\"\" return pulumi.get(self, \"tag\") @property @pulumi.getter(name=\"updateTime\") def update_time(self) -> pulumi.Output[str]: \"\"\" The time",
"not None: pulumi.set(__self__, \"remark\", remark) if tag is not None: pulumi.set(__self__, \"tag\", tag)",
"typing import Any, Mapping, Optional, Sequence, Union, overload from .. import _utilities from",
"cidr_blocks(self) -> pulumi.Input[Sequence[pulumi.Input[str]]]: \"\"\" The CIDR blocks of VPC. \"\"\" return pulumi.get(self, \"cidr_blocks\")",
"of VPC. :param pulumi.Input[str] create_time: The time of creation for VPC, formatted in",
":param pulumi.ResourceOptions opts: Options for the resource. :param pulumi.Input[Sequence[pulumi.Input[str]]] cidr_blocks: The CIDR blocks",
"*** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool.",
"is not None: pulumi.set(__self__, \"tag\", tag) @property @pulumi.getter(name=\"cidrBlocks\") def cidr_blocks(self) -> pulumi.Input[Sequence[pulumi.Input[str]]]: \"\"\"",
"def tag(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, \"tag\", value) @pulumi.input_type class _VPCState: def __init__(__self__, *,",
"not None: pulumi.set(__self__, \"name\", name) if network_infos is not None: pulumi.set(__self__, \"network_infos\", network_infos)",
"of creation for VPC, formatted in RFC3339 time string. \"\"\" return pulumi.get(self, \"create_time\")",
"Optional[pulumi.ResourceOptions] = None, cidr_blocks: Optional[pulumi.Input[Sequence[pulumi.Input[str]]]] = None, create_time: Optional[pulumi.Input[str]] = None, name: Optional[pulumi.Input[str]]",
"is a nested type which documented below. \"\"\" return pulumi.get(self, \"network_infos\") @property @pulumi.getter",
"VPC. :param pulumi.Input[str] create_time: The time of creation for VPC, formatted in RFC3339",
"import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence,",
"@property @pulumi.getter def tag(self) -> Optional[pulumi.Input[str]]: \"\"\" A tag assigned to VPC, which",
"*args, **kwargs): resource_args, opts = _utilities.get_resource_args_opts(VPCArgs, pulumi.ResourceOptions, *args, **kwargs) if resource_args is not",
"pulumi.set(self, \"remark\", value) @property @pulumi.getter def tag(self) -> Optional[pulumi.Input[str]]: \"\"\" A tag assigned",
"required property 'cidr_blocks'\") __props__.__dict__[\"cidr_blocks\"] = cidr_blocks __props__.__dict__[\"name\"] = name __props__.__dict__[\"remark\"] = remark __props__.__dict__[\"tag\"]",
"\"\"\" A tag assigned to VPC, which contains at most 63 characters and",
"value: Optional[pulumi.Input[Sequence[pulumi.Input['VPCNetworkInfoArgs']]]]): pulumi.set(self, \"network_infos\", value) @property @pulumi.getter def remark(self) -> Optional[pulumi.Input[str]]: \"\"\" The",
"by the Pulumi Terraform Bridge (tfgen) Tool. *** # *** Do not edit",
"Optional[pulumi.Input[Sequence[pulumi.Input[pulumi.InputType['VPCNetworkInfoArgs']]]]] = None, remark: Optional[pulumi.Input[str]] = None, tag: Optional[pulumi.Input[str]] = None, update_time: Optional[pulumi.Input[str]]",
"cidr_blocks(self, value: pulumi.Input[Sequence[pulumi.Input[str]]]): pulumi.set(self, \"cidr_blocks\", value) @property @pulumi.getter def name(self) -> Optional[pulumi.Input[str]]: return",
"Optional[pulumi.Input[str]] = None, tag: Optional[pulumi.Input[str]] = None, __props__=None): if opts is None: opts",
"def __init__(__self__, *, cidr_blocks: Optional[pulumi.Input[Sequence[pulumi.Input[str]]]] = None, create_time: Optional[pulumi.Input[str]] = None, name: Optional[pulumi.Input[str]]",
"def create_time(self) -> pulumi.Output[str]: \"\"\" The time of creation for VPC, formatted in",
"name(self) -> Optional[pulumi.Input[str]]: return pulumi.get(self, \"name\") @name.setter def name(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, \"name\",",
"__props__=None): if opts is None: opts = pulumi.ResourceOptions() if not isinstance(opts, pulumi.ResourceOptions): raise",
"remark) if tag is not None: pulumi.set(__self__, \"tag\", tag) if update_time is not",
"pulumi.set(__self__, \"network_infos\", network_infos) if remark is not None: pulumi.set(__self__, \"remark\", remark) if tag",
"pulumi.get(self, \"network_infos\") @network_infos.setter def network_infos(self, value: Optional[pulumi.Input[Sequence[pulumi.Input['VPCNetworkInfoArgs']]]]): pulumi.set(self, \"network_infos\", value) @property @pulumi.getter def",
"def tag(self) -> Optional[pulumi.Input[str]]: \"\"\" A tag assigned to VPC, which contains at",
"the resource to lookup. :param pulumi.ResourceOptions opts: Options for the resource. :param pulumi.Input[Sequence[pulumi.Input[str]]]",
"example uvnet-abc123456 ``` :param str resource_name: The name of the resource. :param pulumi.ResourceOptions",
"_utilities.get_version() if opts.id is None: if __props__ is not None: raise TypeError('__props__ is",
"warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union,",
"qualify the lookup. :param str resource_name: The unique name of the resulting resource.",
"def name(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, \"name\", value) @property @pulumi.getter def remark(self) -> Optional[pulumi.Input[str]]:",
"-> pulumi.Output[Optional[str]]: \"\"\" A tag assigned to VPC, which contains at most 63",
"-> pulumi.Output[str]: return pulumi.get(self, \"name\") @property @pulumi.getter(name=\"networkInfos\") def network_infos(self) -> pulumi.Output[Sequence['outputs.VPCNetworkInfo']]: \"\"\" It",
"if tag is not None: pulumi.set(__self__, \"tag\", tag) if update_time is not None:",
"a VPC resource. :param pulumi.Input[Sequence[pulumi.Input[str]]] cidr_blocks: The CIDR blocks of VPC. :param pulumi.Input[str]",
"\"\"\" The time of creation for VPC, formatted in RFC3339 time string. \"\"\"",
"update_time) @property @pulumi.getter(name=\"cidrBlocks\") def cidr_blocks(self) -> Optional[pulumi.Input[Sequence[pulumi.Input[str]]]]: \"\"\" The CIDR blocks of VPC.",
"VPCArgs: def __init__(__self__, *, cidr_blocks: pulumi.Input[Sequence[pulumi.Input[str]]], name: Optional[pulumi.Input[str]] = None, remark: Optional[pulumi.Input[str]] =",
"'.'. If it is not filled in or a empty string is filled",
"(Default: `\"\"`). \"\"\" return pulumi.get(self, \"remark\") @remark.setter def remark(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, \"remark\",",
"nested type which documented below. :param pulumi.Input[str] remark: The remarks of the VPC.",
"__self__._internal_init(resource_name, opts, **resource_args.__dict__) else: __self__._internal_init(resource_name, *args, **kwargs) def _internal_init(__self__, resource_name: str, opts: Optional[pulumi.ResourceOptions]",
"not None: raise TypeError('__props__ is only valid when passed in combination with a",
"None __props__.__dict__[\"network_infos\"] = None __props__.__dict__[\"update_time\"] = None super(VPC, __self__).__init__( 'ucloud:vpc/vPC:VPC', resource_name, __props__, opts)",
"Pulumi Terraform Bridge (tfgen) Tool. *** # *** Do not edit by hand",
"remark is not None: pulumi.set(__self__, \"remark\", remark) if tag is not None: pulumi.set(__self__,",
"\"\"\" Get an existing VPC resource's state with the given name, id, and",
"value: Optional[pulumi.Input[str]]): pulumi.set(self, \"tag\", value) @property @pulumi.getter(name=\"updateTime\") def update_time(self) -> Optional[pulumi.Input[str]]: \"\"\" The",
"string. \"\"\" return pulumi.get(self, \"create_time\") @create_time.setter def create_time(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, \"create_time\", value)",
"be assigned. (Default: `Default`). \"\"\" ... @overload def __init__(__self__, resource_name: str, args: VPCArgs,",
"name) if network_infos is not None: pulumi.set(__self__, \"network_infos\", network_infos) if remark is not",
"It is a nested type which documented below. \"\"\" return pulumi.get(self, \"network_infos\") @network_infos.setter",
"a VPC resource. > **Note** The network segment can only be created or",
"\"network_infos\", network_infos) if remark is not None: pulumi.set(__self__, \"remark\", remark) if tag is",
"pulumi.Input[str], opts: Optional[pulumi.ResourceOptions] = None, cidr_blocks: Optional[pulumi.Input[Sequence[pulumi.Input[str]]]] = None, create_time: Optional[pulumi.Input[str]] = None,",
"as ucloud example = ucloud.vpc.VPC(\"example\", cidr_blocks=[\"192.168.0.0/16\"], tag=\"tf-example\") ``` ## Import VPC can be",
"\"\"\" return pulumi.get(self, \"network_infos\") @property @pulumi.getter def remark(self) -> pulumi.Output[str]: \"\"\" The remarks",
"of VPC. :param pulumi.Input[str] remark: The remarks of the VPC. (Default: `\"\"`). :param",
"= None, tag: Optional[pulumi.Input[str]] = None): \"\"\" The set of arguments for constructing",
"pulumi.Input[str] remark: The remarks of the VPC. (Default: `\"\"`). :param pulumi.Input[str] tag: A",
"not None: pulumi.set(__self__, \"tag\", tag) @property @pulumi.getter(name=\"cidrBlocks\") def cidr_blocks(self) -> pulumi.Input[Sequence[pulumi.Input[str]]]: \"\"\" The",
"properties. :param pulumi.ResourceOptions opts: Options for the resource. \"\"\" ... def __init__(__self__, resource_name:",
"type which documented below. \"\"\" return pulumi.get(self, \"network_infos\") @property @pulumi.getter def remark(self) ->",
"def cidr_blocks(self, value: pulumi.Input[Sequence[pulumi.Input[str]]]): pulumi.set(self, \"cidr_blocks\", value) @property @pulumi.getter def name(self) -> Optional[pulumi.Input[str]]:",
"blocks of VPC. :param pulumi.Input[str] create_time: The time of creation for VPC, formatted",
"# coding=utf-8 # *** WARNING: this file was generated by the Pulumi Terraform",
"def network_infos(self, value: Optional[pulumi.Input[Sequence[pulumi.Input['VPCNetworkInfoArgs']]]]): pulumi.set(self, \"network_infos\", value) @property @pulumi.getter def remark(self) -> Optional[pulumi.Input[str]]:",
"... @overload def __init__(__self__, resource_name: str, args: VPCArgs, opts: Optional[pulumi.ResourceOptions] = None): \"\"\"",
"\"\"\" return pulumi.get(self, \"tag\") @tag.setter def tag(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, \"tag\", value) @property",
"None __props__.__dict__[\"update_time\"] = None super(VPC, __self__).__init__( 'ucloud:vpc/vPC:VPC', resource_name, __props__, opts) @staticmethod def get(resource_name:",
"return VPC(resource_name, opts=opts, __props__=__props__) @property @pulumi.getter(name=\"cidrBlocks\") def cidr_blocks(self) -> pulumi.Output[Sequence[str]]: \"\"\" The CIDR",
"RFC3339 time string. \"\"\" opts = pulumi.ResourceOptions.merge(opts, pulumi.ResourceOptions(id=id)) __props__ = _VPCState.__new__(_VPCState) __props__.__dict__[\"cidr_blocks\"] =",
"`\"\"`). \"\"\" return pulumi.get(self, \"remark\") @property @pulumi.getter def tag(self) -> pulumi.Output[Optional[str]]: \"\"\" A",
"be assigned. (Default: `Default`). \"\"\" return pulumi.get(self, \"tag\") @property @pulumi.getter(name=\"updateTime\") def update_time(self) ->",
"VPCArgs args: The arguments to use to populate this resource's properties. :param pulumi.ResourceOptions",
"blocks of VPC. \"\"\" return pulumi.get(self, \"cidr_blocks\") @property @pulumi.getter(name=\"createTime\") def create_time(self) -> pulumi.Output[str]:",
"```sh $ pulumi import ucloud:vpc/vPC:VPC example uvnet-abc123456 ``` :param str resource_name: The name",
"certain you know what you are doing! *** import warnings import pulumi import",
"\"\"\" The set of arguments for constructing a VPC resource. :param pulumi.Input[Sequence[pulumi.Input[str]]] cidr_blocks:",
"with the given name, id, and optional extra properties used to qualify the",
"Optional[pulumi.Input[str]]: \"\"\" The remarks of the VPC. (Default: `\"\"`). \"\"\" return pulumi.get(self, \"remark\")",
"value: Optional[pulumi.Input[str]]): pulumi.set(self, \"remark\", value) @property @pulumi.getter def tag(self) -> Optional[pulumi.Input[str]]: \"\"\" A",
"default tag will be assigned. (Default: `Default`). \"\"\" return pulumi.get(self, \"tag\") @property @pulumi.getter(name=\"updateTime\")",
":param str resource_name: The name of the resource. :param VPCArgs args: The arguments",
"import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union, overload from ..",
"cidr_blocks) if name is not None: pulumi.set(__self__, \"name\", name) if remark is not",
"pulumi.set(self, \"name\", value) @property @pulumi.getter(name=\"networkInfos\") def network_infos(self) -> Optional[pulumi.Input[Sequence[pulumi.Input['VPCNetworkInfoArgs']]]]: \"\"\" It is a",
"tag will be assigned. (Default: `Default`). \"\"\" pulumi.set(__self__, \"cidr_blocks\", cidr_blocks) if name is",
"__props__ = _VPCState.__new__(_VPCState) __props__.__dict__[\"cidr_blocks\"] = cidr_blocks __props__.__dict__[\"create_time\"] = create_time __props__.__dict__[\"name\"] = name __props__.__dict__[\"network_infos\"]",
"VPC, formatted in RFC3339 time string. \"\"\" if cidr_blocks is not None: pulumi.set(__self__,",
"be assigned. (Default: `Default`). \"\"\" return pulumi.get(self, \"tag\") @tag.setter def tag(self, value: Optional[pulumi.Input[str]]):",
"the resource. :param pulumi.ResourceOptions opts: Options for the resource. :param pulumi.Input[Sequence[pulumi.Input[str]]] cidr_blocks: The",
"creation for VPC, formatted in RFC3339 time string. :param pulumi.Input[Sequence[pulumi.Input[pulumi.InputType['VPCNetworkInfoArgs']]]] network_infos: It is",
"__props__.__dict__[\"name\"] = name __props__.__dict__[\"network_infos\"] = network_infos __props__.__dict__[\"remark\"] = remark __props__.__dict__[\"tag\"] = tag __props__.__dict__[\"update_time\"]",
"is filled in, then default tag will be assigned. (Default: `Default`). :param pulumi.Input[str]",
"VPC, formatted in RFC3339 time string. \"\"\" opts = pulumi.ResourceOptions.merge(opts, pulumi.ResourceOptions(id=id)) __props__ =",
"pulumi.set(self, \"cidr_blocks\", value) @property @pulumi.getter(name=\"createTime\") def create_time(self) -> Optional[pulumi.Input[str]]: \"\"\" The time of",
"'-', '_', and '.'. If it is not filled in or a empty",
"pulumi.Output[Sequence['outputs.VPCNetworkInfo']]: \"\"\" It is a nested type which documented below. \"\"\" return pulumi.get(self,",
"._inputs import * __all__ = ['VPCArgs', 'VPC'] @pulumi.input_type class VPCArgs: def __init__(__self__, *,",
"formatted in RFC3339 time string. \"\"\" if cidr_blocks is not None: pulumi.set(__self__, \"cidr_blocks\",",
"str resource_name: The name of the resource. :param pulumi.ResourceOptions opts: Options for the",
"RFC3339 time string. \"\"\" return pulumi.get(self, \"update_time\") @update_time.setter def update_time(self, value: Optional[pulumi.Input[str]]): pulumi.set(self,",
"name) if remark is not None: pulumi.set(__self__, \"remark\", remark) if tag is not",
"= _utilities.get_version() if opts.id is None: if __props__ is not None: raise TypeError('__props__",
"@pulumi.getter(name=\"networkInfos\") def network_infos(self) -> pulumi.Output[Sequence['outputs.VPCNetworkInfo']]: \"\"\" It is a nested type which documented",
"same time. ## Example Usage ```python import pulumi import pulumi_ucloud as ucloud example",
"cidr_blocks(self, value: Optional[pulumi.Input[Sequence[pulumi.Input[str]]]]): pulumi.set(self, \"cidr_blocks\", value) @property @pulumi.getter(name=\"createTime\") def create_time(self) -> Optional[pulumi.Input[str]]: \"\"\"",
":param pulumi.Input[Sequence[pulumi.Input[str]]] cidr_blocks: The CIDR blocks of VPC. :param pulumi.Input[str] remark: The remarks",
"for VPC, formatted in RFC3339 time string. :param pulumi.Input[Sequence[pulumi.Input[pulumi.InputType['VPCNetworkInfoArgs']]]] network_infos: It is a",
"= pulumi.ResourceOptions() if not isinstance(opts, pulumi.ResourceOptions): raise TypeError('Expected resource options to be a",
"is None: if __props__ is not None: raise TypeError('__props__ is only valid when",
"pulumi.Input[Sequence[pulumi.Input['VPCNetworkInfoArgs']]] network_infos: It is a nested type which documented below. :param pulumi.Input[str] remark:",
"= remark __props__.__dict__[\"tag\"] = tag __props__.__dict__[\"create_time\"] = None __props__.__dict__[\"network_infos\"] = None __props__.__dict__[\"update_time\"] =",
"= None): \"\"\" Input properties used for looking up and filtering VPC resources.",
"provider ID of the resource to lookup. :param pulumi.ResourceOptions opts: Options for the",
"None, cidr_blocks: Optional[pulumi.Input[Sequence[pulumi.Input[str]]]] = None, create_time: Optional[pulumi.Input[str]] = None, name: Optional[pulumi.Input[str]] = None,",
"pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union, overload from",
"\"\"\" The CIDR blocks of VPC. \"\"\" return pulumi.get(self, \"cidr_blocks\") @property @pulumi.getter(name=\"createTime\") def",
"support Chinese, English, numbers, '-', '_', and '.'. If it is not filled",
"cidr_blocks(self) -> pulumi.Output[Sequence[str]]: \"\"\" The CIDR blocks of VPC. \"\"\" return pulumi.get(self, \"cidr_blocks\")",
"string. \"\"\" opts = pulumi.ResourceOptions.merge(opts, pulumi.ResourceOptions(id=id)) __props__ = _VPCState.__new__(_VPCState) __props__.__dict__[\"cidr_blocks\"] = cidr_blocks __props__.__dict__[\"create_time\"]",
"\"\"\" opts = pulumi.ResourceOptions.merge(opts, pulumi.ResourceOptions(id=id)) __props__ = _VPCState.__new__(_VPCState) __props__.__dict__[\"cidr_blocks\"] = cidr_blocks __props__.__dict__[\"create_time\"] =",
"cidr_blocks: Optional[pulumi.Input[Sequence[pulumi.Input[str]]]] = None, create_time: Optional[pulumi.Input[str]] = None, name: Optional[pulumi.Input[str]] = None, network_infos:",
"a empty string is filled in, then default tag will be assigned. (Default:",
"below. \"\"\" return pulumi.get(self, \"network_infos\") @network_infos.setter def network_infos(self, value: Optional[pulumi.Input[Sequence[pulumi.Input['VPCNetworkInfoArgs']]]]): pulumi.set(self, \"network_infos\", value)",
"'ucloud:vpc/vPC:VPC', resource_name, __props__, opts) @staticmethod def get(resource_name: str, id: pulumi.Input[str], opts: Optional[pulumi.ResourceOptions] =",
"``` :param str resource_name: The name of the resource. :param VPCArgs args: The",
"-> 'VPC': \"\"\" Get an existing VPC resource's state with the given name,",
"pulumi.Output[str]: \"\"\" The time of creation for VPC, formatted in RFC3339 time string.",
"created or deleted, can not perform both of them at the same time.",
"resource. :param pulumi.ResourceOptions opts: Options for the resource. :param pulumi.Input[Sequence[pulumi.Input[str]]] cidr_blocks: The CIDR",
"be a ResourceOptions instance') if opts.version is None: opts.version = _utilities.get_version() if opts.id",
"not opts.urn: raise TypeError(\"Missing required property 'cidr_blocks'\") __props__.__dict__[\"cidr_blocks\"] = cidr_blocks __props__.__dict__[\"name\"] = name",
"in combination with a valid opts.id to get an existing resource') __props__ =",
"__props__.__dict__[\"name\"] = name __props__.__dict__[\"remark\"] = remark __props__.__dict__[\"tag\"] = tag __props__.__dict__[\"create_time\"] = None __props__.__dict__[\"network_infos\"]",
"arguments to use to populate this resource's properties. :param pulumi.ResourceOptions opts: Options for",
"default tag will be assigned. (Default: `Default`). \"\"\" pulumi.set(__self__, \"cidr_blocks\", cidr_blocks) if name",
"tag __props__.__dict__[\"create_time\"] = None __props__.__dict__[\"network_infos\"] = None __props__.__dict__[\"update_time\"] = None super(VPC, __self__).__init__( 'ucloud:vpc/vPC:VPC',",
"outputs from ._inputs import * __all__ = ['VPCArgs', 'VPC'] @pulumi.input_type class VPCArgs: def",
"id, and optional extra properties used to qualify the lookup. :param str resource_name:",
"@cidr_blocks.setter def cidr_blocks(self, value: pulumi.Input[Sequence[pulumi.Input[str]]]): pulumi.set(self, \"cidr_blocks\", value) @property @pulumi.getter def name(self) ->",
"VPC. \"\"\" return pulumi.get(self, \"cidr_blocks\") @cidr_blocks.setter def cidr_blocks(self, value: Optional[pulumi.Input[Sequence[pulumi.Input[str]]]]): pulumi.set(self, \"cidr_blocks\", value)",
"* __all__ = ['VPCArgs', 'VPC'] @pulumi.input_type class VPCArgs: def __init__(__self__, *, cidr_blocks: pulumi.Input[Sequence[pulumi.Input[str]]],",
"pulumi.ResourceOptions() if not isinstance(opts, pulumi.ResourceOptions): raise TypeError('Expected resource options to be a ResourceOptions",
"value: Optional[pulumi.Input[str]]): pulumi.set(self, \"name\", value) @property @pulumi.getter(name=\"networkInfos\") def network_infos(self) -> Optional[pulumi.Input[Sequence[pulumi.Input['VPCNetworkInfoArgs']]]]: \"\"\" It",
"will be assigned. (Default: `Default`). :param pulumi.Input[str] update_time: The time whenever there is",
"@pulumi.input_type class _VPCState: def __init__(__self__, *, cidr_blocks: Optional[pulumi.Input[Sequence[pulumi.Input[str]]]] = None, create_time: Optional[pulumi.Input[str]] =",
"in RFC3339 time string. :param pulumi.Input[Sequence[pulumi.Input['VPCNetworkInfoArgs']]] network_infos: It is a nested type which",
"The time of creation for VPC, formatted in RFC3339 time string. :param pulumi.Input[Sequence[pulumi.Input[pulumi.InputType['VPCNetworkInfoArgs']]]]",
"formatted in RFC3339 time string. \"\"\" return pulumi.get(self, \"create_time\") @property @pulumi.getter def name(self)",
"only valid when passed in combination with a valid opts.id to get an",
"assigned. (Default: `Default`). :param pulumi.Input[str] update_time: The time whenever there is a change",
"to populate this resource's properties. :param pulumi.ResourceOptions opts: Options for the resource. \"\"\"",
"str, opts: Optional[pulumi.ResourceOptions] = None, cidr_blocks: Optional[pulumi.Input[Sequence[pulumi.Input[str]]]] = None, name: Optional[pulumi.Input[str]] = None,",
"valid opts.id to get an existing resource') __props__ = VPCArgs.__new__(VPCArgs) if cidr_blocks is",
"know what you are doing! *** import warnings import pulumi import pulumi.runtime from",
"change made to VPC, formatted in RFC3339 time string. \"\"\" return pulumi.get(self, \"update_time\")",
"The unique provider ID of the resource to lookup. :param pulumi.ResourceOptions opts: Options",
"Any, Mapping, Optional, Sequence, Union, overload from .. import _utilities from . import",
"= None, remark: Optional[pulumi.Input[str]] = None, tag: Optional[pulumi.Input[str]] = None, __props__=None): if opts",
"@property @pulumi.getter(name=\"createTime\") def create_time(self) -> pulumi.Output[str]: \"\"\" The time of creation for VPC,",
"None, tag: Optional[pulumi.Input[str]] = None, __props__=None): if opts is None: opts = pulumi.ResourceOptions()",
"\"remark\", remark) if tag is not None: pulumi.set(__self__, \"tag\", tag) @property @pulumi.getter(name=\"cidrBlocks\") def",
"resource. :param pulumi.Input[Sequence[pulumi.Input[str]]] cidr_blocks: The CIDR blocks of VPC. :param pulumi.Input[str] create_time: The",
"def create_time(self) -> Optional[pulumi.Input[str]]: \"\"\" The time of creation for VPC, formatted in",
"Optional[pulumi.Input[str]] = None, tag: Optional[pulumi.Input[str]] = None): \"\"\" The set of arguments for",
"__props__.__dict__[\"remark\"] = remark __props__.__dict__[\"tag\"] = tag __props__.__dict__[\"create_time\"] = None __props__.__dict__[\"network_infos\"] = None __props__.__dict__[\"update_time\"]",
"whenever there is a change made to VPC, formatted in RFC3339 time string.",
"pulumi.get(self, \"cidr_blocks\") @cidr_blocks.setter def cidr_blocks(self, value: pulumi.Input[Sequence[pulumi.Input[str]]]): pulumi.set(self, \"cidr_blocks\", value) @property @pulumi.getter def",
"Optional[pulumi.Input[str]]: \"\"\" The time of creation for VPC, formatted in RFC3339 time string.",
"properties used for looking up and filtering VPC resources. :param pulumi.Input[Sequence[pulumi.Input[str]]] cidr_blocks: The",
"string is filled in, then default tag will be assigned. (Default: `Default`). :param",
"most 63 characters and only support Chinese, English, numbers, '-', '_', and '.'.",
"tag(self) -> Optional[pulumi.Input[str]]: \"\"\" A tag assigned to VPC, which contains at most",
"= update_time return VPC(resource_name, opts=opts, __props__=__props__) @property @pulumi.getter(name=\"cidrBlocks\") def cidr_blocks(self) -> pulumi.Output[Sequence[str]]: \"\"\"",
"contains at most 63 characters and only support Chinese, English, numbers, '-', '_',",
"__props__, opts) @staticmethod def get(resource_name: str, id: pulumi.Input[str], opts: Optional[pulumi.ResourceOptions] = None, cidr_blocks:",
"value: Optional[pulumi.Input[str]]): pulumi.set(self, \"update_time\", value) class VPC(pulumi.CustomResource): @overload def __init__(__self__, resource_name: str, opts:",
"The arguments to use to populate this resource's properties. :param pulumi.ResourceOptions opts: Options",
"\"update_time\") @update_time.setter def update_time(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, \"update_time\", value) class VPC(pulumi.CustomResource): @overload def",
"= tag __props__.__dict__[\"update_time\"] = update_time return VPC(resource_name, opts=opts, __props__=__props__) @property @pulumi.getter(name=\"cidrBlocks\") def cidr_blocks(self)",
"remark: The remarks of the VPC. (Default: `\"\"`). :param pulumi.Input[str] tag: A tag",
"return pulumi.get(self, \"name\") @name.setter def name(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, \"name\", value) @property @pulumi.getter(name=\"networkInfos\")",
"@property @pulumi.getter def remark(self) -> pulumi.Output[str]: \"\"\" The remarks of the VPC. (Default:",
"@property @pulumi.getter def tag(self) -> pulumi.Output[Optional[str]]: \"\"\" A tag assigned to VPC, which",
"None, update_time: Optional[pulumi.Input[str]] = None) -> 'VPC': \"\"\" Get an existing VPC resource's",
"\"name\", name) if network_infos is not None: pulumi.set(__self__, \"network_infos\", network_infos) if remark is",
"which documented below. \"\"\" return pulumi.get(self, \"network_infos\") @property @pulumi.getter def remark(self) -> pulumi.Output[str]:",
"if opts.version is None: opts.version = _utilities.get_version() if opts.id is None: if __props__",
"If it is not filled in or a empty string is filled in,",
"@pulumi.getter def remark(self) -> Optional[pulumi.Input[str]]: \"\"\" The remarks of the VPC. (Default: `\"\"`).",
"time string. :param pulumi.Input[Sequence[pulumi.Input[pulumi.InputType['VPCNetworkInfoArgs']]]] network_infos: It is a nested type which documented below.",
"import _utilities from . import outputs from ._inputs import * __all__ = ['VPCArgs',",
"None): \"\"\" Input properties used for looking up and filtering VPC resources. :param",
"\"remark\", remark) if tag is not None: pulumi.set(__self__, \"tag\", tag) if update_time is",
"pulumi.get(self, \"tag\") @tag.setter def tag(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, \"tag\", value) @pulumi.input_type class _VPCState:",
"not None: pulumi.set(__self__, \"cidr_blocks\", cidr_blocks) if create_time is not None: pulumi.set(__self__, \"create_time\", create_time)",
"\"create_time\") @property @pulumi.getter def name(self) -> pulumi.Output[str]: return pulumi.get(self, \"name\") @property @pulumi.getter(name=\"networkInfos\") def",
"value) @property @pulumi.getter def tag(self) -> Optional[pulumi.Input[str]]: \"\"\" A tag assigned to VPC,",
"remark: Optional[pulumi.Input[str]] = None, tag: Optional[pulumi.Input[str]] = None, __props__=None): if opts is None:",
"None, tag: Optional[pulumi.Input[str]] = None): \"\"\" The set of arguments for constructing a",
"a ResourceOptions instance') if opts.version is None: opts.version = _utilities.get_version() if opts.id is",
"for VPC, formatted in RFC3339 time string. :param pulumi.Input[Sequence[pulumi.Input['VPCNetworkInfoArgs']]] network_infos: It is a",
"None, remark: Optional[pulumi.Input[str]] = None, tag: Optional[pulumi.Input[str]] = None, update_time: Optional[pulumi.Input[str]] = None):",
"\"\"\" The time whenever there is a change made to VPC, formatted in",
"resource_name: str, opts: Optional[pulumi.ResourceOptions] = None, cidr_blocks: Optional[pulumi.Input[Sequence[pulumi.Input[str]]]] = None, name: Optional[pulumi.Input[str]] =",
"\"network_infos\") @property @pulumi.getter def remark(self) -> pulumi.Output[str]: \"\"\" The remarks of the VPC.",
"pulumi.get(self, \"tag\") @property @pulumi.getter(name=\"updateTime\") def update_time(self) -> pulumi.Output[str]: \"\"\" The time whenever there",
"time of creation for VPC, formatted in RFC3339 time string. :param pulumi.Input[Sequence[pulumi.Input[pulumi.InputType['VPCNetworkInfoArgs']]]] network_infos:",
"pulumi.Input[str] create_time: The time of creation for VPC, formatted in RFC3339 time string.",
"None: pulumi.set(__self__, \"name\", name) if network_infos is not None: pulumi.set(__self__, \"network_infos\", network_infos) if",
"creation for VPC, formatted in RFC3339 time string. \"\"\" return pulumi.get(self, \"create_time\") @create_time.setter",
"string. :param pulumi.Input[Sequence[pulumi.Input[pulumi.InputType['VPCNetworkInfoArgs']]]] network_infos: It is a nested type which documented below. :param",
"def cidr_blocks(self, value: Optional[pulumi.Input[Sequence[pulumi.Input[str]]]]): pulumi.set(self, \"cidr_blocks\", value) @property @pulumi.getter(name=\"createTime\") def create_time(self) -> Optional[pulumi.Input[str]]:",
"\"\"\" return pulumi.get(self, \"create_time\") @property @pulumi.getter def name(self) -> pulumi.Output[str]: return pulumi.get(self, \"name\")",
"__init__(__self__, resource_name: str, opts: Optional[pulumi.ResourceOptions] = None, cidr_blocks: Optional[pulumi.Input[Sequence[pulumi.Input[str]]]] = None, name: Optional[pulumi.Input[str]]",
"tag(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, \"tag\", value) @property @pulumi.getter(name=\"updateTime\") def update_time(self) -> Optional[pulumi.Input[str]]: \"\"\"",
"@property @pulumi.getter(name=\"cidrBlocks\") def cidr_blocks(self) -> pulumi.Output[Sequence[str]]: \"\"\" The CIDR blocks of VPC. \"\"\"",
"if opts is None: opts = pulumi.ResourceOptions() if not isinstance(opts, pulumi.ResourceOptions): raise TypeError('Expected",
"the resource. :param pulumi.Input[Sequence[pulumi.Input[str]]] cidr_blocks: The CIDR blocks of VPC. :param pulumi.Input[str] create_time:",
"import ucloud:vpc/vPC:VPC example uvnet-abc123456 ``` :param str resource_name: The name of the resource.",
"pulumi.ResourceOptions opts: Options for the resource. \"\"\" ... def __init__(__self__, resource_name: str, *args,",
"@staticmethod def get(resource_name: str, id: pulumi.Input[str], opts: Optional[pulumi.ResourceOptions] = None, cidr_blocks: Optional[pulumi.Input[Sequence[pulumi.Input[str]]]] =",
"remarks of the VPC. (Default: `\"\"`). \"\"\" return pulumi.get(self, \"remark\") @property @pulumi.getter def",
"string. \"\"\" return pulumi.get(self, \"update_time\") @update_time.setter def update_time(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, \"update_time\", value)",
"name: Optional[pulumi.Input[str]] = None, remark: Optional[pulumi.Input[str]] = None, tag: Optional[pulumi.Input[str]] = None, __props__=None):",
"if remark is not None: pulumi.set(__self__, \"remark\", remark) if tag is not None:",
"= cidr_blocks __props__.__dict__[\"name\"] = name __props__.__dict__[\"remark\"] = remark __props__.__dict__[\"tag\"] = tag __props__.__dict__[\"create_time\"] =",
"pulumi.get(self, \"name\") @name.setter def name(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, \"name\", value) @property @pulumi.getter(name=\"networkInfos\") def",
"Sequence, Union, overload from .. import _utilities from . import outputs from ._inputs",
"return pulumi.get(self, \"cidr_blocks\") @property @pulumi.getter(name=\"createTime\") def create_time(self) -> pulumi.Output[str]: \"\"\" The time of",
"pulumi.Input[Sequence[pulumi.Input[pulumi.InputType['VPCNetworkInfoArgs']]]] network_infos: It is a nested type which documented below. :param pulumi.Input[str] remark:",
"Do not edit by hand unless you're certain you know what you are",
"__init__(__self__, *, cidr_blocks: pulumi.Input[Sequence[pulumi.Input[str]]], name: Optional[pulumi.Input[str]] = None, remark: Optional[pulumi.Input[str]] = None, tag:",
"= tag __props__.__dict__[\"create_time\"] = None __props__.__dict__[\"network_infos\"] = None __props__.__dict__[\"update_time\"] = None super(VPC, __self__).__init__(",
"in or a empty string is filled in, then default tag will be",
"It is a nested type which documented below. :param pulumi.Input[str] remark: The remarks",
"blocks of VPC. :param pulumi.Input[str] remark: The remarks of the VPC. (Default: `\"\"`).",
"Optional[pulumi.Input[str]]): pulumi.set(self, \"remark\", value) @property @pulumi.getter def tag(self) -> Optional[pulumi.Input[str]]: \"\"\" A tag",
"= _VPCState.__new__(_VPCState) __props__.__dict__[\"cidr_blocks\"] = cidr_blocks __props__.__dict__[\"create_time\"] = create_time __props__.__dict__[\"name\"] = name __props__.__dict__[\"network_infos\"] =",
"= remark __props__.__dict__[\"tag\"] = tag __props__.__dict__[\"update_time\"] = update_time return VPC(resource_name, opts=opts, __props__=__props__) @property",
"The remarks of the VPC. (Default: `\"\"`). :param pulumi.Input[str] tag: A tag assigned",
"Optional[pulumi.Input[str]] = None, update_time: Optional[pulumi.Input[str]] = None): \"\"\" Input properties used for looking",
"are doing! *** import warnings import pulumi import pulumi.runtime from typing import Any,",
"The time of creation for VPC, formatted in RFC3339 time string. :param pulumi.Input[Sequence[pulumi.Input['VPCNetworkInfoArgs']]]",
"generated by the Pulumi Terraform Bridge (tfgen) Tool. *** # *** Do not",
"WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***",
"None and not opts.urn: raise TypeError(\"Missing required property 'cidr_blocks'\") __props__.__dict__[\"cidr_blocks\"] = cidr_blocks __props__.__dict__[\"name\"]",
"of arguments for constructing a VPC resource. :param pulumi.Input[Sequence[pulumi.Input[str]]] cidr_blocks: The CIDR blocks",
"pulumi.get(self, \"remark\") @remark.setter def remark(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, \"remark\", value) @property @pulumi.getter def",
"@property @pulumi.getter(name=\"networkInfos\") def network_infos(self) -> Optional[pulumi.Input[Sequence[pulumi.Input['VPCNetworkInfoArgs']]]]: \"\"\" It is a nested type which",
"using the `id`, e.g. ```sh $ pulumi import ucloud:vpc/vPC:VPC example uvnet-abc123456 ``` :param",
"def tag(self) -> pulumi.Output[Optional[str]]: \"\"\" A tag assigned to VPC, which contains at",
"a change made to VPC, formatted in RFC3339 time string. \"\"\" return pulumi.get(self,",
"= None, remark: Optional[pulumi.Input[str]] = None, tag: Optional[pulumi.Input[str]] = None, update_time: Optional[pulumi.Input[str]] =",
"None, tag: Optional[pulumi.Input[str]] = None, update_time: Optional[pulumi.Input[str]] = None) -> 'VPC': \"\"\" Get",
":param str resource_name: The unique name of the resulting resource. :param pulumi.Input[str] id:",
"None, network_infos: Optional[pulumi.Input[Sequence[pulumi.Input['VPCNetworkInfoArgs']]]] = None, remark: Optional[pulumi.Input[str]] = None, tag: Optional[pulumi.Input[str]] = None,",
"network segment can only be created or deleted, can not perform both of",
"then default tag will be assigned. (Default: `Default`). \"\"\" return pulumi.get(self, \"tag\") @tag.setter",
"ucloud:vpc/vPC:VPC example uvnet-abc123456 ``` :param str resource_name: The name of the resource. :param",
"network_infos) if remark is not None: pulumi.set(__self__, \"remark\", remark) if tag is not",
"= create_time __props__.__dict__[\"name\"] = name __props__.__dict__[\"network_infos\"] = network_infos __props__.__dict__[\"remark\"] = remark __props__.__dict__[\"tag\"] =",
"return pulumi.get(self, \"network_infos\") @property @pulumi.getter def remark(self) -> pulumi.Output[str]: \"\"\" The remarks of",
"**kwargs): resource_args, opts = _utilities.get_resource_args_opts(VPCArgs, pulumi.ResourceOptions, *args, **kwargs) if resource_args is not None:",
"English, numbers, '-', '_', and '.'. If it is not filled in or",
"... def __init__(__self__, resource_name: str, *args, **kwargs): resource_args, opts = _utilities.get_resource_args_opts(VPCArgs, pulumi.ResourceOptions, *args,",
"\"create_time\", value) @property @pulumi.getter def name(self) -> Optional[pulumi.Input[str]]: return pulumi.get(self, \"name\") @name.setter def",
"get(resource_name: str, id: pulumi.Input[str], opts: Optional[pulumi.ResourceOptions] = None, cidr_blocks: Optional[pulumi.Input[Sequence[pulumi.Input[str]]]] = None, create_time:",
"remark: Optional[pulumi.Input[str]] = None, tag: Optional[pulumi.Input[str]] = None, __props__=None): \"\"\" Provides a VPC",
"the VPC. (Default: `\"\"`). \"\"\" return pulumi.get(self, \"remark\") @property @pulumi.getter def tag(self) ->",
"-> pulumi.Output[str]: \"\"\" The time whenever there is a change made to VPC,",
"**resource_args.__dict__) else: __self__._internal_init(resource_name, *args, **kwargs) def _internal_init(__self__, resource_name: str, opts: Optional[pulumi.ResourceOptions] = None,",
"-> pulumi.Output[Sequence[str]]: \"\"\" The CIDR blocks of VPC. \"\"\" return pulumi.get(self, \"cidr_blocks\") @property",
"\"cidr_blocks\") @property @pulumi.getter(name=\"createTime\") def create_time(self) -> pulumi.Output[str]: \"\"\" The time of creation for",
"\"\"\" return pulumi.get(self, \"remark\") @remark.setter def remark(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, \"remark\", value) @property",
"characters and only support Chinese, English, numbers, '-', '_', and '.'. If it",
"in, then default tag will be assigned. (Default: `Default`). \"\"\" ... @overload def",
"resources. :param pulumi.Input[Sequence[pulumi.Input[str]]] cidr_blocks: The CIDR blocks of VPC. :param pulumi.Input[str] create_time: The",
"The name of the resource. :param pulumi.ResourceOptions opts: Options for the resource. :param",
"update_time: Optional[pulumi.Input[str]] = None) -> 'VPC': \"\"\" Get an existing VPC resource's state",
"__props__=__props__) @property @pulumi.getter(name=\"cidrBlocks\") def cidr_blocks(self) -> pulumi.Output[Sequence[str]]: \"\"\" The CIDR blocks of VPC.",
"= _utilities.get_resource_args_opts(VPCArgs, pulumi.ResourceOptions, *args, **kwargs) if resource_args is not None: __self__._internal_init(resource_name, opts, **resource_args.__dict__)",
"`id`, e.g. ```sh $ pulumi import ucloud:vpc/vPC:VPC example uvnet-abc123456 ``` :param str resource_name:",
"pulumi.Output[Optional[str]]: \"\"\" A tag assigned to VPC, which contains at most 63 characters",
"VPC resource. :param pulumi.Input[Sequence[pulumi.Input[str]]] cidr_blocks: The CIDR blocks of VPC. :param pulumi.Input[str] remark:",
":param pulumi.Input[str] remark: The remarks of the VPC. (Default: `\"\"`). :param pulumi.Input[str] tag:",
"A tag assigned to VPC, which contains at most 63 characters and only",
"tag assigned to VPC, which contains at most 63 characters and only support",
"The CIDR blocks of VPC. \"\"\" return pulumi.get(self, \"cidr_blocks\") @cidr_blocks.setter def cidr_blocks(self, value:",
"to lookup. :param pulumi.ResourceOptions opts: Options for the resource. :param pulumi.Input[Sequence[pulumi.Input[str]]] cidr_blocks: The",
"network_infos is not None: pulumi.set(__self__, \"network_infos\", network_infos) if remark is not None: pulumi.set(__self__,",
"None, tag: Optional[pulumi.Input[str]] = None, update_time: Optional[pulumi.Input[str]] = None): \"\"\" Input properties used",
"is not None: pulumi.set(__self__, \"network_infos\", network_infos) if remark is not None: pulumi.set(__self__, \"remark\",",
"opts, **resource_args.__dict__) else: __self__._internal_init(resource_name, *args, **kwargs) def _internal_init(__self__, resource_name: str, opts: Optional[pulumi.ResourceOptions] =",
"if update_time is not None: pulumi.set(__self__, \"update_time\", update_time) @property @pulumi.getter(name=\"cidrBlocks\") def cidr_blocks(self) ->",
"documented below. \"\"\" return pulumi.get(self, \"network_infos\") @property @pulumi.getter def remark(self) -> pulumi.Output[str]: \"\"\"",
"made to VPC, formatted in RFC3339 time string. \"\"\" return pulumi.get(self, \"update_time\") @update_time.setter",
"@tag.setter def tag(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, \"tag\", value) @pulumi.input_type class _VPCState: def __init__(__self__,",
"= None, remark: Optional[pulumi.Input[str]] = None, tag: Optional[pulumi.Input[str]] = None, __props__=None): \"\"\" Provides",
"tag(self) -> pulumi.Output[Optional[str]]: \"\"\" A tag assigned to VPC, which contains at most",
"Optional[pulumi.Input[str]] = None, remark: Optional[pulumi.Input[str]] = None, tag: Optional[pulumi.Input[str]] = None): \"\"\" The",
"remark: Optional[pulumi.Input[str]] = None, tag: Optional[pulumi.Input[str]] = None): \"\"\" The set of arguments",
"\"\"\" return pulumi.get(self, \"tag\") @tag.setter def tag(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, \"tag\", value) @pulumi.input_type",
"None: pulumi.set(__self__, \"create_time\", create_time) if name is not None: pulumi.set(__self__, \"name\", name) if",
"create_time: Optional[pulumi.Input[str]] = None, name: Optional[pulumi.Input[str]] = None, network_infos: Optional[pulumi.Input[Sequence[pulumi.Input['VPCNetworkInfoArgs']]]] = None, remark:",
"return pulumi.get(self, \"update_time\") @update_time.setter def update_time(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, \"update_time\", value) class VPC(pulumi.CustomResource):",
"overload from .. import _utilities from . import outputs from ._inputs import *",
"str, *args, **kwargs): resource_args, opts = _utilities.get_resource_args_opts(VPCArgs, pulumi.ResourceOptions, *args, **kwargs) if resource_args is",
"default tag will be assigned. (Default: `Default`). :param pulumi.Input[str] update_time: The time whenever",
"pulumi.Output[str]: \"\"\" The time whenever there is a change made to VPC, formatted",
"Optional[pulumi.Input[str]]): pulumi.set(self, \"name\", value) @property @pulumi.getter(name=\"networkInfos\") def network_infos(self) -> Optional[pulumi.Input[Sequence[pulumi.Input['VPCNetworkInfoArgs']]]]: \"\"\" It is",
"pulumi.set(self, \"tag\", value) @property @pulumi.getter(name=\"updateTime\") def update_time(self) -> Optional[pulumi.Input[str]]: \"\"\" The time whenever",
"is filled in, then default tag will be assigned. (Default: `Default`). \"\"\" return",
"`Default`). \"\"\" ... @overload def __init__(__self__, resource_name: str, args: VPCArgs, opts: Optional[pulumi.ResourceOptions] =",
"return pulumi.get(self, \"cidr_blocks\") @cidr_blocks.setter def cidr_blocks(self, value: pulumi.Input[Sequence[pulumi.Input[str]]]): pulumi.set(self, \"cidr_blocks\", value) @property @pulumi.getter",
"update_time(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, \"update_time\", value) class VPC(pulumi.CustomResource): @overload def __init__(__self__, resource_name: str,",
"-> Optional[pulumi.Input[str]]: return pulumi.get(self, \"name\") @name.setter def name(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, \"name\", value)",
"The CIDR blocks of VPC. :param pulumi.Input[str] remark: The remarks of the VPC.",
"Optional[pulumi.Input[str]]): pulumi.set(self, \"tag\", value) @property @pulumi.getter(name=\"updateTime\") def update_time(self) -> Optional[pulumi.Input[str]]: \"\"\" The time",
"Optional[pulumi.Input[str]] = None) -> 'VPC': \"\"\" Get an existing VPC resource's state with",
"*args, **kwargs) if resource_args is not None: __self__._internal_init(resource_name, opts, **resource_args.__dict__) else: __self__._internal_init(resource_name, *args,",
"VPC, formatted in RFC3339 time string. \"\"\" return pulumi.get(self, \"update_time\") @update_time.setter def update_time(self,",
"is not None: pulumi.set(__self__, \"remark\", remark) if tag is not None: pulumi.set(__self__, \"tag\",",
"which documented below. :param pulumi.Input[str] remark: The remarks of the VPC. (Default: `\"\"`).",
"pulumi.ResourceOptions): raise TypeError('Expected resource options to be a ResourceOptions instance') if opts.version is",
"Options for the resource. :param pulumi.Input[Sequence[pulumi.Input[str]]] cidr_blocks: The CIDR blocks of VPC. :param",
"@pulumi.getter(name=\"cidrBlocks\") def cidr_blocks(self) -> pulumi.Output[Sequence[str]]: \"\"\" The CIDR blocks of VPC. \"\"\" return",
"create_time __props__.__dict__[\"name\"] = name __props__.__dict__[\"network_infos\"] = network_infos __props__.__dict__[\"remark\"] = remark __props__.__dict__[\"tag\"] = tag",
"= name __props__.__dict__[\"remark\"] = remark __props__.__dict__[\"tag\"] = tag __props__.__dict__[\"create_time\"] = None __props__.__dict__[\"network_infos\"] =",
"\"create_time\", create_time) if name is not None: pulumi.set(__self__, \"name\", name) if network_infos is",
"__self__._internal_init(resource_name, *args, **kwargs) def _internal_init(__self__, resource_name: str, opts: Optional[pulumi.ResourceOptions] = None, cidr_blocks: Optional[pulumi.Input[Sequence[pulumi.Input[str]]]]",
"(Default: `\"\"`). :param pulumi.Input[str] tag: A tag assigned to VPC, which contains at",
"import pulumi_ucloud as ucloud example = ucloud.vpc.VPC(\"example\", cidr_blocks=[\"192.168.0.0/16\"], tag=\"tf-example\") ``` ## Import VPC",
"str resource_name: The name of the resource. :param VPCArgs args: The arguments to",
"opts.version is None: opts.version = _utilities.get_version() if opts.id is None: if __props__ is",
"create_time) if name is not None: pulumi.set(__self__, \"name\", name) if network_infos is not",
"cidr_blocks: pulumi.Input[Sequence[pulumi.Input[str]]], name: Optional[pulumi.Input[str]] = None, remark: Optional[pulumi.Input[str]] = None, tag: Optional[pulumi.Input[str]] =",
"remarks of the VPC. (Default: `\"\"`). \"\"\" return pulumi.get(self, \"remark\") @remark.setter def remark(self,",
".. import _utilities from . import outputs from ._inputs import * __all__ =",
"\"\"\" pulumi.set(__self__, \"cidr_blocks\", cidr_blocks) if name is not None: pulumi.set(__self__, \"name\", name) if",
"\"name\", value) @property @pulumi.getter def remark(self) -> Optional[pulumi.Input[str]]: \"\"\" The remarks of the",
"\"\"\" return pulumi.get(self, \"create_time\") @create_time.setter def create_time(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, \"create_time\", value) @property",
"__init__(__self__, resource_name: str, args: VPCArgs, opts: Optional[pulumi.ResourceOptions] = None): \"\"\" Provides a VPC",
"tag: Optional[pulumi.Input[str]] = None, update_time: Optional[pulumi.Input[str]] = None) -> 'VPC': \"\"\" Get an",
"hand unless you're certain you know what you are doing! *** import warnings",
"str resource_name: The unique name of the resulting resource. :param pulumi.Input[str] id: The",
"in RFC3339 time string. \"\"\" opts = pulumi.ResourceOptions.merge(opts, pulumi.ResourceOptions(id=id)) __props__ = _VPCState.__new__(_VPCState) __props__.__dict__[\"cidr_blocks\"]",
"= network_infos __props__.__dict__[\"remark\"] = remark __props__.__dict__[\"tag\"] = tag __props__.__dict__[\"update_time\"] = update_time return VPC(resource_name,",
"this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. *** #",
"The network segment can only be created or deleted, can not perform both",
"value: Optional[pulumi.Input[str]]): pulumi.set(self, \"name\", value) @property @pulumi.getter def remark(self) -> Optional[pulumi.Input[str]]: \"\"\" The",
"time string. \"\"\" opts = pulumi.ResourceOptions.merge(opts, pulumi.ResourceOptions(id=id)) __props__ = _VPCState.__new__(_VPCState) __props__.__dict__[\"cidr_blocks\"] = cidr_blocks",
"opts: Options for the resource. :param pulumi.Input[Sequence[pulumi.Input[str]]] cidr_blocks: The CIDR blocks of VPC.",
":param pulumi.Input[str] id: The unique provider ID of the resource to lookup. :param",
"used to qualify the lookup. :param str resource_name: The unique name of the",
"tag) @property @pulumi.getter(name=\"cidrBlocks\") def cidr_blocks(self) -> pulumi.Input[Sequence[pulumi.Input[str]]]: \"\"\" The CIDR blocks of VPC.",
"of VPC. \"\"\" return pulumi.get(self, \"cidr_blocks\") @property @pulumi.getter(name=\"createTime\") def create_time(self) -> pulumi.Output[str]: \"\"\"",
"time string. \"\"\" return pulumi.get(self, \"create_time\") @create_time.setter def create_time(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, \"create_time\",",
"= None): \"\"\" The set of arguments for constructing a VPC resource. :param",
"_utilities from . import outputs from ._inputs import * __all__ = ['VPCArgs', 'VPC']",
"name __props__.__dict__[\"remark\"] = remark __props__.__dict__[\"tag\"] = tag __props__.__dict__[\"create_time\"] = None __props__.__dict__[\"network_infos\"] = None",
"return pulumi.get(self, \"name\") @name.setter def name(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, \"name\", value) @property @pulumi.getter",
"@property @pulumi.getter(name=\"cidrBlocks\") def cidr_blocks(self) -> pulumi.Input[Sequence[pulumi.Input[str]]]: \"\"\" The CIDR blocks of VPC. \"\"\"",
"at the same time. ## Example Usage ```python import pulumi import pulumi_ucloud as",
"of them at the same time. ## Example Usage ```python import pulumi import",
"CIDR blocks of VPC. \"\"\" return pulumi.get(self, \"cidr_blocks\") @property @pulumi.getter(name=\"createTime\") def create_time(self) ->",
"return pulumi.get(self, \"cidr_blocks\") @cidr_blocks.setter def cidr_blocks(self, value: Optional[pulumi.Input[Sequence[pulumi.Input[str]]]]): pulumi.set(self, \"cidr_blocks\", value) @property @pulumi.getter(name=\"createTime\")",
"name, id, and optional extra properties used to qualify the lookup. :param str",
"lookup. :param pulumi.ResourceOptions opts: Options for the resource. :param pulumi.Input[Sequence[pulumi.Input[str]]] cidr_blocks: The CIDR",
"RFC3339 time string. \"\"\" if cidr_blocks is not None: pulumi.set(__self__, \"cidr_blocks\", cidr_blocks) if",
"ucloud.vpc.VPC(\"example\", cidr_blocks=[\"192.168.0.0/16\"], tag=\"tf-example\") ``` ## Import VPC can be imported using the `id`,",
"VPC. \"\"\" return pulumi.get(self, \"cidr_blocks\") @property @pulumi.getter(name=\"createTime\") def create_time(self) -> pulumi.Output[str]: \"\"\" The",
"VPC resource's state with the given name, id, and optional extra properties used",
"\"tag\", tag) @property @pulumi.getter(name=\"cidrBlocks\") def cidr_blocks(self) -> pulumi.Input[Sequence[pulumi.Input[str]]]: \"\"\" The CIDR blocks of",
"TypeError('__props__ is only valid when passed in combination with a valid opts.id to",
"resource. :param VPCArgs args: The arguments to use to populate this resource's properties.",
"name of the resource. :param pulumi.ResourceOptions opts: Options for the resource. :param pulumi.Input[Sequence[pulumi.Input[str]]]",
"value: Optional[pulumi.Input[str]]): pulumi.set(self, \"create_time\", value) @property @pulumi.getter def name(self) -> Optional[pulumi.Input[str]]: return pulumi.get(self,",
"filtering VPC resources. :param pulumi.Input[Sequence[pulumi.Input[str]]] cidr_blocks: The CIDR blocks of VPC. :param pulumi.Input[str]",
"@pulumi.getter(name=\"cidrBlocks\") def cidr_blocks(self) -> Optional[pulumi.Input[Sequence[pulumi.Input[str]]]]: \"\"\" The CIDR blocks of VPC. \"\"\" return",
"cidr_blocks=[\"192.168.0.0/16\"], tag=\"tf-example\") ``` ## Import VPC can be imported using the `id`, e.g.",
"**Note** The network segment can only be created or deleted, can not perform",
"for VPC, formatted in RFC3339 time string. \"\"\" return pulumi.get(self, \"create_time\") @property @pulumi.getter",
"there is a change made to VPC, formatted in RFC3339 time string. \"\"\"",
". import outputs from ._inputs import * __all__ = ['VPCArgs', 'VPC'] @pulumi.input_type class",
"not isinstance(opts, pulumi.ResourceOptions): raise TypeError('Expected resource options to be a ResourceOptions instance') if",
"what you are doing! *** import warnings import pulumi import pulumi.runtime from typing",
"be assigned. (Default: `Default`). \"\"\" pulumi.set(__self__, \"cidr_blocks\", cidr_blocks) if name is not None:",
"CIDR blocks of VPC. \"\"\" return pulumi.get(self, \"cidr_blocks\") @cidr_blocks.setter def cidr_blocks(self, value: Optional[pulumi.Input[Sequence[pulumi.Input[str]]]]):",
"network_infos: Optional[pulumi.Input[Sequence[pulumi.Input['VPCNetworkInfoArgs']]]] = None, remark: Optional[pulumi.Input[str]] = None, tag: Optional[pulumi.Input[str]] = None, update_time:",
"The time of creation for VPC, formatted in RFC3339 time string. \"\"\" return",
"def __init__(__self__, resource_name: str, opts: Optional[pulumi.ResourceOptions] = None, cidr_blocks: Optional[pulumi.Input[Sequence[pulumi.Input[str]]]] = None, name:",
"from ._inputs import * __all__ = ['VPCArgs', 'VPC'] @pulumi.input_type class VPCArgs: def __init__(__self__,",
"## Import VPC can be imported using the `id`, e.g. ```sh $ pulumi",
"opts: Optional[pulumi.ResourceOptions] = None): \"\"\" Provides a VPC resource. > **Note** The network",
"None, create_time: Optional[pulumi.Input[str]] = None, name: Optional[pulumi.Input[str]] = None, network_infos: Optional[pulumi.Input[Sequence[pulumi.Input[pulumi.InputType['VPCNetworkInfoArgs']]]]] = None,",
"made to VPC, formatted in RFC3339 time string. \"\"\" opts = pulumi.ResourceOptions.merge(opts, pulumi.ResourceOptions(id=id))",
"__props__.__dict__[\"network_infos\"] = network_infos __props__.__dict__[\"remark\"] = remark __props__.__dict__[\"tag\"] = tag __props__.__dict__[\"update_time\"] = update_time return",
"def remark(self) -> pulumi.Output[str]: \"\"\" The remarks of the VPC. (Default: `\"\"`). \"\"\"",
"nested type which documented below. \"\"\" return pulumi.get(self, \"network_infos\") @network_infos.setter def network_infos(self, value:",
":param pulumi.ResourceOptions opts: Options for the resource. \"\"\" ... def __init__(__self__, resource_name: str,",
"cidr_blocks is None and not opts.urn: raise TypeError(\"Missing required property 'cidr_blocks'\") __props__.__dict__[\"cidr_blocks\"] =",
"_internal_init(__self__, resource_name: str, opts: Optional[pulumi.ResourceOptions] = None, cidr_blocks: Optional[pulumi.Input[Sequence[pulumi.Input[str]]]] = None, name: Optional[pulumi.Input[str]]",
"= None, update_time: Optional[pulumi.Input[str]] = None) -> 'VPC': \"\"\" Get an existing VPC",
"@overload def __init__(__self__, resource_name: str, args: VPCArgs, opts: Optional[pulumi.ResourceOptions] = None): \"\"\" Provides",
"create_time(self) -> Optional[pulumi.Input[str]]: \"\"\" The time of creation for VPC, formatted in RFC3339",
"you know what you are doing! *** import warnings import pulumi import pulumi.runtime",
"update_time: The time whenever there is a change made to VPC, formatted in",
"value) class VPC(pulumi.CustomResource): @overload def __init__(__self__, resource_name: str, opts: Optional[pulumi.ResourceOptions] = None, cidr_blocks:",
"the same time. ## Example Usage ```python import pulumi import pulumi_ucloud as ucloud",
"to get an existing resource') __props__ = VPCArgs.__new__(VPCArgs) if cidr_blocks is None and",
"@property @pulumi.getter(name=\"createTime\") def create_time(self) -> Optional[pulumi.Input[str]]: \"\"\" The time of creation for VPC,",
"remarks of the VPC. (Default: `\"\"`). :param pulumi.Input[str] tag: A tag assigned to",
"filled in or a empty string is filled in, then default tag will",
"def name(self) -> pulumi.Output[str]: return pulumi.get(self, \"name\") @property @pulumi.getter(name=\"networkInfos\") def network_infos(self) -> pulumi.Output[Sequence['outputs.VPCNetworkInfo']]:",
"None, remark: Optional[pulumi.Input[str]] = None, tag: Optional[pulumi.Input[str]] = None): \"\"\" The set of",
"is not None: pulumi.set(__self__, \"name\", name) if remark is not None: pulumi.set(__self__, \"remark\",",
"time of creation for VPC, formatted in RFC3339 time string. \"\"\" return pulumi.get(self,",
"resource_name: The name of the resource. :param VPCArgs args: The arguments to use",
"pulumi.Output[str]: return pulumi.get(self, \"name\") @property @pulumi.getter(name=\"networkInfos\") def network_infos(self) -> pulumi.Output[Sequence['outputs.VPCNetworkInfo']]: \"\"\" It is",
"pulumi.set(self, \"create_time\", value) @property @pulumi.getter def name(self) -> Optional[pulumi.Input[str]]: return pulumi.get(self, \"name\") @name.setter",
"pulumi.Input[Sequence[pulumi.Input[str]]]: \"\"\" The CIDR blocks of VPC. \"\"\" return pulumi.get(self, \"cidr_blocks\") @cidr_blocks.setter def",
"__props__.__dict__[\"create_time\"] = create_time __props__.__dict__[\"name\"] = name __props__.__dict__[\"network_infos\"] = network_infos __props__.__dict__[\"remark\"] = remark __props__.__dict__[\"tag\"]",
":param pulumi.Input[Sequence[pulumi.Input[pulumi.InputType['VPCNetworkInfoArgs']]]] network_infos: It is a nested type which documented below. :param pulumi.Input[str]",
"The name of the resource. :param VPCArgs args: The arguments to use to",
"\"tag\") @property @pulumi.getter(name=\"updateTime\") def update_time(self) -> pulumi.Output[str]: \"\"\" The time whenever there is",
"pulumi.get(self, \"network_infos\") @property @pulumi.getter def remark(self) -> pulumi.Output[str]: \"\"\" The remarks of the",
"is None: opts.version = _utilities.get_version() if opts.id is None: if __props__ is not",
"Options for the resource. \"\"\" ... def __init__(__self__, resource_name: str, *args, **kwargs): resource_args,",
"= VPCArgs.__new__(VPCArgs) if cidr_blocks is None and not opts.urn: raise TypeError(\"Missing required property",
"will be assigned. (Default: `Default`). \"\"\" pulumi.set(__self__, \"cidr_blocks\", cidr_blocks) if name is not",
"\"\"\" return pulumi.get(self, \"cidr_blocks\") @cidr_blocks.setter def cidr_blocks(self, value: pulumi.Input[Sequence[pulumi.Input[str]]]): pulumi.set(self, \"cidr_blocks\", value) @property",
"below. :param pulumi.Input[str] remark: The remarks of the VPC. (Default: `\"\"`). :param pulumi.Input[str]",
"-> Optional[pulumi.Input[Sequence[pulumi.Input['VPCNetworkInfoArgs']]]]: \"\"\" It is a nested type which documented below. \"\"\" return",
"then default tag will be assigned. (Default: `Default`). \"\"\" return pulumi.get(self, \"tag\") @property",
"def create_time(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, \"create_time\", value) @property @pulumi.getter def name(self) -> Optional[pulumi.Input[str]]:",
"example uvnet-abc123456 ``` :param str resource_name: The name of the resource. :param VPCArgs",
"blocks of VPC. \"\"\" return pulumi.get(self, \"cidr_blocks\") @cidr_blocks.setter def cidr_blocks(self, value: pulumi.Input[Sequence[pulumi.Input[str]]]): pulumi.set(self,",
"of the resource. :param pulumi.ResourceOptions opts: Options for the resource. :param pulumi.Input[Sequence[pulumi.Input[str]]] cidr_blocks:",
"tag: A tag assigned to VPC, which contains at most 63 characters and",
"pulumi.ResourceOptions.merge(opts, pulumi.ResourceOptions(id=id)) __props__ = _VPCState.__new__(_VPCState) __props__.__dict__[\"cidr_blocks\"] = cidr_blocks __props__.__dict__[\"create_time\"] = create_time __props__.__dict__[\"name\"] =",
"None, create_time: Optional[pulumi.Input[str]] = None, name: Optional[pulumi.Input[str]] = None, network_infos: Optional[pulumi.Input[Sequence[pulumi.Input['VPCNetworkInfoArgs']]]] = None,",
"if network_infos is not None: pulumi.set(__self__, \"network_infos\", network_infos) if remark is not None:",
"resource's properties. :param pulumi.ResourceOptions opts: Options for the resource. \"\"\" ... def __init__(__self__,",
"formatted in RFC3339 time string. \"\"\" opts = pulumi.ResourceOptions.merge(opts, pulumi.ResourceOptions(id=id)) __props__ = _VPCState.__new__(_VPCState)",
"arguments for constructing a VPC resource. :param pulumi.Input[Sequence[pulumi.Input[str]]] cidr_blocks: The CIDR blocks of",
"None, remark: Optional[pulumi.Input[str]] = None, tag: Optional[pulumi.Input[str]] = None, __props__=None): \"\"\" Provides a",
"properties used to qualify the lookup. :param str resource_name: The unique name of",
"if resource_args is not None: __self__._internal_init(resource_name, opts, **resource_args.__dict__) else: __self__._internal_init(resource_name, *args, **kwargs) def",
"file was generated by the Pulumi Terraform Bridge (tfgen) Tool. *** # ***",
"filled in, then default tag will be assigned. (Default: `Default`). \"\"\" pulumi.set(__self__, \"cidr_blocks\",",
"made to VPC, formatted in RFC3339 time string. \"\"\" if cidr_blocks is not",
"VPC, formatted in RFC3339 time string. :param pulumi.Input[Sequence[pulumi.Input[pulumi.InputType['VPCNetworkInfoArgs']]]] network_infos: It is a nested",
"opts = pulumi.ResourceOptions() if not isinstance(opts, pulumi.ResourceOptions): raise TypeError('Expected resource options to be",
"in RFC3339 time string. \"\"\" if cidr_blocks is not None: pulumi.set(__self__, \"cidr_blocks\", cidr_blocks)",
"Optional[pulumi.Input[str]]: return pulumi.get(self, \"name\") @name.setter def name(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, \"name\", value) @property",
"raise TypeError('Expected resource options to be a ResourceOptions instance') if opts.version is None:",
"opts=opts, __props__=__props__) @property @pulumi.getter(name=\"cidrBlocks\") def cidr_blocks(self) -> pulumi.Output[Sequence[str]]: \"\"\" The CIDR blocks of",
"@pulumi.getter def tag(self) -> Optional[pulumi.Input[str]]: \"\"\" A tag assigned to VPC, which contains",
"\"network_infos\", value) @property @pulumi.getter def remark(self) -> Optional[pulumi.Input[str]]: \"\"\" The remarks of the",
"@update_time.setter def update_time(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, \"update_time\", value) class VPC(pulumi.CustomResource): @overload def __init__(__self__,",
"pulumi.get(self, \"tag\") @tag.setter def tag(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, \"tag\", value) @property @pulumi.getter(name=\"updateTime\") def",
"\"\"\" The CIDR blocks of VPC. \"\"\" return pulumi.get(self, \"cidr_blocks\") @cidr_blocks.setter def cidr_blocks(self,",
"else: __self__._internal_init(resource_name, *args, **kwargs) def _internal_init(__self__, resource_name: str, opts: Optional[pulumi.ResourceOptions] = None, cidr_blocks:",
"resource. :param pulumi.Input[Sequence[pulumi.Input[str]]] cidr_blocks: The CIDR blocks of VPC. :param pulumi.Input[str] remark: The",
"not None: pulumi.set(__self__, \"update_time\", update_time) @property @pulumi.getter(name=\"cidrBlocks\") def cidr_blocks(self) -> Optional[pulumi.Input[Sequence[pulumi.Input[str]]]]: \"\"\" The",
"None): \"\"\" Provides a VPC resource. > **Note** The network segment can only",
"existing VPC resource's state with the given name, id, and optional extra properties",
"= None, cidr_blocks: Optional[pulumi.Input[Sequence[pulumi.Input[str]]]] = None, name: Optional[pulumi.Input[str]] = None, remark: Optional[pulumi.Input[str]] =",
"was generated by the Pulumi Terraform Bridge (tfgen) Tool. *** # *** Do",
"set of arguments for constructing a VPC resource. :param pulumi.Input[Sequence[pulumi.Input[str]]] cidr_blocks: The CIDR",
"def cidr_blocks(self) -> pulumi.Output[Sequence[str]]: \"\"\" The CIDR blocks of VPC. \"\"\" return pulumi.get(self,",
"VPC. (Default: `\"\"`). \"\"\" return pulumi.get(self, \"remark\") @property @pulumi.getter def tag(self) -> pulumi.Output[Optional[str]]:",
"None: opts.version = _utilities.get_version() if opts.id is None: if __props__ is not None:",
"return pulumi.get(self, \"create_time\") @property @pulumi.getter def name(self) -> pulumi.Output[str]: return pulumi.get(self, \"name\") @property",
"isinstance(opts, pulumi.ResourceOptions): raise TypeError('Expected resource options to be a ResourceOptions instance') if opts.version",
"The CIDR blocks of VPC. :param pulumi.Input[str] create_time: The time of creation for",
"combination with a valid opts.id to get an existing resource') __props__ = VPCArgs.__new__(VPCArgs)",
"tag: Optional[pulumi.Input[str]] = None, __props__=None): if opts is None: opts = pulumi.ResourceOptions() if",
"import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union, overload",
"name(self) -> pulumi.Output[str]: return pulumi.get(self, \"name\") @property @pulumi.getter(name=\"networkInfos\") def network_infos(self) -> pulumi.Output[Sequence['outputs.VPCNetworkInfo']]: \"\"\"",
"@name.setter def name(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, \"name\", value) @property @pulumi.getter def remark(self) ->",
"pulumi.Input[str] tag: A tag assigned to VPC, which contains at most 63 characters",
"string. :param pulumi.Input[Sequence[pulumi.Input['VPCNetworkInfoArgs']]] network_infos: It is a nested type which documented below. :param",
"update_time return VPC(resource_name, opts=opts, __props__=__props__) @property @pulumi.getter(name=\"cidrBlocks\") def cidr_blocks(self) -> pulumi.Output[Sequence[str]]: \"\"\" The",
"name __props__.__dict__[\"network_infos\"] = network_infos __props__.__dict__[\"remark\"] = remark __props__.__dict__[\"tag\"] = tag __props__.__dict__[\"update_time\"] = update_time",
"= cidr_blocks __props__.__dict__[\"create_time\"] = create_time __props__.__dict__[\"name\"] = name __props__.__dict__[\"network_infos\"] = network_infos __props__.__dict__[\"remark\"] =",
"-> pulumi.Input[Sequence[pulumi.Input[str]]]: \"\"\" The CIDR blocks of VPC. \"\"\" return pulumi.get(self, \"cidr_blocks\") @cidr_blocks.setter",
"and filtering VPC resources. :param pulumi.Input[Sequence[pulumi.Input[str]]] cidr_blocks: The CIDR blocks of VPC. :param",
"pulumi.get(self, \"name\") @property @pulumi.getter(name=\"networkInfos\") def network_infos(self) -> pulumi.Output[Sequence['outputs.VPCNetworkInfo']]: \"\"\" It is a nested",
"numbers, '-', '_', and '.'. If it is not filled in or a",
"return pulumi.get(self, \"tag\") @property @pulumi.getter(name=\"updateTime\") def update_time(self) -> pulumi.Output[str]: \"\"\" The time whenever",
"def cidr_blocks(self) -> pulumi.Input[Sequence[pulumi.Input[str]]]: \"\"\" The CIDR blocks of VPC. \"\"\" return pulumi.get(self,",
":param pulumi.Input[Sequence[pulumi.Input['VPCNetworkInfoArgs']]] network_infos: It is a nested type which documented below. :param pulumi.Input[str]",
"resource_args, opts = _utilities.get_resource_args_opts(VPCArgs, pulumi.ResourceOptions, *args, **kwargs) if resource_args is not None: __self__._internal_init(resource_name,",
"RFC3339 time string. \"\"\" return pulumi.get(self, \"create_time\") @create_time.setter def create_time(self, value: Optional[pulumi.Input[str]]): pulumi.set(self,",
"## Example Usage ```python import pulumi import pulumi_ucloud as ucloud example = ucloud.vpc.VPC(\"example\",",
"None: pulumi.set(__self__, \"tag\", tag) @property @pulumi.getter(name=\"cidrBlocks\") def cidr_blocks(self) -> pulumi.Input[Sequence[pulumi.Input[str]]]: \"\"\" The CIDR",
"-> pulumi.Output[Sequence['outputs.VPCNetworkInfo']]: \"\"\" It is a nested type which documented below. \"\"\" return",
"return pulumi.get(self, \"create_time\") @create_time.setter def create_time(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, \"create_time\", value) @property @pulumi.getter"
] |
[
"'1563'] #image_list = ['27', '78', '403', '414', '480', '579'] gnd_truth_hr_image_path = 'Data/MRI/PaperTestData/HR_gnd/' generated_hr_image_path",
"avg_ssim /= len(image_list) print('Average PSNR = ' + str(avg_psnr)) print('Average SSIM = '",
"generated_hr_img.min()) print('PSNR = ' + str(psnr_i) + ', SSIM = ' + str(ssim_i))",
"' + str(ssim_i)) avg_psnr += psnr_i avg_ssim += ssim_i avg_psnr /= len(image_list) avg_ssim",
"'1463', '1563'] #image_list = ['27', '78', '403', '414', '480', '579'] gnd_truth_hr_image_path = 'Data/MRI/PaperTestData/HR_gnd/'",
"scipy.misc.imread(generated_hr_image_path, mode='L') # print out PSNR #print(skimage.measure.compare_psnr(gnd_truth_hr_img_resized, generated_hr_img)) # print out SSIM #print(skimage.measure.compare_ssim(gnd_truth_hr_img_resized,",
"im in image_list: gnd_truth_hr_img = scipy.misc.imread(gnd_truth_hr_image_path+'valid_hr-id-'+im+'.png', mode='L') generated_hr_img = scipy.misc.imread(generated_hr_image_path+'valid_hr_gen-id-'+im+'.png', mode='L') # print",
"'403', '414', '480', '579'] gnd_truth_hr_image_path = 'Data/MRI/PaperTestData/HR_gnd/' generated_hr_image_path = 'Data/MRI/PaperTestData/HR_gen/' avg_psnr = 0",
"and SSIM psnr_i = skimage.measure.compare_psnr(gnd_truth_hr_img, generated_hr_img) ssim_i = skimage.measure.compare_ssim(gnd_truth_hr_img, generated_hr_img, data_range=generated_hr_img.max() - generated_hr_img.min())",
"'Data/MRI/PaperTestData/HR_gnd/' generated_hr_image_path = 'Data/MRI/PaperTestData/HR_gen/' avg_psnr = 0 avg_ssim = 0 for im in",
"print out PSNR and SSIM psnr_i = skimage.measure.compare_psnr(gnd_truth_hr_img, generated_hr_img) ssim_i = skimage.measure.compare_ssim(gnd_truth_hr_img, generated_hr_img,",
"'403', '414', '480', '579', '587', '664', '711', '715', '756', '771', '788', '793', '826',",
"generated_hr_img, data_range=generated_hr_img.max() - generated_hr_img.min()) print('PSNR = ' + str(psnr_i) + ', SSIM =",
"#image_list = ['27', '78', '403', '414', '480', '579'] gnd_truth_hr_image_path = 'Data/MRI/PaperTestData/HR_gnd/' generated_hr_image_path =",
"# print out PSNR #print(skimage.measure.compare_psnr(gnd_truth_hr_img_resized, generated_hr_img)) # print out SSIM #print(skimage.measure.compare_ssim(gnd_truth_hr_img_resized, generated_hr_img, data_range=generated_hr_img.max()",
"'788', '793', '826', '947', '994', '1076', '1097', '1099', '1141', '1197', '1263', '1320', '1389',",
"'579', '587', '664', '711', '715', '756', '771', '788', '793', '826', '947', '994', '1076',",
"image_list: gnd_truth_hr_img = scipy.misc.imread(gnd_truth_hr_image_path+'valid_hr-id-'+im+'.png', mode='L') generated_hr_img = scipy.misc.imread(generated_hr_image_path+'valid_hr_gen-id-'+im+'.png', mode='L') # print out PSNR",
"SSIM psnr_i = skimage.measure.compare_psnr(gnd_truth_hr_img, generated_hr_img) ssim_i = skimage.measure.compare_ssim(gnd_truth_hr_img, generated_hr_img, data_range=generated_hr_img.max() - generated_hr_img.min()) print('PSNR",
"'1263', '1320', '1389', '1463', '1563'] #image_list = ['27', '78', '403', '414', '480', '579']",
"to (384x384) image #gnd_truth_hr_img = scipy.misc.imread(gnd_truth_hr_image_path, mode='L') #gnd_truth_hr_img_resized = scipy.misc.imresize(gnd_truth_hr_img, [384, 384], interp='bicubic',",
"= scipy.misc.imread(generated_hr_image_path+'valid_hr_gen-id-'+im+'.png', mode='L') # print out PSNR and SSIM psnr_i = skimage.measure.compare_psnr(gnd_truth_hr_img, generated_hr_img)",
"#gnd_truth_hr_img = scipy.misc.imread(gnd_truth_hr_image_path, mode='L') #gnd_truth_hr_img_resized = scipy.misc.imresize(gnd_truth_hr_img, [384, 384], interp='bicubic', mode='L') # read",
"= scipy.misc.imread(gnd_truth_hr_image_path, mode='L') #gnd_truth_hr_img_resized = scipy.misc.imresize(gnd_truth_hr_img, [384, 384], interp='bicubic', mode='L') # read generated",
"skimage.measure image_list = ['27', '78', '403', '414', '480', '579', '587', '664', '711', '715',",
"'756', '771', '788', '793', '826', '947', '994', '1076', '1097', '1099', '1141', '1197', '1263',",
"str(avg_psnr)) print('Average SSIM = ' + str(avg_ssim)) # resize ground truth to (384x384)",
"# read generated (384x384) image #generated_hr_img = scipy.misc.imread(generated_hr_image_path, mode='L') # print out PSNR",
"str(psnr_i) + ', SSIM = ' + str(ssim_i)) avg_psnr += psnr_i avg_ssim +=",
"'414', '480', '579'] gnd_truth_hr_image_path = 'Data/MRI/PaperTestData/HR_gnd/' generated_hr_image_path = 'Data/MRI/PaperTestData/HR_gen/' avg_psnr = 0 avg_ssim",
"= skimage.measure.compare_ssim(gnd_truth_hr_img, generated_hr_img, data_range=generated_hr_img.max() - generated_hr_img.min()) print('PSNR = ' + str(psnr_i) + ',",
"= scipy.misc.imread(generated_hr_image_path, mode='L') # print out PSNR #print(skimage.measure.compare_psnr(gnd_truth_hr_img_resized, generated_hr_img)) # print out SSIM",
"avg_ssim += ssim_i avg_psnr /= len(image_list) avg_ssim /= len(image_list) print('Average PSNR = '",
"'947', '994', '1076', '1097', '1099', '1141', '1197', '1263', '1320', '1389', '1463', '1563'] #image_list",
"[384, 384], interp='bicubic', mode='L') # read generated (384x384) image #generated_hr_img = scipy.misc.imread(generated_hr_image_path, mode='L')",
"generated_hr_img = scipy.misc.imread(generated_hr_image_path+'valid_hr_gen-id-'+im+'.png', mode='L') # print out PSNR and SSIM psnr_i = skimage.measure.compare_psnr(gnd_truth_hr_img,",
"- generated_hr_img.min()) print('PSNR = ' + str(psnr_i) + ', SSIM = ' +",
"print('Average SSIM = ' + str(avg_ssim)) # resize ground truth to (384x384) image",
"# print out PSNR and SSIM psnr_i = skimage.measure.compare_psnr(gnd_truth_hr_img, generated_hr_img) ssim_i = skimage.measure.compare_ssim(gnd_truth_hr_img,",
"numpy as np import skimage import scipy.misc import skimage.measure image_list = ['27', '78',",
"mode='L') #gnd_truth_hr_img_resized = scipy.misc.imresize(gnd_truth_hr_img, [384, 384], interp='bicubic', mode='L') # read generated (384x384) image",
"'994', '1076', '1097', '1099', '1141', '1197', '1263', '1320', '1389', '1463', '1563'] #image_list =",
"= skimage.measure.compare_psnr(gnd_truth_hr_img, generated_hr_img) ssim_i = skimage.measure.compare_ssim(gnd_truth_hr_img, generated_hr_img, data_range=generated_hr_img.max() - generated_hr_img.min()) print('PSNR = '",
"+ str(avg_psnr)) print('Average SSIM = ' + str(avg_ssim)) # resize ground truth to",
"psnr_i avg_ssim += ssim_i avg_psnr /= len(image_list) avg_ssim /= len(image_list) print('Average PSNR =",
"PSNR = ' + str(avg_psnr)) print('Average SSIM = ' + str(avg_ssim)) # resize",
"= ['27', '78', '403', '414', '480', '579', '587', '664', '711', '715', '756', '771',",
"#generated_hr_img = scipy.misc.imread(generated_hr_image_path, mode='L') # print out PSNR #print(skimage.measure.compare_psnr(gnd_truth_hr_img_resized, generated_hr_img)) # print out",
"'793', '826', '947', '994', '1076', '1097', '1099', '1141', '1197', '1263', '1320', '1389', '1463',",
"'78', '403', '414', '480', '579'] gnd_truth_hr_image_path = 'Data/MRI/PaperTestData/HR_gnd/' generated_hr_image_path = 'Data/MRI/PaperTestData/HR_gen/' avg_psnr =",
"/= len(image_list) print('Average PSNR = ' + str(avg_psnr)) print('Average SSIM = ' +",
"out PSNR and SSIM psnr_i = skimage.measure.compare_psnr(gnd_truth_hr_img, generated_hr_img) ssim_i = skimage.measure.compare_ssim(gnd_truth_hr_img, generated_hr_img, data_range=generated_hr_img.max()",
"['27', '78', '403', '414', '480', '579'] gnd_truth_hr_image_path = 'Data/MRI/PaperTestData/HR_gnd/' generated_hr_image_path = 'Data/MRI/PaperTestData/HR_gen/' avg_psnr",
"str(avg_ssim)) # resize ground truth to (384x384) image #gnd_truth_hr_img = scipy.misc.imread(gnd_truth_hr_image_path, mode='L') #gnd_truth_hr_img_resized",
"#gnd_truth_hr_img_resized = scipy.misc.imresize(gnd_truth_hr_img, [384, 384], interp='bicubic', mode='L') # read generated (384x384) image #generated_hr_img",
"<reponame>ashishpatel26/SuperResolution-Medical-Imaging-using-SRGAN import scipy import numpy as np import skimage import scipy.misc import skimage.measure",
"'480', '579', '587', '664', '711', '715', '756', '771', '788', '793', '826', '947', '994',",
"avg_psnr += psnr_i avg_ssim += ssim_i avg_psnr /= len(image_list) avg_ssim /= len(image_list) print('Average",
"image_list = ['27', '78', '403', '414', '480', '579', '587', '664', '711', '715', '756',",
"+ str(avg_ssim)) # resize ground truth to (384x384) image #gnd_truth_hr_img = scipy.misc.imread(gnd_truth_hr_image_path, mode='L')",
"avg_psnr /= len(image_list) avg_ssim /= len(image_list) print('Average PSNR = ' + str(avg_psnr)) print('Average",
"ssim_i = skimage.measure.compare_ssim(gnd_truth_hr_img, generated_hr_img, data_range=generated_hr_img.max() - generated_hr_img.min()) print('PSNR = ' + str(psnr_i) +",
"(384x384) image #gnd_truth_hr_img = scipy.misc.imread(gnd_truth_hr_image_path, mode='L') #gnd_truth_hr_img_resized = scipy.misc.imresize(gnd_truth_hr_img, [384, 384], interp='bicubic', mode='L')",
"out PSNR #print(skimage.measure.compare_psnr(gnd_truth_hr_img_resized, generated_hr_img)) # print out SSIM #print(skimage.measure.compare_ssim(gnd_truth_hr_img_resized, generated_hr_img, data_range=generated_hr_img.max() - generated_hr_img.min()))",
"mode='L') # read generated (384x384) image #generated_hr_img = scipy.misc.imread(generated_hr_image_path, mode='L') # print out",
"'480', '579'] gnd_truth_hr_image_path = 'Data/MRI/PaperTestData/HR_gnd/' generated_hr_image_path = 'Data/MRI/PaperTestData/HR_gen/' avg_psnr = 0 avg_ssim =",
"SSIM = ' + str(avg_ssim)) # resize ground truth to (384x384) image #gnd_truth_hr_img",
"resize ground truth to (384x384) image #gnd_truth_hr_img = scipy.misc.imread(gnd_truth_hr_image_path, mode='L') #gnd_truth_hr_img_resized = scipy.misc.imresize(gnd_truth_hr_img,",
"'771', '788', '793', '826', '947', '994', '1076', '1097', '1099', '1141', '1197', '1263', '1320',",
"'579'] gnd_truth_hr_image_path = 'Data/MRI/PaperTestData/HR_gnd/' generated_hr_image_path = 'Data/MRI/PaperTestData/HR_gen/' avg_psnr = 0 avg_ssim = 0",
"gnd_truth_hr_img = scipy.misc.imread(gnd_truth_hr_image_path+'valid_hr-id-'+im+'.png', mode='L') generated_hr_img = scipy.misc.imread(generated_hr_image_path+'valid_hr_gen-id-'+im+'.png', mode='L') # print out PSNR and",
"= ' + str(ssim_i)) avg_psnr += psnr_i avg_ssim += ssim_i avg_psnr /= len(image_list)",
"generated_hr_img) ssim_i = skimage.measure.compare_ssim(gnd_truth_hr_img, generated_hr_img, data_range=generated_hr_img.max() - generated_hr_img.min()) print('PSNR = ' + str(psnr_i)",
"np import skimage import scipy.misc import skimage.measure image_list = ['27', '78', '403', '414',",
"'1097', '1099', '1141', '1197', '1263', '1320', '1389', '1463', '1563'] #image_list = ['27', '78',",
"'826', '947', '994', '1076', '1097', '1099', '1141', '1197', '1263', '1320', '1389', '1463', '1563']",
"mode='L') generated_hr_img = scipy.misc.imread(generated_hr_image_path+'valid_hr_gen-id-'+im+'.png', mode='L') # print out PSNR and SSIM psnr_i =",
"generated (384x384) image #generated_hr_img = scipy.misc.imread(generated_hr_image_path, mode='L') # print out PSNR #print(skimage.measure.compare_psnr(gnd_truth_hr_img_resized, generated_hr_img))",
"= scipy.misc.imresize(gnd_truth_hr_img, [384, 384], interp='bicubic', mode='L') # read generated (384x384) image #generated_hr_img =",
"print out PSNR #print(skimage.measure.compare_psnr(gnd_truth_hr_img_resized, generated_hr_img)) # print out SSIM #print(skimage.measure.compare_ssim(gnd_truth_hr_img_resized, generated_hr_img, data_range=generated_hr_img.max() -",
"skimage.measure.compare_psnr(gnd_truth_hr_img, generated_hr_img) ssim_i = skimage.measure.compare_ssim(gnd_truth_hr_img, generated_hr_img, data_range=generated_hr_img.max() - generated_hr_img.min()) print('PSNR = ' +",
"as np import skimage import scipy.misc import skimage.measure image_list = ['27', '78', '403',",
"', SSIM = ' + str(ssim_i)) avg_psnr += psnr_i avg_ssim += ssim_i avg_psnr",
"= ' + str(avg_ssim)) # resize ground truth to (384x384) image #gnd_truth_hr_img =",
"import numpy as np import skimage import scipy.misc import skimage.measure image_list = ['27',",
"scipy.misc.imread(generated_hr_image_path+'valid_hr_gen-id-'+im+'.png', mode='L') # print out PSNR and SSIM psnr_i = skimage.measure.compare_psnr(gnd_truth_hr_img, generated_hr_img) ssim_i",
"' + str(psnr_i) + ', SSIM = ' + str(ssim_i)) avg_psnr += psnr_i",
"'587', '664', '711', '715', '756', '771', '788', '793', '826', '947', '994', '1076', '1097',",
"'1076', '1097', '1099', '1141', '1197', '1263', '1320', '1389', '1463', '1563'] #image_list = ['27',",
"len(image_list) avg_ssim /= len(image_list) print('Average PSNR = ' + str(avg_psnr)) print('Average SSIM =",
"gnd_truth_hr_image_path = 'Data/MRI/PaperTestData/HR_gnd/' generated_hr_image_path = 'Data/MRI/PaperTestData/HR_gen/' avg_psnr = 0 avg_ssim = 0 for",
"PSNR and SSIM psnr_i = skimage.measure.compare_psnr(gnd_truth_hr_img, generated_hr_img) ssim_i = skimage.measure.compare_ssim(gnd_truth_hr_img, generated_hr_img, data_range=generated_hr_img.max() -",
"scipy.misc import skimage.measure image_list = ['27', '78', '403', '414', '480', '579', '587', '664',",
"+ str(ssim_i)) avg_psnr += psnr_i avg_ssim += ssim_i avg_psnr /= len(image_list) avg_ssim /=",
"# resize ground truth to (384x384) image #gnd_truth_hr_img = scipy.misc.imread(gnd_truth_hr_image_path, mode='L') #gnd_truth_hr_img_resized =",
"ground truth to (384x384) image #gnd_truth_hr_img = scipy.misc.imread(gnd_truth_hr_image_path, mode='L') #gnd_truth_hr_img_resized = scipy.misc.imresize(gnd_truth_hr_img, [384,",
"'715', '756', '771', '788', '793', '826', '947', '994', '1076', '1097', '1099', '1141', '1197',",
"ssim_i avg_psnr /= len(image_list) avg_ssim /= len(image_list) print('Average PSNR = ' + str(avg_psnr))",
"+= psnr_i avg_ssim += ssim_i avg_psnr /= len(image_list) avg_ssim /= len(image_list) print('Average PSNR",
"+= ssim_i avg_psnr /= len(image_list) avg_ssim /= len(image_list) print('Average PSNR = ' +",
"avg_ssim = 0 for im in image_list: gnd_truth_hr_img = scipy.misc.imread(gnd_truth_hr_image_path+'valid_hr-id-'+im+'.png', mode='L') generated_hr_img =",
"len(image_list) print('Average PSNR = ' + str(avg_psnr)) print('Average SSIM = ' + str(avg_ssim))",
"import scipy import numpy as np import skimage import scipy.misc import skimage.measure image_list",
"= ['27', '78', '403', '414', '480', '579'] gnd_truth_hr_image_path = 'Data/MRI/PaperTestData/HR_gnd/' generated_hr_image_path = 'Data/MRI/PaperTestData/HR_gen/'",
"truth to (384x384) image #gnd_truth_hr_img = scipy.misc.imread(gnd_truth_hr_image_path, mode='L') #gnd_truth_hr_img_resized = scipy.misc.imresize(gnd_truth_hr_img, [384, 384],",
"+ ', SSIM = ' + str(ssim_i)) avg_psnr += psnr_i avg_ssim += ssim_i",
"for im in image_list: gnd_truth_hr_img = scipy.misc.imread(gnd_truth_hr_image_path+'valid_hr-id-'+im+'.png', mode='L') generated_hr_img = scipy.misc.imread(generated_hr_image_path+'valid_hr_gen-id-'+im+'.png', mode='L') #",
"avg_psnr = 0 avg_ssim = 0 for im in image_list: gnd_truth_hr_img = scipy.misc.imread(gnd_truth_hr_image_path+'valid_hr-id-'+im+'.png',",
"mode='L') # print out PSNR and SSIM psnr_i = skimage.measure.compare_psnr(gnd_truth_hr_img, generated_hr_img) ssim_i =",
"psnr_i = skimage.measure.compare_psnr(gnd_truth_hr_img, generated_hr_img) ssim_i = skimage.measure.compare_ssim(gnd_truth_hr_img, generated_hr_img, data_range=generated_hr_img.max() - generated_hr_img.min()) print('PSNR =",
"'711', '715', '756', '771', '788', '793', '826', '947', '994', '1076', '1097', '1099', '1141',",
"scipy.misc.imread(gnd_truth_hr_image_path, mode='L') #gnd_truth_hr_img_resized = scipy.misc.imresize(gnd_truth_hr_img, [384, 384], interp='bicubic', mode='L') # read generated (384x384)",
"(384x384) image #generated_hr_img = scipy.misc.imread(generated_hr_image_path, mode='L') # print out PSNR #print(skimage.measure.compare_psnr(gnd_truth_hr_img_resized, generated_hr_img)) #",
"SSIM = ' + str(ssim_i)) avg_psnr += psnr_i avg_ssim += ssim_i avg_psnr /=",
"' + str(avg_psnr)) print('Average SSIM = ' + str(avg_ssim)) # resize ground truth",
"'78', '403', '414', '480', '579', '587', '664', '711', '715', '756', '771', '788', '793',",
"import skimage import scipy.misc import skimage.measure image_list = ['27', '78', '403', '414', '480',",
"['27', '78', '403', '414', '480', '579', '587', '664', '711', '715', '756', '771', '788',",
"generated_hr_image_path = 'Data/MRI/PaperTestData/HR_gen/' avg_psnr = 0 avg_ssim = 0 for im in image_list:",
"print('Average PSNR = ' + str(avg_psnr)) print('Average SSIM = ' + str(avg_ssim)) #",
"384], interp='bicubic', mode='L') # read generated (384x384) image #generated_hr_img = scipy.misc.imread(generated_hr_image_path, mode='L') #",
"= ' + str(avg_psnr)) print('Average SSIM = ' + str(avg_ssim)) # resize ground",
"'1320', '1389', '1463', '1563'] #image_list = ['27', '78', '403', '414', '480', '579'] gnd_truth_hr_image_path",
"data_range=generated_hr_img.max() - generated_hr_img.min()) print('PSNR = ' + str(psnr_i) + ', SSIM = '",
"' + str(avg_ssim)) # resize ground truth to (384x384) image #gnd_truth_hr_img = scipy.misc.imread(gnd_truth_hr_image_path,",
"0 avg_ssim = 0 for im in image_list: gnd_truth_hr_img = scipy.misc.imread(gnd_truth_hr_image_path+'valid_hr-id-'+im+'.png', mode='L') generated_hr_img",
"in image_list: gnd_truth_hr_img = scipy.misc.imread(gnd_truth_hr_image_path+'valid_hr-id-'+im+'.png', mode='L') generated_hr_img = scipy.misc.imread(generated_hr_image_path+'valid_hr_gen-id-'+im+'.png', mode='L') # print out",
"skimage.measure.compare_ssim(gnd_truth_hr_img, generated_hr_img, data_range=generated_hr_img.max() - generated_hr_img.min()) print('PSNR = ' + str(psnr_i) + ', SSIM",
"scipy import numpy as np import skimage import scipy.misc import skimage.measure image_list =",
"+ str(psnr_i) + ', SSIM = ' + str(ssim_i)) avg_psnr += psnr_i avg_ssim",
"'Data/MRI/PaperTestData/HR_gen/' avg_psnr = 0 avg_ssim = 0 for im in image_list: gnd_truth_hr_img =",
"= 'Data/MRI/PaperTestData/HR_gnd/' generated_hr_image_path = 'Data/MRI/PaperTestData/HR_gen/' avg_psnr = 0 avg_ssim = 0 for im",
"scipy.misc.imresize(gnd_truth_hr_img, [384, 384], interp='bicubic', mode='L') # read generated (384x384) image #generated_hr_img = scipy.misc.imread(generated_hr_image_path,",
"str(ssim_i)) avg_psnr += psnr_i avg_ssim += ssim_i avg_psnr /= len(image_list) avg_ssim /= len(image_list)",
"mode='L') # print out PSNR #print(skimage.measure.compare_psnr(gnd_truth_hr_img_resized, generated_hr_img)) # print out SSIM #print(skimage.measure.compare_ssim(gnd_truth_hr_img_resized, generated_hr_img,",
"= 'Data/MRI/PaperTestData/HR_gen/' avg_psnr = 0 avg_ssim = 0 for im in image_list: gnd_truth_hr_img",
"read generated (384x384) image #generated_hr_img = scipy.misc.imread(generated_hr_image_path, mode='L') # print out PSNR #print(skimage.measure.compare_psnr(gnd_truth_hr_img_resized,",
"scipy.misc.imread(gnd_truth_hr_image_path+'valid_hr-id-'+im+'.png', mode='L') generated_hr_img = scipy.misc.imread(generated_hr_image_path+'valid_hr_gen-id-'+im+'.png', mode='L') # print out PSNR and SSIM psnr_i",
"'664', '711', '715', '756', '771', '788', '793', '826', '947', '994', '1076', '1097', '1099',",
"0 for im in image_list: gnd_truth_hr_img = scipy.misc.imread(gnd_truth_hr_image_path+'valid_hr-id-'+im+'.png', mode='L') generated_hr_img = scipy.misc.imread(generated_hr_image_path+'valid_hr_gen-id-'+im+'.png', mode='L')",
"'1099', '1141', '1197', '1263', '1320', '1389', '1463', '1563'] #image_list = ['27', '78', '403',",
"'1197', '1263', '1320', '1389', '1463', '1563'] #image_list = ['27', '78', '403', '414', '480',",
"import scipy.misc import skimage.measure image_list = ['27', '78', '403', '414', '480', '579', '587',",
"/= len(image_list) avg_ssim /= len(image_list) print('Average PSNR = ' + str(avg_psnr)) print('Average SSIM",
"= scipy.misc.imread(gnd_truth_hr_image_path+'valid_hr-id-'+im+'.png', mode='L') generated_hr_img = scipy.misc.imread(generated_hr_image_path+'valid_hr_gen-id-'+im+'.png', mode='L') # print out PSNR and SSIM",
"= ' + str(psnr_i) + ', SSIM = ' + str(ssim_i)) avg_psnr +=",
"'414', '480', '579', '587', '664', '711', '715', '756', '771', '788', '793', '826', '947',",
"import skimage.measure image_list = ['27', '78', '403', '414', '480', '579', '587', '664', '711',",
"skimage import scipy.misc import skimage.measure image_list = ['27', '78', '403', '414', '480', '579',",
"'1389', '1463', '1563'] #image_list = ['27', '78', '403', '414', '480', '579'] gnd_truth_hr_image_path =",
"'1141', '1197', '1263', '1320', '1389', '1463', '1563'] #image_list = ['27', '78', '403', '414',",
"interp='bicubic', mode='L') # read generated (384x384) image #generated_hr_img = scipy.misc.imread(generated_hr_image_path, mode='L') # print",
"= 0 for im in image_list: gnd_truth_hr_img = scipy.misc.imread(gnd_truth_hr_image_path+'valid_hr-id-'+im+'.png', mode='L') generated_hr_img = scipy.misc.imread(generated_hr_image_path+'valid_hr_gen-id-'+im+'.png',",
"= 0 avg_ssim = 0 for im in image_list: gnd_truth_hr_img = scipy.misc.imread(gnd_truth_hr_image_path+'valid_hr-id-'+im+'.png', mode='L')",
"image #gnd_truth_hr_img = scipy.misc.imread(gnd_truth_hr_image_path, mode='L') #gnd_truth_hr_img_resized = scipy.misc.imresize(gnd_truth_hr_img, [384, 384], interp='bicubic', mode='L') #",
"image #generated_hr_img = scipy.misc.imread(generated_hr_image_path, mode='L') # print out PSNR #print(skimage.measure.compare_psnr(gnd_truth_hr_img_resized, generated_hr_img)) # print",
"print('PSNR = ' + str(psnr_i) + ', SSIM = ' + str(ssim_i)) avg_psnr"
] |
[
"executable to use instead of the current one.\" \" Overrides the corresponding setting",
"eprint(\"Error reading the config file: {}\".format(e)) except yaml.YAMLError as e: eprint(\"Malformed YAML in",
"to the python executable to use instead of the current one.\" \" Overrides",
"current working directory.\" \"\\nWARNING: Always verify externally supplied configurations before using them.\" )",
"logging.getLogger(\"matplotlib\").setLevel(logging.INFO) logging.getLogger(\"snips_nlu\").setLevel(logging.WARNING) logging.getLogger(\"urllib3\").setLevel(logging.INFO) logging.getLogger(\"msrest\").setLevel(logging.INFO) global_config_override = {} for label, value in vars(args).items(): if",
") ) parser.add_argument( \"-i\", \"--iterations\", dest = \"iterations\", type = int, help =",
"sig) try: await NLUBenchmarker.getInstance().runFromConfigFile( args.CONFIG, **global_config_override ) except OSError as e: eprint(\"Error reading",
"supplied configurations before using them.\" ) ) parser.add_argument( \"-v\", \"--verbose\", dest = \"VERBOSE\",",
"the next possible situation (this may take a while, as the\" \" current",
"print( \"Aborting execution in the next possible situation (this may take a while,",
"None: parser = argparse.ArgumentParser(description=\"Benchmark NLU frameworks.\") parser.add_argument( \"-c\", \"--config-file\", dest = \"CONFIG\", type",
"-> None: print( \"Aborting execution in the next possible situation (this may take",
"\"-c\", \"--config-file\", dest = \"CONFIG\", type = str, default = \"config.yml\", help =",
"is not None: global_config_override[label] = value async def main_runner() -> None: def cancel(_sig:",
"in the current working directory.\" \"\\nWARNING: Always verify externally supplied configurations before using",
"\" Defaults to \\\"config.yml\\\" in the current working directory.\" \"\\nWARNING: Always verify externally",
"\"Aborting execution in the next possible situation (this may take a while, as",
"= ( \"Path to the python executable to use instead of the current",
"Prevent various modules from spamming the log logging.getLogger(\"asyncio\").setLevel(logging.INFO) logging.getLogger(\"docker\").setLevel(logging.INFO) logging.getLogger(\"matplotlib\").setLevel(logging.INFO) logging.getLogger(\"snips_nlu\").setLevel(logging.WARNING) logging.getLogger(\"urllib3\").setLevel(logging.INFO) logging.getLogger(\"msrest\").setLevel(logging.INFO)",
"default = \"config.yml\", help = ( \"Path to the configuration file.\" \" Defaults",
"current operation has to finish first).\" ) NLUBenchmarker.getInstance().cancel() loop = asyncio.get_event_loop() for sig",
"= asyncio.get_event_loop() for sig in (SIGINT, SIGTERM): loop.add_signal_handler(sig, cancel, sig) try: await NLUBenchmarker.getInstance().runFromConfigFile(",
"dest = \"iterations\", type = int, help = ( \"The number of iterations",
"True, help = ( \"If set, ignore all sorts of cached data.\" \"",
"# Prevent various modules from spamming the log logging.getLogger(\"asyncio\").setLevel(logging.INFO) logging.getLogger(\"docker\").setLevel(logging.INFO) logging.getLogger(\"matplotlib\").setLevel(logging.INFO) logging.getLogger(\"snips_nlu\").setLevel(logging.WARNING) logging.getLogger(\"urllib3\").setLevel(logging.INFO)",
"\"Path to the python executable to use instead of the current one.\" \"",
"setting in the configuration file.\" ) ) args = parser.parse_args() # Set the",
"to \\\"config.yml\\\" in the current working directory.\" \"\\nWARNING: Always verify externally supplied configurations",
"dest = \"CONFIG\", type = str, default = \"config.yml\", help = ( \"Path",
"Always verify externally supplied configurations before using them.\" ) ) parser.add_argument( \"-i\", \"--iterations\",",
"if args.VERBOSE else logging.INFO) # Prevent various modules from spamming the log logging.getLogger(\"asyncio\").setLevel(logging.INFO)",
") parser.add_argument( \"--ignore-cache\", dest = \"ignore_cache\", action = \"store_const\", const = True, help",
"\"python\", type = str, help = ( \"Path to the python executable to",
"to finish first).\" ) NLUBenchmarker.getInstance().cancel() loop = asyncio.get_event_loop() for sig in (SIGINT, SIGTERM):",
"before using them.\" ) ) parser.add_argument( \"-v\", \"--verbose\", dest = \"VERBOSE\", action =",
"them.\" ) ) parser.add_argument( \"-v\", \"--verbose\", dest = \"VERBOSE\", action = \"store_const\", const",
"corresponding setting in the configuration file.\" ) ) args = parser.parse_args() # Set",
"= \"store_const\", const = True, default = False, help = \"Enable verbose/debug output.\"",
"None: print(*args, file=sys.stderr, **kwargs) def main() -> None: parser = argparse.ArgumentParser(description=\"Benchmark NLU frameworks.\")",
"from signal import SIGINT, SIGTERM import sys from typing import Any import yaml",
"benchmark.\" \" Overrides the corresponding setting in the configuration file.\" ) ) parser.add_argument(",
"default = False, help = \"Enable verbose/debug output.\" ) parser.add_argument( \"-p\", \"--python\", dest",
"first).\" ) NLUBenchmarker.getInstance().cancel() loop = asyncio.get_event_loop() for sig in (SIGINT, SIGTERM): loop.add_signal_handler(sig, cancel,",
"file: {}\".format(e)) except yaml.YAMLError as e: eprint(\"Malformed YAML in the config file: {}\".format(e))",
"argparse.ArgumentParser(description=\"Benchmark NLU frameworks.\") parser.add_argument( \"-c\", \"--config-file\", dest = \"CONFIG\", type = str, default",
"finish first).\" ) NLUBenchmarker.getInstance().cancel() loop = asyncio.get_event_loop() for sig in (SIGINT, SIGTERM): loop.add_signal_handler(sig,",
"(SIGINT, SIGTERM): loop.add_signal_handler(sig, cancel, sig) try: await NLUBenchmarker.getInstance().runFromConfigFile( args.CONFIG, **global_config_override ) except OSError",
") NLUBenchmarker.getInstance().cancel() loop = asyncio.get_event_loop() for sig in (SIGINT, SIGTERM): loop.add_signal_handler(sig, cancel, sig)",
"\"Path to the configuration file.\" \" Defaults to \\\"config.yml\\\" in the current working",
"in the configuration file.\" ) ) parser.add_argument( \"--ignore-cache\", dest = \"ignore_cache\", action =",
"all sorts of cached data.\" \" Overrides the corresponding setting in the configuration",
"cached data.\" \" Overrides the corresponding setting in the configuration file.\" ) )",
"cancel(_sig: int) -> None: print( \"Aborting execution in the next possible situation (this",
"configurations before using them.\" ) ) parser.add_argument( \"-i\", \"--iterations\", dest = \"iterations\", type",
"in the configuration file.\" ) ) args = parser.parse_args() # Set the general",
"\" current operation has to finish first).\" ) NLUBenchmarker.getInstance().cancel() loop = asyncio.get_event_loop() for",
"DEBUG or INFO logging.basicConfig(level = logging.DEBUG if args.VERBOSE else logging.INFO) # Prevent various",
"from .nlu_benchmarker import NLUBenchmarker def eprint(*args: Any, **kwargs: Any) -> None: print(*args, file=sys.stderr,",
".nlu_benchmarker import NLUBenchmarker def eprint(*args: Any, **kwargs: Any) -> None: print(*args, file=sys.stderr, **kwargs)",
"main() -> None: parser = argparse.ArgumentParser(description=\"Benchmark NLU frameworks.\") parser.add_argument( \"-c\", \"--config-file\", dest =",
"help = ( \"The number of iterations to benchmark.\" \" Overrides the corresponding",
"externally supplied configurations before using them.\" ) ) parser.add_argument( \"-i\", \"--iterations\", dest =",
"type = int, help = ( \"The number of iterations to benchmark.\" \"",
"(this may take a while, as the\" \" current operation has to finish",
"**global_config_override ) except OSError as e: eprint(\"Error reading the config file: {}\".format(e)) except",
"verbose/debug output.\" ) parser.add_argument( \"-p\", \"--python\", dest = \"python\", type = str, help",
"import yaml from .nlu_benchmarker import NLUBenchmarker def eprint(*args: Any, **kwargs: Any) -> None:",
"parser.add_argument( \"--ignore-cache\", dest = \"ignore_cache\", action = \"store_const\", const = True, help =",
"= \"config.yml\", help = ( \"Path to the configuration file.\" \" Defaults to",
"= {} for label, value in vars(args).items(): if label.islower() and value is not",
"yaml.YAMLError as e: eprint(\"Malformed YAML in the config file: {}\".format(e)) asyncio.run(main_runner()) if __name__",
"Overrides the corresponding setting in the configuration file.\" ) ) args = parser.parse_args()",
"None: print( \"Aborting execution in the next possible situation (this may take a",
"the corresponding setting in the configuration file.\" ) ) parser.add_argument( \"--ignore-cache\", dest =",
"= True, default = False, help = \"Enable verbose/debug output.\" ) parser.add_argument( \"-p\",",
"except OSError as e: eprint(\"Error reading the config file: {}\".format(e)) except yaml.YAMLError as",
"dest = \"ignore_cache\", action = \"store_const\", const = True, help = ( \"If",
"import argparse import asyncio import logging from signal import SIGINT, SIGTERM import sys",
"as e: eprint(\"Malformed YAML in the config file: {}\".format(e)) asyncio.run(main_runner()) if __name__ ==",
"-> None: parser = argparse.ArgumentParser(description=\"Benchmark NLU frameworks.\") parser.add_argument( \"-c\", \"--config-file\", dest = \"CONFIG\",",
"current one.\" \" Overrides the corresponding setting in the configuration file.\" \"\\nWARNING: Always",
"print(*args, file=sys.stderr, **kwargs) def main() -> None: parser = argparse.ArgumentParser(description=\"Benchmark NLU frameworks.\") parser.add_argument(",
"= str, default = \"config.yml\", help = ( \"Path to the configuration file.\"",
"= False, help = \"Enable verbose/debug output.\" ) parser.add_argument( \"-p\", \"--python\", dest =",
"to use instead of the current one.\" \" Overrides the corresponding setting in",
"try: await NLUBenchmarker.getInstance().runFromConfigFile( args.CONFIG, **global_config_override ) except OSError as e: eprint(\"Error reading the",
"sorts of cached data.\" \" Overrides the corresponding setting in the configuration file.\"",
"{} for label, value in vars(args).items(): if label.islower() and value is not None:",
"Defaults to \\\"config.yml\\\" in the current working directory.\" \"\\nWARNING: Always verify externally supplied",
"= argparse.ArgumentParser(description=\"Benchmark NLU frameworks.\") parser.add_argument( \"-c\", \"--config-file\", dest = \"CONFIG\", type = str,",
"\"--ignore-cache\", dest = \"ignore_cache\", action = \"store_const\", const = True, help = (",
"type = str, default = \"config.yml\", help = ( \"Path to the configuration",
"**kwargs) def main() -> None: parser = argparse.ArgumentParser(description=\"Benchmark NLU frameworks.\") parser.add_argument( \"-c\", \"--config-file\",",
"False, help = \"Enable verbose/debug output.\" ) parser.add_argument( \"-p\", \"--python\", dest = \"python\",",
"NLUBenchmarker def eprint(*args: Any, **kwargs: Any) -> None: print(*args, file=sys.stderr, **kwargs) def main()",
"value in vars(args).items(): if label.islower() and value is not None: global_config_override[label] = value",
") ) parser.add_argument( \"-v\", \"--verbose\", dest = \"VERBOSE\", action = \"store_const\", const =",
"def main() -> None: parser = argparse.ArgumentParser(description=\"Benchmark NLU frameworks.\") parser.add_argument( \"-c\", \"--config-file\", dest",
"file.\" \"\\nWARNING: Always verify externally supplied configurations before using them.\" ) ) parser.add_argument(",
"the config file: {}\".format(e)) except yaml.YAMLError as e: eprint(\"Malformed YAML in the config",
"global_config_override[label] = value async def main_runner() -> None: def cancel(_sig: int) -> None:",
"= \"Enable verbose/debug output.\" ) parser.add_argument( \"-p\", \"--python\", dest = \"python\", type =",
"NLU frameworks.\") parser.add_argument( \"-c\", \"--config-file\", dest = \"CONFIG\", type = str, default =",
"str, help = ( \"Path to the python executable to use instead of",
") args = parser.parse_args() # Set the general log level to DEBUG or",
"may take a while, as the\" \" current operation has to finish first).\"",
"help = ( \"Path to the configuration file.\" \" Defaults to \\\"config.yml\\\" in",
"configuration file.\" \"\\nWARNING: Always verify externally supplied configurations before using them.\" ) )",
") parser.add_argument( \"-p\", \"--python\", dest = \"python\", type = str, help = (",
"the configuration file.\" \" Defaults to \\\"config.yml\\\" in the current working directory.\" \"\\nWARNING:",
"sig in (SIGINT, SIGTERM): loop.add_signal_handler(sig, cancel, sig) try: await NLUBenchmarker.getInstance().runFromConfigFile( args.CONFIG, **global_config_override )",
"**kwargs: Any) -> None: print(*args, file=sys.stderr, **kwargs) def main() -> None: parser =",
"Always verify externally supplied configurations before using them.\" ) ) parser.add_argument( \"-v\", \"--verbose\",",
"type = str, help = ( \"Path to the python executable to use",
"\" Overrides the corresponding setting in the configuration file.\" ) ) parser.add_argument( \"--ignore-cache\",",
"parser.add_argument( \"-v\", \"--verbose\", dest = \"VERBOSE\", action = \"store_const\", const = True, default",
"parser = argparse.ArgumentParser(description=\"Benchmark NLU frameworks.\") parser.add_argument( \"-c\", \"--config-file\", dest = \"CONFIG\", type =",
"while, as the\" \" current operation has to finish first).\" ) NLUBenchmarker.getInstance().cancel() loop",
"from typing import Any import yaml from .nlu_benchmarker import NLUBenchmarker def eprint(*args: Any,",
"\"--python\", dest = \"python\", type = str, help = ( \"Path to the",
"const = True, help = ( \"If set, ignore all sorts of cached",
"logging.DEBUG if args.VERBOSE else logging.INFO) # Prevent various modules from spamming the log",
"modules from spamming the log logging.getLogger(\"asyncio\").setLevel(logging.INFO) logging.getLogger(\"docker\").setLevel(logging.INFO) logging.getLogger(\"matplotlib\").setLevel(logging.INFO) logging.getLogger(\"snips_nlu\").setLevel(logging.WARNING) logging.getLogger(\"urllib3\").setLevel(logging.INFO) logging.getLogger(\"msrest\").setLevel(logging.INFO) global_config_override =",
"Overrides the corresponding setting in the configuration file.\" \"\\nWARNING: Always verify externally supplied",
"parser.add_argument( \"-c\", \"--config-file\", dest = \"CONFIG\", type = str, default = \"config.yml\", help",
"to benchmark.\" \" Overrides the corresponding setting in the configuration file.\" ) )",
"<gh_stars>0 import argparse import asyncio import logging from signal import SIGINT, SIGTERM import",
"None: global_config_override[label] = value async def main_runner() -> None: def cancel(_sig: int) ->",
"action = \"store_const\", const = True, default = False, help = \"Enable verbose/debug",
"various modules from spamming the log logging.getLogger(\"asyncio\").setLevel(logging.INFO) logging.getLogger(\"docker\").setLevel(logging.INFO) logging.getLogger(\"matplotlib\").setLevel(logging.INFO) logging.getLogger(\"snips_nlu\").setLevel(logging.WARNING) logging.getLogger(\"urllib3\").setLevel(logging.INFO) logging.getLogger(\"msrest\").setLevel(logging.INFO) global_config_override",
"value is not None: global_config_override[label] = value async def main_runner() -> None: def",
"\"config.yml\", help = ( \"Path to the configuration file.\" \" Defaults to \\\"config.yml\\\"",
"parser.add_argument( \"-i\", \"--iterations\", dest = \"iterations\", type = int, help = ( \"The",
"operation has to finish first).\" ) NLUBenchmarker.getInstance().cancel() loop = asyncio.get_event_loop() for sig in",
") parser.add_argument( \"-i\", \"--iterations\", dest = \"iterations\", type = int, help = (",
"= ( \"The number of iterations to benchmark.\" \" Overrides the corresponding setting",
"corresponding setting in the configuration file.\" ) ) parser.add_argument( \"--ignore-cache\", dest = \"ignore_cache\",",
"eprint(\"Malformed YAML in the config file: {}\".format(e)) asyncio.run(main_runner()) if __name__ == \"__main__\": main()",
"except yaml.YAMLError as e: eprint(\"Malformed YAML in the config file: {}\".format(e)) asyncio.run(main_runner()) if",
"logging.getLogger(\"asyncio\").setLevel(logging.INFO) logging.getLogger(\"docker\").setLevel(logging.INFO) logging.getLogger(\"matplotlib\").setLevel(logging.INFO) logging.getLogger(\"snips_nlu\").setLevel(logging.WARNING) logging.getLogger(\"urllib3\").setLevel(logging.INFO) logging.getLogger(\"msrest\").setLevel(logging.INFO) global_config_override = {} for label, value in",
"args.CONFIG, **global_config_override ) except OSError as e: eprint(\"Error reading the config file: {}\".format(e))",
"log level to DEBUG or INFO logging.basicConfig(level = logging.DEBUG if args.VERBOSE else logging.INFO)",
"of iterations to benchmark.\" \" Overrides the corresponding setting in the configuration file.\"",
"logging.basicConfig(level = logging.DEBUG if args.VERBOSE else logging.INFO) # Prevent various modules from spamming",
"{}\".format(e)) except yaml.YAMLError as e: eprint(\"Malformed YAML in the config file: {}\".format(e)) asyncio.run(main_runner())",
"label.islower() and value is not None: global_config_override[label] = value async def main_runner() ->",
"\"\\nWARNING: Always verify externally supplied configurations before using them.\" ) ) parser.add_argument( \"-v\",",
"has to finish first).\" ) NLUBenchmarker.getInstance().cancel() loop = asyncio.get_event_loop() for sig in (SIGINT,",
"def main_runner() -> None: def cancel(_sig: int) -> None: print( \"Aborting execution in",
"for label, value in vars(args).items(): if label.islower() and value is not None: global_config_override[label]",
"set, ignore all sorts of cached data.\" \" Overrides the corresponding setting in",
"else logging.INFO) # Prevent various modules from spamming the log logging.getLogger(\"asyncio\").setLevel(logging.INFO) logging.getLogger(\"docker\").setLevel(logging.INFO) logging.getLogger(\"matplotlib\").setLevel(logging.INFO)",
"output.\" ) parser.add_argument( \"-p\", \"--python\", dest = \"python\", type = str, help =",
"python executable to use instead of the current one.\" \" Overrides the corresponding",
"before using them.\" ) ) parser.add_argument( \"-i\", \"--iterations\", dest = \"iterations\", type =",
"= \"VERBOSE\", action = \"store_const\", const = True, default = False, help =",
"global_config_override = {} for label, value in vars(args).items(): if label.islower() and value is",
"parser.add_argument( \"-p\", \"--python\", dest = \"python\", type = str, help = ( \"Path",
"\" Overrides the corresponding setting in the configuration file.\" ) ) args =",
"using them.\" ) ) parser.add_argument( \"-i\", \"--iterations\", dest = \"iterations\", type = int,",
"logging.getLogger(\"urllib3\").setLevel(logging.INFO) logging.getLogger(\"msrest\").setLevel(logging.INFO) global_config_override = {} for label, value in vars(args).items(): if label.islower() and",
"int, help = ( \"The number of iterations to benchmark.\" \" Overrides the",
"directory.\" \"\\nWARNING: Always verify externally supplied configurations before using them.\" ) ) parser.add_argument(",
"help = ( \"If set, ignore all sorts of cached data.\" \" Overrides",
"dest = \"VERBOSE\", action = \"store_const\", const = True, default = False, help",
"True, default = False, help = \"Enable verbose/debug output.\" ) parser.add_argument( \"-p\", \"--python\",",
"the current working directory.\" \"\\nWARNING: Always verify externally supplied configurations before using them.\"",
"import asyncio import logging from signal import SIGINT, SIGTERM import sys from typing",
"def eprint(*args: Any, **kwargs: Any) -> None: print(*args, file=sys.stderr, **kwargs) def main() ->",
"( \"The number of iterations to benchmark.\" \" Overrides the corresponding setting in",
") ) args = parser.parse_args() # Set the general log level to DEBUG",
"and value is not None: global_config_override[label] = value async def main_runner() -> None:",
"the configuration file.\" \"\\nWARNING: Always verify externally supplied configurations before using them.\" )",
"OSError as e: eprint(\"Error reading the config file: {}\".format(e)) except yaml.YAMLError as e:",
"not None: global_config_override[label] = value async def main_runner() -> None: def cancel(_sig: int)",
"the configuration file.\" ) ) parser.add_argument( \"--ignore-cache\", dest = \"ignore_cache\", action = \"store_const\",",
"iterations to benchmark.\" \" Overrides the corresponding setting in the configuration file.\" )",
"( \"Path to the python executable to use instead of the current one.\"",
"in the next possible situation (this may take a while, as the\" \"",
"args.VERBOSE else logging.INFO) # Prevent various modules from spamming the log logging.getLogger(\"asyncio\").setLevel(logging.INFO) logging.getLogger(\"docker\").setLevel(logging.INFO)",
"value async def main_runner() -> None: def cancel(_sig: int) -> None: print( \"Aborting",
"the general log level to DEBUG or INFO logging.basicConfig(level = logging.DEBUG if args.VERBOSE",
"import logging from signal import SIGINT, SIGTERM import sys from typing import Any",
"asyncio.get_event_loop() for sig in (SIGINT, SIGTERM): loop.add_signal_handler(sig, cancel, sig) try: await NLUBenchmarker.getInstance().runFromConfigFile( args.CONFIG,",
"possible situation (this may take a while, as the\" \" current operation has",
"import NLUBenchmarker def eprint(*args: Any, **kwargs: Any) -> None: print(*args, file=sys.stderr, **kwargs) def",
"\" Overrides the corresponding setting in the configuration file.\" \"\\nWARNING: Always verify externally",
"\"store_const\", const = True, default = False, help = \"Enable verbose/debug output.\" )",
"ignore all sorts of cached data.\" \" Overrides the corresponding setting in the",
"the log logging.getLogger(\"asyncio\").setLevel(logging.INFO) logging.getLogger(\"docker\").setLevel(logging.INFO) logging.getLogger(\"matplotlib\").setLevel(logging.INFO) logging.getLogger(\"snips_nlu\").setLevel(logging.WARNING) logging.getLogger(\"urllib3\").setLevel(logging.INFO) logging.getLogger(\"msrest\").setLevel(logging.INFO) global_config_override = {} for label,",
"help = \"Enable verbose/debug output.\" ) parser.add_argument( \"-p\", \"--python\", dest = \"python\", type",
"= int, help = ( \"The number of iterations to benchmark.\" \" Overrides",
"take a while, as the\" \" current operation has to finish first).\" )",
"setting in the configuration file.\" \"\\nWARNING: Always verify externally supplied configurations before using",
"vars(args).items(): if label.islower() and value is not None: global_config_override[label] = value async def",
"const = True, default = False, help = \"Enable verbose/debug output.\" ) parser.add_argument(",
") parser.add_argument( \"-v\", \"--verbose\", dest = \"VERBOSE\", action = \"store_const\", const = True,",
"\"Enable verbose/debug output.\" ) parser.add_argument( \"-p\", \"--python\", dest = \"python\", type = str,",
"NLUBenchmarker.getInstance().cancel() loop = asyncio.get_event_loop() for sig in (SIGINT, SIGTERM): loop.add_signal_handler(sig, cancel, sig) try:",
"the configuration file.\" ) ) args = parser.parse_args() # Set the general log",
"configuration file.\" ) ) args = parser.parse_args() # Set the general log level",
"Overrides the corresponding setting in the configuration file.\" ) ) parser.add_argument( \"--ignore-cache\", dest",
"as e: eprint(\"Error reading the config file: {}\".format(e)) except yaml.YAMLError as e: eprint(\"Malformed",
"asyncio import logging from signal import SIGINT, SIGTERM import sys from typing import",
"dest = \"python\", type = str, help = ( \"Path to the python",
"import sys from typing import Any import yaml from .nlu_benchmarker import NLUBenchmarker def",
"logging.getLogger(\"msrest\").setLevel(logging.INFO) global_config_override = {} for label, value in vars(args).items(): if label.islower() and value",
"SIGINT, SIGTERM import sys from typing import Any import yaml from .nlu_benchmarker import",
"file=sys.stderr, **kwargs) def main() -> None: parser = argparse.ArgumentParser(description=\"Benchmark NLU frameworks.\") parser.add_argument( \"-c\",",
"argparse import asyncio import logging from signal import SIGINT, SIGTERM import sys from",
"from spamming the log logging.getLogger(\"asyncio\").setLevel(logging.INFO) logging.getLogger(\"docker\").setLevel(logging.INFO) logging.getLogger(\"matplotlib\").setLevel(logging.INFO) logging.getLogger(\"snips_nlu\").setLevel(logging.WARNING) logging.getLogger(\"urllib3\").setLevel(logging.INFO) logging.getLogger(\"msrest\").setLevel(logging.INFO) global_config_override = {}",
"\"-v\", \"--verbose\", dest = \"VERBOSE\", action = \"store_const\", const = True, default =",
"execution in the next possible situation (this may take a while, as the\"",
"file.\" ) ) parser.add_argument( \"--ignore-cache\", dest = \"ignore_cache\", action = \"store_const\", const =",
"in the configuration file.\" \"\\nWARNING: Always verify externally supplied configurations before using them.\"",
"verify externally supplied configurations before using them.\" ) ) parser.add_argument( \"-i\", \"--iterations\", dest",
"Any, **kwargs: Any) -> None: print(*args, file=sys.stderr, **kwargs) def main() -> None: parser",
"\"-i\", \"--iterations\", dest = \"iterations\", type = int, help = ( \"The number",
") except OSError as e: eprint(\"Error reading the config file: {}\".format(e)) except yaml.YAMLError",
"frameworks.\") parser.add_argument( \"-c\", \"--config-file\", dest = \"CONFIG\", type = str, default = \"config.yml\",",
"label, value in vars(args).items(): if label.islower() and value is not None: global_config_override[label] =",
"next possible situation (this may take a while, as the\" \" current operation",
"import Any import yaml from .nlu_benchmarker import NLUBenchmarker def eprint(*args: Any, **kwargs: Any)",
"int) -> None: print( \"Aborting execution in the next possible situation (this may",
"action = \"store_const\", const = True, help = ( \"If set, ignore all",
"configuration file.\" \" Defaults to \\\"config.yml\\\" in the current working directory.\" \"\\nWARNING: Always",
"\"--config-file\", dest = \"CONFIG\", type = str, default = \"config.yml\", help = (",
"= logging.DEBUG if args.VERBOSE else logging.INFO) # Prevent various modules from spamming the",
"for sig in (SIGINT, SIGTERM): loop.add_signal_handler(sig, cancel, sig) try: await NLUBenchmarker.getInstance().runFromConfigFile( args.CONFIG, **global_config_override",
"the python executable to use instead of the current one.\" \" Overrides the",
"\"VERBOSE\", action = \"store_const\", const = True, default = False, help = \"Enable",
"args = parser.parse_args() # Set the general log level to DEBUG or INFO",
"\"CONFIG\", type = str, default = \"config.yml\", help = ( \"Path to the",
"if label.islower() and value is not None: global_config_override[label] = value async def main_runner()",
"\"store_const\", const = True, help = ( \"If set, ignore all sorts of",
"parser.parse_args() # Set the general log level to DEBUG or INFO logging.basicConfig(level =",
"using them.\" ) ) parser.add_argument( \"-v\", \"--verbose\", dest = \"VERBOSE\", action = \"store_const\",",
"loop = asyncio.get_event_loop() for sig in (SIGINT, SIGTERM): loop.add_signal_handler(sig, cancel, sig) try: await",
"\"The number of iterations to benchmark.\" \" Overrides the corresponding setting in the",
"the corresponding setting in the configuration file.\" ) ) args = parser.parse_args() #",
"typing import Any import yaml from .nlu_benchmarker import NLUBenchmarker def eprint(*args: Any, **kwargs:",
"use instead of the current one.\" \" Overrides the corresponding setting in the",
"or INFO logging.basicConfig(level = logging.DEBUG if args.VERBOSE else logging.INFO) # Prevent various modules",
"config file: {}\".format(e)) except yaml.YAMLError as e: eprint(\"Malformed YAML in the config file:",
"\\\"config.yml\\\" in the current working directory.\" \"\\nWARNING: Always verify externally supplied configurations before",
"configurations before using them.\" ) ) parser.add_argument( \"-v\", \"--verbose\", dest = \"VERBOSE\", action",
"-> None: def cancel(_sig: int) -> None: print( \"Aborting execution in the next",
"one.\" \" Overrides the corresponding setting in the configuration file.\" \"\\nWARNING: Always verify",
"= ( \"Path to the configuration file.\" \" Defaults to \\\"config.yml\\\" in the",
") ) parser.add_argument( \"--ignore-cache\", dest = \"ignore_cache\", action = \"store_const\", const = True,",
"Set the general log level to DEBUG or INFO logging.basicConfig(level = logging.DEBUG if",
"configuration file.\" ) ) parser.add_argument( \"--ignore-cache\", dest = \"ignore_cache\", action = \"store_const\", const",
"logging from signal import SIGINT, SIGTERM import sys from typing import Any import",
"in vars(args).items(): if label.islower() and value is not None: global_config_override[label] = value async",
"a while, as the\" \" current operation has to finish first).\" ) NLUBenchmarker.getInstance().cancel()",
"signal import SIGINT, SIGTERM import sys from typing import Any import yaml from",
"\"If set, ignore all sorts of cached data.\" \" Overrides the corresponding setting",
"SIGTERM import sys from typing import Any import yaml from .nlu_benchmarker import NLUBenchmarker",
"logging.INFO) # Prevent various modules from spamming the log logging.getLogger(\"asyncio\").setLevel(logging.INFO) logging.getLogger(\"docker\").setLevel(logging.INFO) logging.getLogger(\"matplotlib\").setLevel(logging.INFO) logging.getLogger(\"snips_nlu\").setLevel(logging.WARNING)",
"situation (this may take a while, as the\" \" current operation has to",
"them.\" ) ) parser.add_argument( \"-i\", \"--iterations\", dest = \"iterations\", type = int, help",
"general log level to DEBUG or INFO logging.basicConfig(level = logging.DEBUG if args.VERBOSE else",
"= value async def main_runner() -> None: def cancel(_sig: int) -> None: print(",
"of cached data.\" \" Overrides the corresponding setting in the configuration file.\" )",
"async def main_runner() -> None: def cancel(_sig: int) -> None: print( \"Aborting execution",
"= ( \"If set, ignore all sorts of cached data.\" \" Overrides the",
"e: eprint(\"Error reading the config file: {}\".format(e)) except yaml.YAMLError as e: eprint(\"Malformed YAML",
"await NLUBenchmarker.getInstance().runFromConfigFile( args.CONFIG, **global_config_override ) except OSError as e: eprint(\"Error reading the config",
"of the current one.\" \" Overrides the corresponding setting in the configuration file.\"",
"spamming the log logging.getLogger(\"asyncio\").setLevel(logging.INFO) logging.getLogger(\"docker\").setLevel(logging.INFO) logging.getLogger(\"matplotlib\").setLevel(logging.INFO) logging.getLogger(\"snips_nlu\").setLevel(logging.WARNING) logging.getLogger(\"urllib3\").setLevel(logging.INFO) logging.getLogger(\"msrest\").setLevel(logging.INFO) global_config_override = {} for",
"def cancel(_sig: int) -> None: print( \"Aborting execution in the next possible situation",
"as the\" \" current operation has to finish first).\" ) NLUBenchmarker.getInstance().cancel() loop =",
"the\" \" current operation has to finish first).\" ) NLUBenchmarker.getInstance().cancel() loop = asyncio.get_event_loop()",
"# Set the general log level to DEBUG or INFO logging.basicConfig(level = logging.DEBUG",
"= \"CONFIG\", type = str, default = \"config.yml\", help = ( \"Path to",
"supplied configurations before using them.\" ) ) parser.add_argument( \"-i\", \"--iterations\", dest = \"iterations\",",
"data.\" \" Overrides the corresponding setting in the configuration file.\" ) ) args",
"main_runner() -> None: def cancel(_sig: int) -> None: print( \"Aborting execution in the",
"\"--iterations\", dest = \"iterations\", type = int, help = ( \"The number of",
"= \"store_const\", const = True, help = ( \"If set, ignore all sorts",
"level to DEBUG or INFO logging.basicConfig(level = logging.DEBUG if args.VERBOSE else logging.INFO) #",
"cancel, sig) try: await NLUBenchmarker.getInstance().runFromConfigFile( args.CONFIG, **global_config_override ) except OSError as e: eprint(\"Error",
"\"-p\", \"--python\", dest = \"python\", type = str, help = ( \"Path to",
"setting in the configuration file.\" ) ) parser.add_argument( \"--ignore-cache\", dest = \"ignore_cache\", action",
"eprint(*args: Any, **kwargs: Any) -> None: print(*args, file=sys.stderr, **kwargs) def main() -> None:",
"INFO logging.basicConfig(level = logging.DEBUG if args.VERBOSE else logging.INFO) # Prevent various modules from",
"verify externally supplied configurations before using them.\" ) ) parser.add_argument( \"-v\", \"--verbose\", dest",
"log logging.getLogger(\"asyncio\").setLevel(logging.INFO) logging.getLogger(\"docker\").setLevel(logging.INFO) logging.getLogger(\"matplotlib\").setLevel(logging.INFO) logging.getLogger(\"snips_nlu\").setLevel(logging.WARNING) logging.getLogger(\"urllib3\").setLevel(logging.INFO) logging.getLogger(\"msrest\").setLevel(logging.INFO) global_config_override = {} for label, value",
"the current one.\" \" Overrides the corresponding setting in the configuration file.\" \"\\nWARNING:",
"\"ignore_cache\", action = \"store_const\", const = True, help = ( \"If set, ignore",
"-> None: print(*args, file=sys.stderr, **kwargs) def main() -> None: parser = argparse.ArgumentParser(description=\"Benchmark NLU",
"str, default = \"config.yml\", help = ( \"Path to the configuration file.\" \"",
"number of iterations to benchmark.\" \" Overrides the corresponding setting in the configuration",
"the corresponding setting in the configuration file.\" \"\\nWARNING: Always verify externally supplied configurations",
"\"\\nWARNING: Always verify externally supplied configurations before using them.\" ) ) parser.add_argument( \"-i\",",
"to the configuration file.\" \" Defaults to \\\"config.yml\\\" in the current working directory.\"",
"reading the config file: {}\".format(e)) except yaml.YAMLError as e: eprint(\"Malformed YAML in the",
"file.\" ) ) args = parser.parse_args() # Set the general log level to",
"instead of the current one.\" \" Overrides the corresponding setting in the configuration",
"= True, help = ( \"If set, ignore all sorts of cached data.\"",
"None: def cancel(_sig: int) -> None: print( \"Aborting execution in the next possible",
"working directory.\" \"\\nWARNING: Always verify externally supplied configurations before using them.\" ) )",
"logging.getLogger(\"docker\").setLevel(logging.INFO) logging.getLogger(\"matplotlib\").setLevel(logging.INFO) logging.getLogger(\"snips_nlu\").setLevel(logging.WARNING) logging.getLogger(\"urllib3\").setLevel(logging.INFO) logging.getLogger(\"msrest\").setLevel(logging.INFO) global_config_override = {} for label, value in vars(args).items():",
"= \"python\", type = str, help = ( \"Path to the python executable",
"externally supplied configurations before using them.\" ) ) parser.add_argument( \"-v\", \"--verbose\", dest =",
"corresponding setting in the configuration file.\" \"\\nWARNING: Always verify externally supplied configurations before",
"help = ( \"Path to the python executable to use instead of the",
"= \"iterations\", type = int, help = ( \"The number of iterations to",
"to DEBUG or INFO logging.basicConfig(level = logging.DEBUG if args.VERBOSE else logging.INFO) # Prevent",
"logging.getLogger(\"snips_nlu\").setLevel(logging.WARNING) logging.getLogger(\"urllib3\").setLevel(logging.INFO) logging.getLogger(\"msrest\").setLevel(logging.INFO) global_config_override = {} for label, value in vars(args).items(): if label.islower()",
"( \"If set, ignore all sorts of cached data.\" \" Overrides the corresponding",
"= \"ignore_cache\", action = \"store_const\", const = True, help = ( \"If set,",
"sys from typing import Any import yaml from .nlu_benchmarker import NLUBenchmarker def eprint(*args:",
"import SIGINT, SIGTERM import sys from typing import Any import yaml from .nlu_benchmarker",
"SIGTERM): loop.add_signal_handler(sig, cancel, sig) try: await NLUBenchmarker.getInstance().runFromConfigFile( args.CONFIG, **global_config_override ) except OSError as",
"= str, help = ( \"Path to the python executable to use instead",
"NLUBenchmarker.getInstance().runFromConfigFile( args.CONFIG, **global_config_override ) except OSError as e: eprint(\"Error reading the config file:",
"= parser.parse_args() # Set the general log level to DEBUG or INFO logging.basicConfig(level",
"yaml from .nlu_benchmarker import NLUBenchmarker def eprint(*args: Any, **kwargs: Any) -> None: print(*args,",
"Any) -> None: print(*args, file=sys.stderr, **kwargs) def main() -> None: parser = argparse.ArgumentParser(description=\"Benchmark",
"( \"Path to the configuration file.\" \" Defaults to \\\"config.yml\\\" in the current",
"\"--verbose\", dest = \"VERBOSE\", action = \"store_const\", const = True, default = False,",
"e: eprint(\"Malformed YAML in the config file: {}\".format(e)) asyncio.run(main_runner()) if __name__ == \"__main__\":",
"Any import yaml from .nlu_benchmarker import NLUBenchmarker def eprint(*args: Any, **kwargs: Any) ->",
"in (SIGINT, SIGTERM): loop.add_signal_handler(sig, cancel, sig) try: await NLUBenchmarker.getInstance().runFromConfigFile( args.CONFIG, **global_config_override ) except",
"file.\" \" Defaults to \\\"config.yml\\\" in the current working directory.\" \"\\nWARNING: Always verify",
"loop.add_signal_handler(sig, cancel, sig) try: await NLUBenchmarker.getInstance().runFromConfigFile( args.CONFIG, **global_config_override ) except OSError as e:",
"\"iterations\", type = int, help = ( \"The number of iterations to benchmark.\""
] |
[
"prefix + _pretty_dict(item, indent + 4) for item in value ] return '(%s)'",
"KIND, either express or implied. # See the License for the specific language",
"Unless required by applicable law or agreed to in writing, software # distributed",
"under the License. import os import logging class Logger(object): __instance = None def",
"<reponame>intelkevinputnam/lpot-docs #!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright (c) 2021",
"def _log(self): LOGLEVEL = os.environ.get('LOGLEVEL', 'INFO').upper() self._logger = logging.getLogger() self._logger.handlers.clear() self._logger.setLevel(LOGLEVEL) formatter =",
"# limitations under the License. import os import logging class Logger(object): __instance =",
"Logger().get_logger().fatal(msg, *args, **kwargs) def info(msg, *args, **kwargs): if isinstance(msg, dict): for _, line",
"_pretty_dict(item, indent + 4) for item in value ] return '(%s)' % (','.join(items)",
"= os.environ.get('LOGLEVEL', 'INFO').upper() self._logger = logging.getLogger() self._logger.handlers.clear() self._logger.setLevel(LOGLEVEL) formatter = logging.Formatter( '%(asctime)s [%(levelname)s]",
"* indent) else: return repr(value) level = Logger().get_logger().level DEBUG = logging.DEBUG def log(level,",
"debug(msg, *args, **kwargs): if isinstance(msg, dict): for _, line in enumerate(_pretty_dict(msg).split('\\n')): Logger().get_logger().debug(line, *args,",
"def __new__(cls): if Logger.__instance is None: Logger.__instance = object.__new__(cls) Logger.__instance._log() return Logger.__instance def",
"this file except in compliance with the License. # You may obtain a",
"dict): for _, line in enumerate(_pretty_dict(msg).split('\\n')): Logger().get_logger().log(level, line, *args, **kwargs) else: Logger().get_logger().log(level, msg,",
"'(%s)' % (','.join(items) + '\\n' + ' ' * indent) else: return repr(value)",
"enumerate(_pretty_dict(msg).split('\\n')): Logger().get_logger().fatal(line, *args, **kwargs) else: Logger().get_logger().fatal(msg, *args, **kwargs) def info(msg, *args, **kwargs): if",
"**kwargs) else: Logger().get_logger().error(msg, *args, **kwargs) def fatal(msg, *args, **kwargs): if isinstance(msg, dict): for",
"def fatal(msg, *args, **kwargs): if isinstance(msg, dict): for _, line in enumerate(_pretty_dict(msg).split('\\n')): Logger().get_logger().fatal(line,",
"-*- # # Copyright (c) 2021 Intel Corporation # # Licensed under the",
"ANY KIND, either express or implied. # See the License for the specific",
"(indent + 4) if isinstance(value, dict): items = [ prefix + repr(key) +",
"% (','.join(items) + '\\n' + ' ' * indent) elif isinstance(value, tuple): items",
"msg, *args, **kwargs) def debug(msg, *args, **kwargs): if isinstance(msg, dict): for _, line",
"Logger.__instance._log() return Logger.__instance def _log(self): LOGLEVEL = os.environ.get('LOGLEVEL', 'INFO').upper() self._logger = logging.getLogger() self._logger.handlers.clear()",
"import logging class Logger(object): __instance = None def __new__(cls): if Logger.__instance is None:",
"Logger().get_logger().log(level, msg, *args, **kwargs) def debug(msg, *args, **kwargs): if isinstance(msg, dict): for _,",
"item in value ] return '[%s]' % (','.join(items) + '\\n' + ' '",
"governing permissions and # limitations under the License. import os import logging class",
"**kwargs) else: Logger().get_logger().fatal(msg, *args, **kwargs) def info(msg, *args, **kwargs): if isinstance(msg, dict): for",
"if isinstance(msg, dict): for _, line in enumerate(_pretty_dict(msg).split('\\n')): Logger().get_logger().log(level, line, *args, **kwargs) else:",
"WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See",
"Copyright (c) 2021 Intel Corporation # # Licensed under the Apache License, Version",
"* (indent + 4) if isinstance(value, dict): items = [ prefix + repr(key)",
"*args, **kwargs) else: Logger().get_logger().debug(msg, *args, **kwargs) def error(msg, *args, **kwargs): if isinstance(msg, dict):",
"else: Logger().get_logger().fatal(msg, *args, **kwargs) def info(msg, *args, **kwargs): if isinstance(msg, dict): for _,",
"warning(msg, *args, **kwargs): if isinstance(msg, dict): for _, line in enumerate(_pretty_dict(msg).split('\\n')): Logger().get_logger().warning(line, *args,",
"= logging.DEBUG def log(level, msg, *args, **kwargs): if isinstance(msg, dict): for _, line",
"isinstance(msg, dict): for _, line in enumerate(_pretty_dict(msg).split('\\n')): Logger().get_logger().info(line, *args, **kwargs) else: Logger().get_logger().info(msg, *args,",
"IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or",
"msg, *args, **kwargs): if isinstance(msg, dict): for _, line in enumerate(_pretty_dict(msg).split('\\n')): Logger().get_logger().log(level, line,",
"in value ] return '(%s)' % (','.join(items) + '\\n' + ' ' *",
"OF ANY KIND, either express or implied. # See the License for the",
"prefix = '\\n' + ' ' * (indent + 4) if isinstance(value, dict):",
"-*- coding: utf-8 -*- # # Copyright (c) 2021 Intel Corporation # #",
"Logger.__instance is None: Logger.__instance = object.__new__(cls) Logger.__instance._log() return Logger.__instance def _log(self): LOGLEVEL =",
"isinstance(value, list): items = [ prefix + _pretty_dict(item, indent + 4) for item",
"*args, **kwargs) else: Logger().get_logger().fatal(msg, *args, **kwargs) def info(msg, *args, **kwargs): if isinstance(msg, dict):",
"logging.Formatter( '%(asctime)s [%(levelname)s] %(message)s', \"%Y-%m-%d %H:%M:%S\") streamHandler = logging.StreamHandler() streamHandler.setFormatter(formatter) self._logger.addHandler(streamHandler) self._logger.propagate =",
"indent) else: return repr(value) level = Logger().get_logger().level DEBUG = logging.DEBUG def log(level, msg,",
"Logger().get_logger().error(msg, *args, **kwargs) def fatal(msg, *args, **kwargs): if isinstance(msg, dict): for _, line",
"enumerate(_pretty_dict(msg).split('\\n')): Logger().get_logger().error(line, *args, **kwargs) else: Logger().get_logger().error(msg, *args, **kwargs) def fatal(msg, *args, **kwargs): if",
"**kwargs) def info(msg, *args, **kwargs): if isinstance(msg, dict): for _, line in enumerate(_pretty_dict(msg).split('\\n')):",
"None: Logger.__instance = object.__new__(cls) Logger.__instance._log() return Logger.__instance def _log(self): LOGLEVEL = os.environ.get('LOGLEVEL', 'INFO').upper()",
"' + _pretty_dict(value[key], indent + 4) for key in value ] return '{%s}'",
"def warn(msg, *args, **kwargs): if isinstance(msg, dict): for _, line in enumerate(_pretty_dict(msg).split('\\n')): Logger().get_logger().warning(line,",
"LOGLEVEL = os.environ.get('LOGLEVEL', 'INFO').upper() self._logger = logging.getLogger() self._logger.handlers.clear() self._logger.setLevel(LOGLEVEL) formatter = logging.Formatter( '%(asctime)s",
"info(msg, *args, **kwargs): if isinstance(msg, dict): for _, line in enumerate(_pretty_dict(msg).split('\\n')): Logger().get_logger().info(line, *args,",
"warn(msg, *args, **kwargs): if isinstance(msg, dict): for _, line in enumerate(_pretty_dict(msg).split('\\n')): Logger().get_logger().warning(line, *args,",
"if isinstance(msg, dict): for _, line in enumerate(_pretty_dict(msg).split('\\n')): Logger().get_logger().warning(line, *args, **kwargs) else: Logger().get_logger().warning(msg,",
"% (','.join(items) + '\\n' + ' ' * indent) elif isinstance(value, list): items",
"+ ' ' * (indent + 4) if isinstance(value, dict): items = [",
"+ 4) for item in value ] return '(%s)' % (','.join(items) + '\\n'",
"+ _pretty_dict(item, indent + 4) for item in value ] return '(%s)' %",
"def error(msg, *args, **kwargs): if isinstance(msg, dict): for _, line in enumerate(_pretty_dict(msg).split('\\n')): Logger().get_logger().error(line,",
"= None def __new__(cls): if Logger.__instance is None: Logger.__instance = object.__new__(cls) Logger.__instance._log() return",
"software # distributed under the License is distributed on an \"AS IS\" BASIS,",
"import os import logging class Logger(object): __instance = None def __new__(cls): if Logger.__instance",
"in enumerate(_pretty_dict(msg).split('\\n')): Logger().get_logger().debug(line, *args, **kwargs) else: Logger().get_logger().debug(msg, *args, **kwargs) def error(msg, *args, **kwargs):",
"Logger().get_logger().warning(msg, *args, **kwargs) def warning(msg, *args, **kwargs): if isinstance(msg, dict): for _, line",
"*args, **kwargs): if isinstance(msg, dict): for _, line in enumerate(_pretty_dict(msg).split('\\n')): Logger().get_logger().fatal(line, *args, **kwargs)",
"[ prefix + _pretty_dict(item, indent + 4) for item in value ] return",
"# # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to",
"**kwargs) def debug(msg, *args, **kwargs): if isinstance(msg, dict): for _, line in enumerate(_pretty_dict(msg).split('\\n')):",
"+ repr(key) + ': ' + _pretty_dict(value[key], indent + 4) for key in",
"**kwargs): if isinstance(msg, dict): for _, line in enumerate(_pretty_dict(msg).split('\\n')): Logger().get_logger().log(level, line, *args, **kwargs)",
"DEBUG = logging.DEBUG def log(level, msg, *args, **kwargs): if isinstance(msg, dict): for _,",
"**kwargs) def fatal(msg, *args, **kwargs): if isinstance(msg, dict): for _, line in enumerate(_pretty_dict(msg).split('\\n')):",
"%H:%M:%S\") streamHandler = logging.StreamHandler() streamHandler.setFormatter(formatter) self._logger.addHandler(streamHandler) self._logger.propagate = False def get_logger(self): return self._logger",
"under the License is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES",
"= False def get_logger(self): return self._logger def _pretty_dict(value, indent=0): prefix = '\\n' +",
"the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law",
"+ '\\n' + ' ' * indent) elif isinstance(value, list): items = [",
"utf-8 -*- # # Copyright (c) 2021 Intel Corporation # # Licensed under",
"_pretty_dict(value, indent=0): prefix = '\\n' + ' ' * (indent + 4) if",
"+ ': ' + _pretty_dict(value[key], indent + 4) for key in value ]",
"\"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express",
"_log(self): LOGLEVEL = os.environ.get('LOGLEVEL', 'INFO').upper() self._logger = logging.getLogger() self._logger.handlers.clear() self._logger.setLevel(LOGLEVEL) formatter = logging.Formatter(",
"items = [ prefix + _pretty_dict(item, indent + 4) for item in value",
"'[%s]' % (','.join(items) + '\\n' + ' ' * indent) elif isinstance(value, tuple):",
"required by applicable law or agreed to in writing, software # distributed under",
"**kwargs): if isinstance(msg, dict): for _, line in enumerate(_pretty_dict(msg).split('\\n')): Logger().get_logger().info(line, *args, **kwargs) else:",
"applicable law or agreed to in writing, software # distributed under the License",
"*args, **kwargs): if isinstance(msg, dict): for _, line in enumerate(_pretty_dict(msg).split('\\n')): Logger().get_logger().error(line, *args, **kwargs)",
"enumerate(_pretty_dict(msg).split('\\n')): Logger().get_logger().log(level, line, *args, **kwargs) else: Logger().get_logger().log(level, msg, *args, **kwargs) def debug(msg, *args,",
"for _, line in enumerate(_pretty_dict(msg).split('\\n')): Logger().get_logger().debug(line, *args, **kwargs) else: Logger().get_logger().debug(msg, *args, **kwargs) def",
"or agreed to in writing, software # distributed under the License is distributed",
"**kwargs): if isinstance(msg, dict): for _, line in enumerate(_pretty_dict(msg).split('\\n')): Logger().get_logger().debug(line, *args, **kwargs) else:",
"False def get_logger(self): return self._logger def _pretty_dict(value, indent=0): prefix = '\\n' + '",
"CONDITIONS OF ANY KIND, either express or implied. # See the License for",
"object.__new__(cls) Logger.__instance._log() return Logger.__instance def _log(self): LOGLEVEL = os.environ.get('LOGLEVEL', 'INFO').upper() self._logger = logging.getLogger()",
"key in value ] return '{%s}' % (','.join(items) + '\\n' + ' '",
"indent + 4) for key in value ] return '{%s}' % (','.join(items) +",
"License. import os import logging class Logger(object): __instance = None def __new__(cls): if",
"**kwargs) def warning(msg, *args, **kwargs): if isinstance(msg, dict): for _, line in enumerate(_pretty_dict(msg).split('\\n')):",
"' ' * indent) elif isinstance(value, list): items = [ prefix + _pretty_dict(item,",
"else: Logger().get_logger().debug(msg, *args, **kwargs) def error(msg, *args, **kwargs): if isinstance(msg, dict): for _,",
"'INFO').upper() self._logger = logging.getLogger() self._logger.handlers.clear() self._logger.setLevel(LOGLEVEL) formatter = logging.Formatter( '%(asctime)s [%(levelname)s] %(message)s', \"%Y-%m-%d",
"under the Apache License, Version 2.0 (the \"License\"); # you may not use",
"writing, software # distributed under the License is distributed on an \"AS IS\"",
"You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 #",
"License. # You may obtain a copy of the License at # #",
"*args, **kwargs) else: Logger().get_logger().warning(msg, *args, **kwargs) def warning(msg, *args, **kwargs): if isinstance(msg, dict):",
"Logger().get_logger().fatal(line, *args, **kwargs) else: Logger().get_logger().fatal(msg, *args, **kwargs) def info(msg, *args, **kwargs): if isinstance(msg,",
"compliance with the License. # You may obtain a copy of the License",
"_, line in enumerate(_pretty_dict(msg).split('\\n')): Logger().get_logger().log(level, line, *args, **kwargs) else: Logger().get_logger().log(level, msg, *args, **kwargs)",
"for the specific language governing permissions and # limitations under the License. import",
"elif isinstance(value, tuple): items = [ prefix + _pretty_dict(item, indent + 4) for",
"(','.join(items) + '\\n' + ' ' * indent) else: return repr(value) level =",
"of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable",
"line in enumerate(_pretty_dict(msg).split('\\n')): Logger().get_logger().error(line, *args, **kwargs) else: Logger().get_logger().error(msg, *args, **kwargs) def fatal(msg, *args,",
"+ '\\n' + ' ' * indent) else: return repr(value) level = Logger().get_logger().level",
"and # limitations under the License. import os import logging class Logger(object): __instance",
"# -*- coding: utf-8 -*- # # Copyright (c) 2021 Intel Corporation #",
"def warning(msg, *args, **kwargs): if isinstance(msg, dict): for _, line in enumerate(_pretty_dict(msg).split('\\n')): Logger().get_logger().warning(line,",
"**kwargs) else: Logger().get_logger().log(level, msg, *args, **kwargs) def debug(msg, *args, **kwargs): if isinstance(msg, dict):",
"if Logger.__instance is None: Logger.__instance = object.__new__(cls) Logger.__instance._log() return Logger.__instance def _log(self): LOGLEVEL",
"formatter = logging.Formatter( '%(asctime)s [%(levelname)s] %(message)s', \"%Y-%m-%d %H:%M:%S\") streamHandler = logging.StreamHandler() streamHandler.setFormatter(formatter) self._logger.addHandler(streamHandler)",
"not use this file except in compliance with the License. # You may",
"level = Logger().get_logger().level DEBUG = logging.DEBUG def log(level, msg, *args, **kwargs): if isinstance(msg,",
"% (','.join(items) + '\\n' + ' ' * indent) else: return repr(value) level",
"*args, **kwargs) else: Logger().get_logger().error(msg, *args, **kwargs) def fatal(msg, *args, **kwargs): if isinstance(msg, dict):",
"'{%s}' % (','.join(items) + '\\n' + ' ' * indent) elif isinstance(value, list):",
"License, Version 2.0 (the \"License\"); # you may not use this file except",
"Corporation # # Licensed under the Apache License, Version 2.0 (the \"License\"); #",
"*args, **kwargs) def info(msg, *args, **kwargs): if isinstance(msg, dict): for _, line in",
"*args, **kwargs): if isinstance(msg, dict): for _, line in enumerate(_pretty_dict(msg).split('\\n')): Logger().get_logger().log(level, line, *args,",
"distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY",
"in value ] return '{%s}' % (','.join(items) + '\\n' + ' ' *",
"' * indent) elif isinstance(value, tuple): items = [ prefix + _pretty_dict(item, indent",
"# you may not use this file except in compliance with the License.",
"%(message)s', \"%Y-%m-%d %H:%M:%S\") streamHandler = logging.StreamHandler() streamHandler.setFormatter(formatter) self._logger.addHandler(streamHandler) self._logger.propagate = False def get_logger(self):",
"_pretty_dict(item, indent + 4) for item in value ] return '[%s]' % (','.join(items)",
"agreed to in writing, software # distributed under the License is distributed on",
"*args, **kwargs) def warn(msg, *args, **kwargs): if isinstance(msg, dict): for _, line in",
"Logger().get_logger().warning(line, *args, **kwargs) else: Logger().get_logger().warning(msg, *args, **kwargs) def warning(msg, *args, **kwargs): if isinstance(msg,",
"= object.__new__(cls) Logger.__instance._log() return Logger.__instance def _log(self): LOGLEVEL = os.environ.get('LOGLEVEL', 'INFO').upper() self._logger =",
"(the \"License\"); # you may not use this file except in compliance with",
"is None: Logger.__instance = object.__new__(cls) Logger.__instance._log() return Logger.__instance def _log(self): LOGLEVEL = os.environ.get('LOGLEVEL',",
"= Logger().get_logger().level DEBUG = logging.DEBUG def log(level, msg, *args, **kwargs): if isinstance(msg, dict):",
"' * indent) elif isinstance(value, list): items = [ prefix + _pretty_dict(item, indent",
"list): items = [ prefix + _pretty_dict(item, indent + 4) for item in",
"line in enumerate(_pretty_dict(msg).split('\\n')): Logger().get_logger().log(level, line, *args, **kwargs) else: Logger().get_logger().log(level, msg, *args, **kwargs) def",
"else: return repr(value) level = Logger().get_logger().level DEBUG = logging.DEBUG def log(level, msg, *args,",
"# Unless required by applicable law or agreed to in writing, software #",
"by applicable law or agreed to in writing, software # distributed under the",
"copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by",
"return '[%s]' % (','.join(items) + '\\n' + ' ' * indent) elif isinstance(value,",
"**kwargs): if isinstance(msg, dict): for _, line in enumerate(_pretty_dict(msg).split('\\n')): Logger().get_logger().fatal(line, *args, **kwargs) else:",
"logging class Logger(object): __instance = None def __new__(cls): if Logger.__instance is None: Logger.__instance",
"Logger().get_logger().level DEBUG = logging.DEBUG def log(level, msg, *args, **kwargs): if isinstance(msg, dict): for",
"*args, **kwargs) def warning(msg, *args, **kwargs): if isinstance(msg, dict): for _, line in",
"indent) elif isinstance(value, list): items = [ prefix + _pretty_dict(item, indent + 4)",
"'\\n' + ' ' * indent) else: return repr(value) level = Logger().get_logger().level DEBUG",
"self._logger.addHandler(streamHandler) self._logger.propagate = False def get_logger(self): return self._logger def _pretty_dict(value, indent=0): prefix =",
"self._logger = logging.getLogger() self._logger.handlers.clear() self._logger.setLevel(LOGLEVEL) formatter = logging.Formatter( '%(asctime)s [%(levelname)s] %(message)s', \"%Y-%m-%d %H:%M:%S\")",
"file except in compliance with the License. # You may obtain a copy",
"limitations under the License. import os import logging class Logger(object): __instance = None",
"Logger().get_logger().log(level, line, *args, **kwargs) else: Logger().get_logger().log(level, msg, *args, **kwargs) def debug(msg, *args, **kwargs):",
"dict): items = [ prefix + repr(key) + ': ' + _pretty_dict(value[key], indent",
"License for the specific language governing permissions and # limitations under the License.",
"4) for item in value ] return '(%s)' % (','.join(items) + '\\n' +",
"_pretty_dict(value[key], indent + 4) for key in value ] return '{%s}' % (','.join(items)",
"to in writing, software # distributed under the License is distributed on an",
"os import logging class Logger(object): __instance = None def __new__(cls): if Logger.__instance is",
"isinstance(msg, dict): for _, line in enumerate(_pretty_dict(msg).split('\\n')): Logger().get_logger().warning(line, *args, **kwargs) else: Logger().get_logger().warning(msg, *args,",
"permissions and # limitations under the License. import os import logging class Logger(object):",
"return Logger.__instance def _log(self): LOGLEVEL = os.environ.get('LOGLEVEL', 'INFO').upper() self._logger = logging.getLogger() self._logger.handlers.clear() self._logger.setLevel(LOGLEVEL)",
"implied. # See the License for the specific language governing permissions and #",
"4) for item in value ] return '[%s]' % (','.join(items) + '\\n' +",
"\"License\"); # you may not use this file except in compliance with the",
"**kwargs) def error(msg, *args, **kwargs): if isinstance(msg, dict): for _, line in enumerate(_pretty_dict(msg).split('\\n')):",
"obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless",
"(','.join(items) + '\\n' + ' ' * indent) elif isinstance(value, tuple): items =",
"Logger().get_logger().info(line, *args, **kwargs) else: Logger().get_logger().info(msg, *args, **kwargs) def warn(msg, *args, **kwargs): if isinstance(msg,",
"*args, **kwargs): if isinstance(msg, dict): for _, line in enumerate(_pretty_dict(msg).split('\\n')): Logger().get_logger().warning(line, *args, **kwargs)",
"tuple): items = [ prefix + _pretty_dict(item, indent + 4) for item in",
"the specific language governing permissions and # limitations under the License. import os",
"or implied. # See the License for the specific language governing permissions and",
"\"%Y-%m-%d %H:%M:%S\") streamHandler = logging.StreamHandler() streamHandler.setFormatter(formatter) self._logger.addHandler(streamHandler) self._logger.propagate = False def get_logger(self): return",
"python # -*- coding: utf-8 -*- # # Copyright (c) 2021 Intel Corporation",
"Apache License, Version 2.0 (the \"License\"); # you may not use this file",
"= logging.Formatter( '%(asctime)s [%(levelname)s] %(message)s', \"%Y-%m-%d %H:%M:%S\") streamHandler = logging.StreamHandler() streamHandler.setFormatter(formatter) self._logger.addHandler(streamHandler) self._logger.propagate",
"Logger().get_logger().debug(msg, *args, **kwargs) def error(msg, *args, **kwargs): if isinstance(msg, dict): for _, line",
"OR CONDITIONS OF ANY KIND, either express or implied. # See the License",
"may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # #",
"line, *args, **kwargs) else: Logger().get_logger().log(level, msg, *args, **kwargs) def debug(msg, *args, **kwargs): if",
"http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing,",
"' * (indent + 4) if isinstance(value, dict): items = [ prefix +",
"**kwargs) def warn(msg, *args, **kwargs): if isinstance(msg, dict): for _, line in enumerate(_pretty_dict(msg).split('\\n')):",
"in writing, software # distributed under the License is distributed on an \"AS",
"logging.StreamHandler() streamHandler.setFormatter(formatter) self._logger.addHandler(streamHandler) self._logger.propagate = False def get_logger(self): return self._logger def _pretty_dict(value, indent=0):",
"# See the License for the specific language governing permissions and # limitations",
"the License is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR",
"items = [ prefix + repr(key) + ': ' + _pretty_dict(value[key], indent +",
"2021 Intel Corporation # # Licensed under the Apache License, Version 2.0 (the",
"= [ prefix + repr(key) + ': ' + _pretty_dict(value[key], indent + 4)",
"*args, **kwargs) else: Logger().get_logger().log(level, msg, *args, **kwargs) def debug(msg, *args, **kwargs): if isinstance(msg,",
"**kwargs) else: Logger().get_logger().warning(msg, *args, **kwargs) def warning(msg, *args, **kwargs): if isinstance(msg, dict): for",
"prefix + repr(key) + ': ' + _pretty_dict(value[key], indent + 4) for key",
"**kwargs): if isinstance(msg, dict): for _, line in enumerate(_pretty_dict(msg).split('\\n')): Logger().get_logger().warning(line, *args, **kwargs) else:",
"the Apache License, Version 2.0 (the \"License\"); # you may not use this",
"you may not use this file except in compliance with the License. #",
"enumerate(_pretty_dict(msg).split('\\n')): Logger().get_logger().debug(line, *args, **kwargs) else: Logger().get_logger().debug(msg, *args, **kwargs) def error(msg, *args, **kwargs): if",
"Logger.__instance def _log(self): LOGLEVEL = os.environ.get('LOGLEVEL', 'INFO').upper() self._logger = logging.getLogger() self._logger.handlers.clear() self._logger.setLevel(LOGLEVEL) formatter",
"value ] return '(%s)' % (','.join(items) + '\\n' + ' ' * indent)",
"dict): for _, line in enumerate(_pretty_dict(msg).split('\\n')): Logger().get_logger().error(line, *args, **kwargs) else: Logger().get_logger().error(msg, *args, **kwargs)",
"dict): for _, line in enumerate(_pretty_dict(msg).split('\\n')): Logger().get_logger().fatal(line, *args, **kwargs) else: Logger().get_logger().fatal(msg, *args, **kwargs)",
"* indent) elif isinstance(value, list): items = [ prefix + _pretty_dict(item, indent +",
"def log(level, msg, *args, **kwargs): if isinstance(msg, dict): for _, line in enumerate(_pretty_dict(msg).split('\\n')):",
"use this file except in compliance with the License. # You may obtain",
"self._logger.setLevel(LOGLEVEL) formatter = logging.Formatter( '%(asctime)s [%(levelname)s] %(message)s', \"%Y-%m-%d %H:%M:%S\") streamHandler = logging.StreamHandler() streamHandler.setFormatter(formatter)",
"' ' * indent) elif isinstance(value, tuple): items = [ prefix + _pretty_dict(item,",
"= [ prefix + _pretty_dict(item, indent + 4) for item in value ]",
"return repr(value) level = Logger().get_logger().level DEBUG = logging.DEBUG def log(level, msg, *args, **kwargs):",
"line in enumerate(_pretty_dict(msg).split('\\n')): Logger().get_logger().warning(line, *args, **kwargs) else: Logger().get_logger().warning(msg, *args, **kwargs) def warning(msg, *args,",
"# Licensed under the Apache License, Version 2.0 (the \"License\"); # you may",
"None def __new__(cls): if Logger.__instance is None: Logger.__instance = object.__new__(cls) Logger.__instance._log() return Logger.__instance",
"_, line in enumerate(_pretty_dict(msg).split('\\n')): Logger().get_logger().warning(line, *args, **kwargs) else: Logger().get_logger().warning(msg, *args, **kwargs) def warning(msg,",
"log(level, msg, *args, **kwargs): if isinstance(msg, dict): for _, line in enumerate(_pretty_dict(msg).split('\\n')): Logger().get_logger().log(level,",
"if isinstance(msg, dict): for _, line in enumerate(_pretty_dict(msg).split('\\n')): Logger().get_logger().error(line, *args, **kwargs) else: Logger().get_logger().error(msg,",
"2.0 (the \"License\"); # you may not use this file except in compliance",
"(','.join(items) + '\\n' + ' ' * indent) elif isinstance(value, list): items =",
"class Logger(object): __instance = None def __new__(cls): if Logger.__instance is None: Logger.__instance =",
"self._logger.propagate = False def get_logger(self): return self._logger def _pretty_dict(value, indent=0): prefix = '\\n'",
"WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the",
"4) for key in value ] return '{%s}' % (','.join(items) + '\\n' +",
"+ 4) for key in value ] return '{%s}' % (','.join(items) + '\\n'",
"# # Unless required by applicable law or agreed to in writing, software",
"express or implied. # See the License for the specific language governing permissions",
"get_logger(self): return self._logger def _pretty_dict(value, indent=0): prefix = '\\n' + ' ' *",
"repr(key) + ': ' + _pretty_dict(value[key], indent + 4) for key in value",
"+ ' ' * indent) elif isinstance(value, list): items = [ prefix +",
"prefix + _pretty_dict(item, indent + 4) for item in value ] return '[%s]'",
"line in enumerate(_pretty_dict(msg).split('\\n')): Logger().get_logger().fatal(line, *args, **kwargs) else: Logger().get_logger().fatal(msg, *args, **kwargs) def info(msg, *args,",
"+ ' ' * indent) elif isinstance(value, tuple): items = [ prefix +",
"specific language governing permissions and # limitations under the License. import os import",
"= logging.StreamHandler() streamHandler.setFormatter(formatter) self._logger.addHandler(streamHandler) self._logger.propagate = False def get_logger(self): return self._logger def _pretty_dict(value,",
"either express or implied. # See the License for the specific language governing",
"else: Logger().get_logger().warning(msg, *args, **kwargs) def warning(msg, *args, **kwargs): if isinstance(msg, dict): for _,",
"os.environ.get('LOGLEVEL', 'INFO').upper() self._logger = logging.getLogger() self._logger.handlers.clear() self._logger.setLevel(LOGLEVEL) formatter = logging.Formatter( '%(asctime)s [%(levelname)s] %(message)s',",
"for _, line in enumerate(_pretty_dict(msg).split('\\n')): Logger().get_logger().fatal(line, *args, **kwargs) else: Logger().get_logger().fatal(msg, *args, **kwargs) def",
"# Copyright (c) 2021 Intel Corporation # # Licensed under the Apache License,",
"Licensed under the Apache License, Version 2.0 (the \"License\"); # you may not",
"an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either",
"+ '\\n' + ' ' * indent) elif isinstance(value, tuple): items = [",
"value ] return '{%s}' % (','.join(items) + '\\n' + ' ' * indent)",
"return '{%s}' % (','.join(items) + '\\n' + ' ' * indent) elif isinstance(value,",
"' ' * indent) else: return repr(value) level = Logger().get_logger().level DEBUG = logging.DEBUG",
"*args, **kwargs) def fatal(msg, *args, **kwargs): if isinstance(msg, dict): for _, line in",
"else: Logger().get_logger().error(msg, *args, **kwargs) def fatal(msg, *args, **kwargs): if isinstance(msg, dict): for _,",
"__instance = None def __new__(cls): if Logger.__instance is None: Logger.__instance = object.__new__(cls) Logger.__instance._log()",
"for _, line in enumerate(_pretty_dict(msg).split('\\n')): Logger().get_logger().log(level, line, *args, **kwargs) else: Logger().get_logger().log(level, msg, *args,",
"isinstance(msg, dict): for _, line in enumerate(_pretty_dict(msg).split('\\n')): Logger().get_logger().fatal(line, *args, **kwargs) else: Logger().get_logger().fatal(msg, *args,",
"the License. # You may obtain a copy of the License at #",
"if isinstance(msg, dict): for _, line in enumerate(_pretty_dict(msg).split('\\n')): Logger().get_logger().debug(line, *args, **kwargs) else: Logger().get_logger().debug(msg,",
"isinstance(msg, dict): for _, line in enumerate(_pretty_dict(msg).split('\\n')): Logger().get_logger().error(line, *args, **kwargs) else: Logger().get_logger().error(msg, *args,",
"if isinstance(msg, dict): for _, line in enumerate(_pretty_dict(msg).split('\\n')): Logger().get_logger().fatal(line, *args, **kwargs) else: Logger().get_logger().fatal(msg,",
"# distributed under the License is distributed on an \"AS IS\" BASIS, #",
"is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF",
"def info(msg, *args, **kwargs): if isinstance(msg, dict): for _, line in enumerate(_pretty_dict(msg).split('\\n')): Logger().get_logger().info(line,",
"*args, **kwargs) else: Logger().get_logger().info(msg, *args, **kwargs) def warn(msg, *args, **kwargs): if isinstance(msg, dict):",
"= '\\n' + ' ' * (indent + 4) if isinstance(value, dict): items",
"[%(levelname)s] %(message)s', \"%Y-%m-%d %H:%M:%S\") streamHandler = logging.StreamHandler() streamHandler.setFormatter(formatter) self._logger.addHandler(streamHandler) self._logger.propagate = False def",
"logging.DEBUG def log(level, msg, *args, **kwargs): if isinstance(msg, dict): for _, line in",
"error(msg, *args, **kwargs): if isinstance(msg, dict): for _, line in enumerate(_pretty_dict(msg).split('\\n')): Logger().get_logger().error(line, *args,",
"Logger().get_logger().info(msg, *args, **kwargs) def warn(msg, *args, **kwargs): if isinstance(msg, dict): for _, line",
"dict): for _, line in enumerate(_pretty_dict(msg).split('\\n')): Logger().get_logger().debug(line, *args, **kwargs) else: Logger().get_logger().debug(msg, *args, **kwargs)",
"isinstance(value, dict): items = [ prefix + repr(key) + ': ' + _pretty_dict(value[key],",
"def debug(msg, *args, **kwargs): if isinstance(msg, dict): for _, line in enumerate(_pretty_dict(msg).split('\\n')): Logger().get_logger().debug(line,",
"line in enumerate(_pretty_dict(msg).split('\\n')): Logger().get_logger().info(line, *args, **kwargs) else: Logger().get_logger().info(msg, *args, **kwargs) def warn(msg, *args,",
"Logger().get_logger().debug(line, *args, **kwargs) else: Logger().get_logger().debug(msg, *args, **kwargs) def error(msg, *args, **kwargs): if isinstance(msg,",
"_, line in enumerate(_pretty_dict(msg).split('\\n')): Logger().get_logger().fatal(line, *args, **kwargs) else: Logger().get_logger().fatal(msg, *args, **kwargs) def info(msg,",
"with the License. # You may obtain a copy of the License at",
"**kwargs): if isinstance(msg, dict): for _, line in enumerate(_pretty_dict(msg).split('\\n')): Logger().get_logger().error(line, *args, **kwargs) else:",
"repr(value) level = Logger().get_logger().level DEBUG = logging.DEBUG def log(level, msg, *args, **kwargs): if",
"def _pretty_dict(value, indent=0): prefix = '\\n' + ' ' * (indent + 4)",
"Logger().get_logger().error(line, *args, **kwargs) else: Logger().get_logger().error(msg, *args, **kwargs) def fatal(msg, *args, **kwargs): if isinstance(msg,",
"'\\n' + ' ' * (indent + 4) if isinstance(value, dict): items =",
"] return '{%s}' % (','.join(items) + '\\n' + ' ' * indent) elif",
"# # Licensed under the Apache License, Version 2.0 (the \"License\"); # you",
"for key in value ] return '{%s}' % (','.join(items) + '\\n' + '",
"item in value ] return '(%s)' % (','.join(items) + '\\n' + ' '",
"indent + 4) for item in value ] return '[%s]' % (','.join(items) +",
"'\\n' + ' ' * indent) elif isinstance(value, tuple): items = [ prefix",
"in enumerate(_pretty_dict(msg).split('\\n')): Logger().get_logger().log(level, line, *args, **kwargs) else: Logger().get_logger().log(level, msg, *args, **kwargs) def debug(msg,",
"indent=0): prefix = '\\n' + ' ' * (indent + 4) if isinstance(value,",
"* indent) elif isinstance(value, tuple): items = [ prefix + _pretty_dict(item, indent +",
"return '(%s)' % (','.join(items) + '\\n' + ' ' * indent) else: return",
"indent) elif isinstance(value, tuple): items = [ prefix + _pretty_dict(item, indent + 4)",
"return self._logger def _pretty_dict(value, indent=0): prefix = '\\n' + ' ' * (indent",
"law or agreed to in writing, software # distributed under the License is",
"the License for the specific language governing permissions and # limitations under the",
"streamHandler = logging.StreamHandler() streamHandler.setFormatter(formatter) self._logger.addHandler(streamHandler) self._logger.propagate = False def get_logger(self): return self._logger def",
"on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,",
"] return '(%s)' % (','.join(items) + '\\n' + ' ' * indent) else:",
"in enumerate(_pretty_dict(msg).split('\\n')): Logger().get_logger().info(line, *args, **kwargs) else: Logger().get_logger().info(msg, *args, **kwargs) def warn(msg, *args, **kwargs):",
"else: Logger().get_logger().info(msg, *args, **kwargs) def warn(msg, *args, **kwargs): if isinstance(msg, dict): for _,",
"for _, line in enumerate(_pretty_dict(msg).split('\\n')): Logger().get_logger().info(line, *args, **kwargs) else: Logger().get_logger().info(msg, *args, **kwargs) def",
"line in enumerate(_pretty_dict(msg).split('\\n')): Logger().get_logger().debug(line, *args, **kwargs) else: Logger().get_logger().debug(msg, *args, **kwargs) def error(msg, *args,",
"_, line in enumerate(_pretty_dict(msg).split('\\n')): Logger().get_logger().info(line, *args, **kwargs) else: Logger().get_logger().info(msg, *args, **kwargs) def warn(msg,",
"dict): for _, line in enumerate(_pretty_dict(msg).split('\\n')): Logger().get_logger().info(line, *args, **kwargs) else: Logger().get_logger().info(msg, *args, **kwargs)",
"def get_logger(self): return self._logger def _pretty_dict(value, indent=0): prefix = '\\n' + ' '",
"[ prefix + repr(key) + ': ' + _pretty_dict(value[key], indent + 4) for",
"for item in value ] return '(%s)' % (','.join(items) + '\\n' + '",
"in compliance with the License. # You may obtain a copy of the",
"for _, line in enumerate(_pretty_dict(msg).split('\\n')): Logger().get_logger().warning(line, *args, **kwargs) else: Logger().get_logger().warning(msg, *args, **kwargs) def",
"License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or",
"# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. #",
"at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed",
"the License. import os import logging class Logger(object): __instance = None def __new__(cls):",
"*args, **kwargs) def debug(msg, *args, **kwargs): if isinstance(msg, dict): for _, line in",
"See the License for the specific language governing permissions and # limitations under",
"language governing permissions and # limitations under the License. import os import logging",
"BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.",
"*args, **kwargs): if isinstance(msg, dict): for _, line in enumerate(_pretty_dict(msg).split('\\n')): Logger().get_logger().debug(line, *args, **kwargs)",
"indent + 4) for item in value ] return '(%s)' % (','.join(items) +",
"a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required",
"# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in",
"isinstance(value, tuple): items = [ prefix + _pretty_dict(item, indent + 4) for item",
"_, line in enumerate(_pretty_dict(msg).split('\\n')): Logger().get_logger().error(line, *args, **kwargs) else: Logger().get_logger().error(msg, *args, **kwargs) def fatal(msg,",
"self._logger def _pretty_dict(value, indent=0): prefix = '\\n' + ' ' * (indent +",
"#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright (c) 2021 Intel",
"in enumerate(_pretty_dict(msg).split('\\n')): Logger().get_logger().fatal(line, *args, **kwargs) else: Logger().get_logger().fatal(msg, *args, **kwargs) def info(msg, *args, **kwargs):",
"coding: utf-8 -*- # # Copyright (c) 2021 Intel Corporation # # Licensed",
"enumerate(_pretty_dict(msg).split('\\n')): Logger().get_logger().warning(line, *args, **kwargs) else: Logger().get_logger().warning(msg, *args, **kwargs) def warning(msg, *args, **kwargs): if",
"'\\n' + ' ' * indent) elif isinstance(value, list): items = [ prefix",
"(c) 2021 Intel Corporation # # Licensed under the Apache License, Version 2.0",
"in enumerate(_pretty_dict(msg).split('\\n')): Logger().get_logger().error(line, *args, **kwargs) else: Logger().get_logger().error(msg, *args, **kwargs) def fatal(msg, *args, **kwargs):",
"if isinstance(msg, dict): for _, line in enumerate(_pretty_dict(msg).split('\\n')): Logger().get_logger().info(line, *args, **kwargs) else: Logger().get_logger().info(msg,",
"__new__(cls): if Logger.__instance is None: Logger.__instance = object.__new__(cls) Logger.__instance._log() return Logger.__instance def _log(self):",
"for item in value ] return '[%s]' % (','.join(items) + '\\n' + '",
"# # Copyright (c) 2021 Intel Corporation # # Licensed under the Apache",
"Version 2.0 (the \"License\"); # you may not use this file except in",
"4) if isinstance(value, dict): items = [ prefix + repr(key) + ': '",
"except in compliance with the License. # You may obtain a copy of",
"*args, **kwargs): if isinstance(msg, dict): for _, line in enumerate(_pretty_dict(msg).split('\\n')): Logger().get_logger().info(line, *args, **kwargs)",
"dict): for _, line in enumerate(_pretty_dict(msg).split('\\n')): Logger().get_logger().warning(line, *args, **kwargs) else: Logger().get_logger().warning(msg, *args, **kwargs)",
"logging.getLogger() self._logger.handlers.clear() self._logger.setLevel(LOGLEVEL) formatter = logging.Formatter( '%(asctime)s [%(levelname)s] %(message)s', \"%Y-%m-%d %H:%M:%S\") streamHandler =",
"else: Logger().get_logger().log(level, msg, *args, **kwargs) def debug(msg, *args, **kwargs): if isinstance(msg, dict): for",
"': ' + _pretty_dict(value[key], indent + 4) for key in value ] return",
"# You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0",
"may not use this file except in compliance with the License. # You",
"License is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS",
"_, line in enumerate(_pretty_dict(msg).split('\\n')): Logger().get_logger().debug(line, *args, **kwargs) else: Logger().get_logger().debug(msg, *args, **kwargs) def error(msg,",
"+ _pretty_dict(value[key], indent + 4) for key in value ] return '{%s}' %",
"isinstance(msg, dict): for _, line in enumerate(_pretty_dict(msg).split('\\n')): Logger().get_logger().log(level, line, *args, **kwargs) else: Logger().get_logger().log(level,",
"' ' * (indent + 4) if isinstance(value, dict): items = [ prefix",
"Intel Corporation # # Licensed under the Apache License, Version 2.0 (the \"License\");",
"+ ' ' * indent) else: return repr(value) level = Logger().get_logger().level DEBUG =",
"fatal(msg, *args, **kwargs): if isinstance(msg, dict): for _, line in enumerate(_pretty_dict(msg).split('\\n')): Logger().get_logger().fatal(line, *args,",
"streamHandler.setFormatter(formatter) self._logger.addHandler(streamHandler) self._logger.propagate = False def get_logger(self): return self._logger def _pretty_dict(value, indent=0): prefix",
"enumerate(_pretty_dict(msg).split('\\n')): Logger().get_logger().info(line, *args, **kwargs) else: Logger().get_logger().info(msg, *args, **kwargs) def warn(msg, *args, **kwargs): if",
"= logging.getLogger() self._logger.handlers.clear() self._logger.setLevel(LOGLEVEL) formatter = logging.Formatter( '%(asctime)s [%(levelname)s] %(message)s', \"%Y-%m-%d %H:%M:%S\") streamHandler",
"**kwargs) else: Logger().get_logger().info(msg, *args, **kwargs) def warn(msg, *args, **kwargs): if isinstance(msg, dict): for",
"**kwargs) else: Logger().get_logger().debug(msg, *args, **kwargs) def error(msg, *args, **kwargs): if isinstance(msg, dict): for",
"isinstance(msg, dict): for _, line in enumerate(_pretty_dict(msg).split('\\n')): Logger().get_logger().debug(line, *args, **kwargs) else: Logger().get_logger().debug(msg, *args,",
"+ 4) if isinstance(value, dict): items = [ prefix + repr(key) + ':",
"in value ] return '[%s]' % (','.join(items) + '\\n' + ' ' *",
"+ _pretty_dict(item, indent + 4) for item in value ] return '[%s]' %",
"*args, **kwargs) def error(msg, *args, **kwargs): if isinstance(msg, dict): for _, line in",
"+ 4) for item in value ] return '[%s]' % (','.join(items) + '\\n'",
"'%(asctime)s [%(levelname)s] %(message)s', \"%Y-%m-%d %H:%M:%S\") streamHandler = logging.StreamHandler() streamHandler.setFormatter(formatter) self._logger.addHandler(streamHandler) self._logger.propagate = False",
"value ] return '[%s]' % (','.join(items) + '\\n' + ' ' * indent)",
"distributed under the License is distributed on an \"AS IS\" BASIS, # WITHOUT",
"Logger(object): __instance = None def __new__(cls): if Logger.__instance is None: Logger.__instance = object.__new__(cls)",
"for _, line in enumerate(_pretty_dict(msg).split('\\n')): Logger().get_logger().error(line, *args, **kwargs) else: Logger().get_logger().error(msg, *args, **kwargs) def",
"if isinstance(value, dict): items = [ prefix + repr(key) + ': ' +",
"] return '[%s]' % (','.join(items) + '\\n' + ' ' * indent) elif",
"Logger.__instance = object.__new__(cls) Logger.__instance._log() return Logger.__instance def _log(self): LOGLEVEL = os.environ.get('LOGLEVEL', 'INFO').upper() self._logger",
"self._logger.handlers.clear() self._logger.setLevel(LOGLEVEL) formatter = logging.Formatter( '%(asctime)s [%(levelname)s] %(message)s', \"%Y-%m-%d %H:%M:%S\") streamHandler = logging.StreamHandler()",
"in enumerate(_pretty_dict(msg).split('\\n')): Logger().get_logger().warning(line, *args, **kwargs) else: Logger().get_logger().warning(msg, *args, **kwargs) def warning(msg, *args, **kwargs):",
"elif isinstance(value, list): items = [ prefix + _pretty_dict(item, indent + 4) for",
"' * indent) else: return repr(value) level = Logger().get_logger().level DEBUG = logging.DEBUG def"
] |
[
"interpretable = keras.layers.Conv2D(filters=parts, kernel_size=1, activation='relu', kernel_initializer=kernel_initializer, kernel_regularizer=kernel_regularizer)(features) shape = interpretable.get_shape().as_list() if routing ==",
"temper=temper, atoms=16, bs=64, idx=1) def compute_entropy(root, backbone='InceptionV3', iter_num=2, activated=True, temper=10.0, atoms=16, routing='DR', finetune=0,",
"= build_model_name(params) inputs, probs, tensor_log = build(num_out, params.model.backbone, params.model.fine, params.routing.type, params.routing.iter_num, params.routing.temper, params.caps.parts,",
"return results def do_adv(root): epsilons = [0.1, 0.2, 0.3] tempers = [0.0, 20.0,",
"voc_parts.build_dataset3(root + 'data', batch_size=32, shape=data_shape) test_model = keras.Model(model.layers[0].input, [model.layers[3].output, model.layers[5].output]) results = []",
"child_pose, child_prob = layers.CapsuleGroups(height=shape[1], width=shape[2], channel=shape[3], atoms=16, method='channel', activation='squash')(interpretable) log.add_hist('child_activation', child_prob) transformed_caps =",
"idx=1) def compute_entropy(root, backbone='InceptionV3', iter_num=2, activated=True, temper=10.0, atoms=16, routing='DR', finetune=0, parts=128, bs=32): model,",
"idx=idx) inputs, probs, log = build(6, backbone, finetune, routing, iter_num, temper, parts, atoms)",
"finetune=0, parts=128, bs=128, idx=1): data_shape = utils.get_shape(backbone) model_dir = get_model_dir(backbone=backbone, log=log, routing=routing, finetune=finetune,",
"'log', backbone=backbone, iter_num=iter_num, temper=temper, atoms=atoms, routing=routing, finetune=finetune, parts=parts, bs=bs) train_set, test_set, info =",
"299, 3) else: data_shape = (224, 224, 3) train_set, test_set, info = voc_parts.build_dataset3(batch_size=params.training.batch_size,",
"log def main(): args, params = config.parse_args() if params.task == 'train': params.dataset.name =",
"outputs=probs, name='x') load_ckpt(model, model_dir) return model, data_shape, model_dir def evaluate_attack(epsilons, root='', log='log', backbone='InceptionV3',",
"inputs, probs, tensor_log = build(num_out, params.model.backbone, params.model.fine, params.routing.type, params.routing.iter_num, params.routing.temper, params.caps.parts, params.caps.atoms )",
"info = voc_parts.build_dataset3(batch_size=params.training.batch_size, shape=data_shape, arch=params.model.backbone) model, tensor_log = build_model(num_out=info.features['label'].num_classes, params=params) trainer = train.Trainer(model,",
"backbone in backbones: print('backbone:', backbone) for parts in parts_list: print('parts:', parts) for method",
"'avg' or routing == 'max': tempers = [-1] for temper in tempers: print('temper:',",
"tempers = [0.0, 20.0, 40.0, 60.0, 80.0] for temper in tempers: print('temper:{}'.format(temper)) compute_entropy(root,",
"os.path.exists(model_dir): raise Exception('model not exist:{}'.format(model_dir)) return model_dir def load_model(backbone, iter_num, temper, atoms=16, log='log',",
"name=model_name) log_model = keras.Model(inputs=inputs, outputs=tensor_log.get_outputs(), name=model_name + '_log') tensor_log.set_model(log_model) loss, optimizer = get_loss_opt(params.routing.type)",
"keras.initializers.he_normal() BASE_NAME = 'ex4_3' def build_model_name(params): model_name = BASE_NAME model_name += '_{}'.format(params.model.backbone) model_name",
"= keras.metrics.CategoricalAccuracy(name='acc_adv') if metric == 'acc': results = attacks.evaluate_model_after_attacks(epsilons, acc_adv, test_set, model, loss,",
"epsilons = [0.1] evaluate_attack(epsilons, root=root, backbone=backbone, metric='success', all_target=all_target, method=method, steps=5, routing=routing, black_box=black_box, parts=parts,",
"if routing == 'DR' or routing == 'EM': model_dir += '_iter{}'.format(iter_num) model_dir +=",
"results def do_adv(root): epsilons = [0.1, 0.2, 0.3] tempers = [0.0, 20.0, 40.0,",
"args, params = config.parse_args() if params.task == 'train': params.dataset.name = 'voc2010' if params.model.backbone",
"shape = interpretable.get_shape().as_list() if routing == 'avg': pool = keras.layers.GlobalAveragePooling2D()(interpretable) output = keras.layers.Dense(num_out)(pool)",
"= attacks.evaluate_attacks_success_rate(epsilons, test_set, model, loss, method=method, steps=steps, label_sparse=False, cost=True, model_src=model_src) return results def",
"build(num_out, params.model.backbone, params.model.fine, params.routing.type, params.routing.iter_num, params.routing.temper, params.caps.parts, params.caps.atoms ) model = keras.Model(inputs=inputs, outputs=probs,",
"arch=params.model.backbone) model, tensor_log = build_model(num_out=info.features['label'].num_classes, params=params) trainer = train.Trainer(model, params, info, tensor_log, finetune=True,",
"atoms=atoms, routing=routing, finetune=finetune, parts=parts, bs=bs) train_set, test_set, info = voc_parts.build_dataset3(root + 'data', batch_size=32,",
"atoms=None, finetune=0, parts=128, bs=32, idx=1): model_dir = '{}/{}/{}_{}_fine{}_part{}_{}'.format(log, dataset, BASE_NAME, backbone, finetune, parts,",
"test_set, model, loss, categories, method=method, steps=steps, label_sparse=False, cost=True, model_src=model_src) else: results = attacks.evaluate_attacks_success_rate(epsilons,",
"bs=32, idx=1): model_dir = '{}/{}/{}_{}_fine{}_part{}_{}'.format(log, dataset, BASE_NAME, backbone, finetune, parts, routing) if routing",
"build(num_out, backbone, fine, routing, iter_num, temper, parts, atoms): log = utils.TensorLog() if backbone",
"for backbone in backbones: print('backbone:', backbone) for parts in parts_list: print('parts:', parts) for",
"model') model_src, data_shape, model_dir = load_model(log=root + log, backbone=backbone, routing=routing, iter_num=iter_num, temper=temper, atoms=atoms,",
"tempers: print('temper:{}'.format(temper)) compute_entropy(root, backbone='InceptionV3', iter_num=2, temper=temper, atoms=16, routing='DR', finetune=0, parts=128, bs=64) if __name__",
"in_shape = (224, 224, 3) base = keras.applications.VGG16(include_top=False, input_shape=in_shape) elif backbone == 'VGG19':",
"for temper in tempers: print('temper:', temper) if all_target: epsilons = [0.1] evaluate_attack(epsilons, root=root,",
"tensor_log def build(num_out, backbone, fine, routing, iter_num, temper, parts, atoms): log = utils.TensorLog()",
"+= '_part{}'.format(params.caps.parts) model_name += '_{}'.format(params.routing.type) if params.routing.type == 'DR' or params.routing.type == 'EM':",
"inputs = keras.Input(in_shape) features = base(inputs) interpretable = keras.layers.Conv2D(filters=parts, kernel_size=1, activation='relu', kernel_initializer=kernel_initializer, kernel_regularizer=kernel_regularizer)(features)",
"= '{}/{}/{}_{}_fine{}_part{}_{}'.format(log, dataset, BASE_NAME, backbone, finetune, parts, routing) if routing == 'DR' or",
"routing='DR', black_box=False, iter_num=10, temper=1.0, atoms=16, parts=128, bs=64, idx=1): model, data_shape, model_dir = load_model(log=root",
"atoms): log = utils.TensorLog() if backbone == 'VGG16': in_shape = (224, 224, 3)",
"manager = tf.train.CheckpointManager(ckpt, model_dir, max_to_keep=3) ckpt.restore(manager.latest_checkpoint) if manager.latest_checkpoint: print(\"Restored from {}\".format(manager.latest_checkpoint)) def get_model_dir(backbone,",
"routing='DR', finetune=0, parts=128, bs=128, idx=1): data_shape = utils.get_shape(backbone) model_dir = get_model_dir(backbone=backbone, log=log, routing=routing,",
"shape=data_shape, arch=params.model.backbone) model, tensor_log = build_model(num_out=info.features['label'].num_classes, params=params) trainer = train.Trainer(model, params, info, tensor_log,",
"finetune=0, parts=128, bs=32): model, data_shape, model_dir = load_model(log=root + 'log', backbone=backbone, iter_num=iter_num, temper=temper,",
"in methods: print('method:', method) if routing == 'avg' or routing == 'max': tempers",
"output = keras.layers.Dense(num_out)(pool) elif routing == 'DR': child_pose, child_prob = layers.CapsuleGroups(height=shape[1], width=shape[2], channel=shape[3],",
"= load_model(log=root + log, backbone=backbone, routing=routing, iter_num=iter_num, temper=temper, atoms=atoms, parts=parts, bs=bs, finetune=finetune, idx=idx)",
"'max': tempers = [-1] for temper in tempers: print('temper:', temper) if all_target: epsilons",
"black_box=black_box, parts=parts, iter_num=2, temper=temper, atoms=16, bs=64, idx=1) def compute_entropy(root, backbone='InceptionV3', iter_num=2, activated=True, temper=10.0,",
"parts, atoms): log = utils.TensorLog() if backbone == 'VGG16': in_shape = (224, 224,",
"224, 3) base = keras.applications.VGG16(include_top=False, input_shape=in_shape) elif backbone == 'VGG19': in_shape = (224,",
"type == 'DR' or type == 'EM': loss = losses.MarginLoss(sparse=False, upper_margin=0.9, bottom_margin=0.1, down_weight=0.5)",
"40.0, 60.0, 80.0] parts_list = [128] all_target = False black_box = False methods",
"label_sparse=False, cost=True, model_src=model_src) elif metric == 'success': if all_target: categories = [i for",
"= keras.Model(model.layers[0].input, [model.layers[3].output, model.layers[5].output]) results = [] for images, labels in test_set: (child_poses,",
"test_model = keras.Model(model.layers[0].input, [model.layers[3].output, model.layers[5].output]) results = [] for images, labels in test_set:",
"backbone, fine, routing, iter_num, temper, parts, atoms): log = utils.TensorLog() if backbone ==",
"1e-4 kernel_regularizer = keras.regularizers.l2(WEIGHT_DECAY) kernel_initializer = keras.initializers.he_normal() BASE_NAME = 'ex4_3' def build_model_name(params): model_name",
"else: for w in layer.weights: if 'kernel' in w.name: r = kernel_regularizer(w) layer.add_loss(lambda:",
"root=root, backbone=backbone, metric='success', all_target=all_target, method=method, steps=5, routing=routing, black_box=black_box, parts=parts, iter_num=2, temper=temper, atoms=16, bs=64,",
"model, data_shape, model_dir = load_model(log=root + 'log', backbone=backbone, iter_num=iter_num, temper=temper, atoms=atoms, routing=routing, finetune=finetune,",
"== 'max': tempers = [-1] for temper in tempers: print('temper:', temper) if all_target:",
"upper_margin=0.9, bottom_margin=0.1, down_weight=0.5) else: loss = keras.losses.CategoricalCrossentropy(from_logits=True) return loss, optimizer def build_model(num_out, params):",
"layer_num = len(base.layers) for i, layer in enumerate(base.layers): if i < layer_num-fine: layer.trainable",
"elif params.task == 'attack': do_adv(os.getcwd()) elif params.task == 'score': compute_entropies(os.getcwd()) def load_ckpt(model, model_dir):",
"do_adv(os.getcwd()) elif params.task == 'score': compute_entropies(os.getcwd()) def load_ckpt(model, model_dir): model.compile(optimizer=keras.optimizers.Adam(0.0001), loss=keras.losses.CategoricalCrossentropy(from_logits=False), metrics=[]) ckpt",
"temper=10.0, atoms=16, routing='DR', finetune=0, parts=128, bs=32): model, data_shape, model_dir = load_model(log=root + 'log',",
"pooling=False, log=log)((transformed_caps, child_prob)) log.add_hist('parent_activation', parent_probs[-1]) output = parent_probs[-1] return inputs, output, log def",
"print('backbone:', backbone) for parts in parts_list: print('parts:', parts) for method in methods: print('method:',",
"down_weight=0.5) else: loss = keras.losses.CategoricalCrossentropy(from_logits=True) return loss, optimizer def build_model(num_out, params): model_name =",
"in_shape = (224, 224, 3) base = keras.applications.ResNet50(include_top=False, input_shape=in_shape) else: in_shape = (299,",
"evaluate_attack(epsilons, root=root, backbone=backbone, metric='success', all_target=all_target, method=method, steps=5, routing=routing, black_box=black_box, parts=parts, iter_num=2, temper=temper, atoms=16,",
"parent_poses, parent_probs, cs = layers.DynamicRouting(num_routing=iter_num, softmax_in=False, temper=temper, activation='squash', pooling=False, log=log)((transformed_caps, child_prob)) log.add_hist('parent_activation', parent_probs[-1])",
"= False else: for w in layer.weights: if 'kernel' in w.name: r =",
"atoms=16, routing='DR', finetune=0, parts=128, bs=32): model, data_shape, model_dir = load_model(log=root + 'log', backbone=backbone,",
"shape=data_shape) test_model = keras.Model(model.layers[0].input, [model.layers[3].output, model.layers[5].output]) results = [] for images, labels in",
"'data', batch_size=32, shape=data_shape) test_model = keras.Model(model.layers[0].input, [model.layers[3].output, model.layers[5].output]) results = [] for images,",
"load_model(log=root + log, backbone=backbone, routing=routing, iter_num=iter_num, temper=temper, atoms=atoms, parts=parts, bs=bs, finetune=finetune, idx=idx) if",
"'DR' for backbone in backbones: print('backbone:', backbone) for parts in parts_list: print('parts:', parts)",
"'_trial{}'.format(str(params.training.idx)) model_name += '_bs{}'.format(str(params.training.batch_size)) if params.dataset.flip: model_name += '_flip' if params.dataset.crop: model_name +=",
"== 'EM': loss = losses.MarginLoss(sparse=False, upper_margin=0.9, bottom_margin=0.1, down_weight=0.5) else: loss = keras.losses.CategoricalCrossentropy(from_logits=True) return",
"print(\"Restored from {}\".format(manager.latest_checkpoint)) def get_model_dir(backbone, log='log', routing='avg', dataset='voc2010', iter_num=None, temper=None, atoms=None, finetune=0, parts=128,",
"False else: for w in layer.weights: if 'kernel' in w.name: r = kernel_regularizer(w)",
"as tf tf.get_logger().setLevel('ERROR') from tensorflow import keras from common.inputs.voc2010 import voc_parts from common",
"def main(): args, params = config.parse_args() if params.task == 'train': params.dataset.name = 'voc2010'",
"model_dir def load_model(backbone, iter_num, temper, atoms=16, log='log', routing='DR', finetune=0, parts=128, bs=128, idx=1): data_shape",
"np.concatenate(results, 0) mean = np.mean(results) std = np.std(results) print('{:.4}/{:.3}'.format(mean, std)) def compute_entropies(root): tempers",
"categories = [i for i in range(6)] results = attacks.evaluate_attacks_success_rate_all_target(epsilons, test_set, model, loss,",
"box source model') model_src, data_shape, model_dir = load_model(log=root + log, backbone=backbone, routing=routing, iter_num=iter_num,",
"model = keras.Model(inputs=inputs, outputs=probs, name='x') load_ckpt(model, model_dir) return model, data_shape, model_dir def evaluate_attack(epsilons,",
"= ['InceptionV3'] routing = 'DR' for backbone in backbones: print('backbone:', backbone) for parts",
"= build(6, backbone, finetune, routing, iter_num, temper, parts, atoms) model = keras.Model(inputs=inputs, outputs=probs,",
"model = keras.Model(inputs=inputs, outputs=probs, name=model_name) log_model = keras.Model(inputs=inputs, outputs=tensor_log.get_outputs(), name=model_name + '_log') tensor_log.set_model(log_model)",
"elif routing == 'DR': child_pose, child_prob = layers.CapsuleGroups(height=shape[1], width=shape[2], channel=shape[3], atoms=16, method='channel', activation='squash')(interpretable)",
"if i < layer_num-fine: layer.trainable = False else: for w in layer.weights: if",
"'data', batch_size=32, shape=data_shape) acc_adv = keras.metrics.CategoricalAccuracy(name='acc_adv') if metric == 'acc': results = attacks.evaluate_model_after_attacks(epsilons,",
"exist:{}'.format(model_dir)) return model_dir def load_model(backbone, iter_num, temper, atoms=16, log='log', routing='DR', finetune=0, parts=128, bs=128,",
"child_prob) transformed_caps = layers.CapsuleTransformDense(num_out=num_out, out_atom=atoms, share_weights=False, initializer=keras.initializers.glorot_normal(), regularizer=kernel_regularizer)(child_pose) parent_poses, parent_probs, cs = layers.DynamicRouting(num_routing=iter_num,",
"params.dataset.crop: model_name += '_crop' return model_name def get_loss_opt(type): optimizer = keras.optimizers.Adam(0.0001) if type",
"log=log, routing=routing, finetune=finetune, parts=parts, bs=bs, iter_num=iter_num, temper=temper, atoms=atoms, idx=idx) inputs, probs, log =",
"atoms=16, bs=64, idx=1) def compute_entropy(root, backbone='InceptionV3', iter_num=2, activated=True, temper=10.0, atoms=16, routing='DR', finetune=0, parts=128,",
"temper) if all_target: epsilons = [0.1] evaluate_attack(epsilons, root=root, backbone=backbone, metric='success', all_target=all_target, method=method, steps=5,",
"params.task == 'score': compute_entropies(os.getcwd()) def load_ckpt(model, model_dir): model.compile(optimizer=keras.optimizers.Adam(0.0001), loss=keras.losses.CategoricalCrossentropy(from_logits=False), metrics=[]) ckpt = tf.train.Checkpoint(optimizer=model.optimizer,",
"layer in enumerate(base.layers): if i < layer_num-fine: layer.trainable = False else: for w",
"get_loss_opt(routing) _, test_set, info = voc_parts.build_dataset3(root + 'data', batch_size=32, shape=data_shape) acc_adv = keras.metrics.CategoricalAccuracy(name='acc_adv')",
"parent_probs, cs) = test_model(images) c = cs[-1] if activated: entropy = activated_entropy(c, child_probs)",
"main(): args, params = config.parse_args() if params.task == 'train': params.dataset.name = 'voc2010' if",
"[] return model, tensor_log def build(num_out, backbone, fine, routing, iter_num, temper, parts, atoms):",
"r) inputs = keras.Input(in_shape) features = base(inputs) interpretable = keras.layers.Conv2D(filters=parts, kernel_size=1, activation='relu', kernel_initializer=kernel_initializer,",
"model_dir = get_model_dir(backbone=backbone, log=log, routing=routing, finetune=finetune, parts=parts, bs=bs, iter_num=iter_num, temper=temper, atoms=atoms, idx=idx) inputs,",
"80.0] for temper in tempers: print('temper:{}'.format(temper)) compute_entropy(root, backbone='InceptionV3', iter_num=2, temper=temper, atoms=16, routing='DR', finetune=0,",
"'EM': loss = losses.MarginLoss(sparse=False, upper_margin=0.9, bottom_margin=0.1, down_weight=0.5) else: loss = keras.losses.CategoricalCrossentropy(from_logits=True) return loss,",
"metrics=[]) model.summary() model.callbacks = [] return model, tensor_log def build(num_out, backbone, fine, routing,",
"'kernel' in w.name: r = kernel_regularizer(w) layer.add_loss(lambda: r) inputs = keras.Input(in_shape) features =",
"= [] return model, tensor_log def build(num_out, backbone, fine, routing, iter_num, temper, parts,",
"+ log, backbone=backbone, routing=routing, iter_num=iter_num, temper=temper, atoms=atoms, parts=parts, bs=bs, finetune=finetune, idx=idx) if black_box:",
"bs=32): model, data_shape, model_dir = load_model(log=root + 'log', backbone=backbone, iter_num=iter_num, temper=temper, atoms=atoms, routing=routing,",
"keras.applications.InceptionV3(include_top=False, input_shape=in_shape) elif backbone == 'ResNet50': in_shape = (224, 224, 3) base =",
"temper in tempers: print('temper:{}'.format(temper)) compute_entropy(root, backbone='InceptionV3', iter_num=2, temper=temper, atoms=16, routing='DR', finetune=0, parts=128, bs=64)",
"'_{}'.format(params.model.backbone) model_name += '_fine{}'.format(params.model.fine) model_name += '_part{}'.format(params.caps.parts) model_name += '_{}'.format(params.routing.type) if params.routing.type ==",
"3) base = keras.applications.ResNet50(include_top=False, input_shape=in_shape) else: in_shape = (299, 299, 3) base =",
"model_name += '_trial{}'.format(str(params.training.idx)) model_name += '_bs{}'.format(str(params.training.batch_size)) if params.dataset.flip: model_name += '_flip' if params.dataset.crop:",
"== 'VGG16': in_shape = (224, 224, 3) base = keras.applications.VGG16(include_top=False, input_shape=in_shape) elif backbone",
"tempers = [-1] for temper in tempers: print('temper:', temper) if all_target: epsilons =",
"= 1e-4 kernel_regularizer = keras.regularizers.l2(WEIGHT_DECAY) kernel_initializer = keras.initializers.he_normal() BASE_NAME = 'ex4_3' def build_model_name(params):",
"if params.model.backbone == 'InceptionV3': data_shape = (299, 299, 3) else: data_shape = (224,",
"= voc_parts.build_dataset3(root + 'data', batch_size=32, shape=data_shape) test_model = keras.Model(model.layers[0].input, [model.layers[3].output, model.layers[5].output]) results =",
"params.routing.temper, params.caps.parts, params.caps.atoms ) model = keras.Model(inputs=inputs, outputs=probs, name=model_name) log_model = keras.Model(inputs=inputs, outputs=tensor_log.get_outputs(),",
"'{}/{}/{}_{}_fine{}_part{}_{}'.format(log, dataset, BASE_NAME, backbone, finetune, parts, routing) if routing == 'DR' or routing",
"batch_size=32, shape=data_shape) test_model = keras.Model(model.layers[0].input, [model.layers[3].output, model.layers[5].output]) results = [] for images, labels",
"(299, 299, 3) base = keras.applications.InceptionV3(include_top=False, input_shape=in_shape) elif backbone == 'ResNet50': in_shape =",
"'ex4_3' def build_model_name(params): model_name = BASE_NAME model_name += '_{}'.format(params.model.backbone) model_name += '_fine{}'.format(params.model.fine) model_name",
"def get_loss_opt(type): optimizer = keras.optimizers.Adam(0.0001) if type == 'DR' or type == 'EM':",
"parts=128, bs=128, idx=1): data_shape = utils.get_shape(backbone) model_dir = get_model_dir(backbone=backbone, log=log, routing=routing, finetune=finetune, parts=parts,",
"loss = keras.losses.CategoricalCrossentropy(from_logits=True) return loss, optimizer def build_model(num_out, params): model_name = build_model_name(params) inputs,",
"for method in methods: print('method:', method) if routing == 'avg' or routing ==",
"= interpretable.get_shape().as_list() if routing == 'avg': pool = keras.layers.GlobalAveragePooling2D()(interpretable) output = keras.layers.Dense(num_out)(pool) elif",
"layer.trainable = False else: for w in layer.weights: if 'kernel' in w.name: r",
"label_sparse=False, cost=True, model_src=model_src) else: results = attacks.evaluate_attacks_success_rate(epsilons, test_set, model, loss, method=method, steps=steps, label_sparse=False,",
"BASE_NAME = 'ex4_3' def build_model_name(params): model_name = BASE_NAME model_name += '_{}'.format(params.model.backbone) model_name +=",
"finetune=finetune, parts=parts, bs=bs) train_set, test_set, info = voc_parts.build_dataset3(root + 'data', batch_size=32, shape=data_shape) test_model",
"test_set, info = voc_parts.build_dataset3(batch_size=params.training.batch_size, shape=data_shape, arch=params.model.backbone) model, tensor_log = build_model(num_out=info.features['label'].num_classes, params=params) trainer =",
"model_src=model_src) else: results = attacks.evaluate_attacks_success_rate(epsilons, test_set, model, loss, method=method, steps=steps, label_sparse=False, cost=True, model_src=model_src)",
"'avg': pool = keras.layers.GlobalAveragePooling2D()(interpretable) output = keras.layers.Dense(num_out)(pool) elif routing == 'max': pool =",
"build_model_name(params) inputs, probs, tensor_log = build(num_out, params.model.backbone, params.model.fine, params.routing.type, params.routing.iter_num, params.routing.temper, params.caps.parts, params.caps.atoms",
"in backbones: print('backbone:', backbone) for parts in parts_list: print('parts:', parts) for method in",
"'_iter{}'.format(iter_num) model_dir += '_temper{}'.format(temper) model_dir += '_atoms{}'.format(atoms) model_dir += '_trial{}_bs{}_flip_crop'.format(idx, bs) if not",
"activated=True, temper=10.0, atoms=16, routing='DR', finetune=0, parts=128, bs=32): model, data_shape, model_dir = load_model(log=root +",
"= test_model(images) c = cs[-1] if activated: entropy = activated_entropy(c, child_probs) else: entropy",
"'DR' or params.routing.type == 'EM': model_name += '_iter{}'.format(params.routing.iter_num) model_name += '_temper{}'.format(params.routing.temper) model_name +=",
"iter_num=iter_num, temper=temper, atoms=atoms, parts=parts, bs=bs, finetune=finetune, idx=2) else: model_src = model loss, _",
"'FGSM'] backbones = ['InceptionV3'] routing = 'DR' for backbone in backbones: print('backbone:', backbone)",
"def compute_entropy(root, backbone='InceptionV3', iter_num=2, activated=True, temper=10.0, atoms=16, routing='DR', finetune=0, parts=128, bs=32): model, data_shape,",
"output = keras.layers.Dense(num_out)(pool) elif routing == 'max': pool = keras.layers.GlobalMaxPooling2D()(interpretable) output = keras.layers.Dense(num_out)(pool)",
"backbone=backbone, iter_num=iter_num, temper=temper, atoms=atoms, routing=routing, finetune=finetune, parts=parts, bs=bs) train_set, test_set, info = voc_parts.build_dataset3(root",
"= np.mean(results) std = np.std(results) print('{:.4}/{:.3}'.format(mean, std)) def compute_entropies(root): tempers = [0.0, 20.0,",
"'_part{}'.format(params.caps.parts) model_name += '_{}'.format(params.routing.type) if params.routing.type == 'DR' or params.routing.type == 'EM': model_name",
"keras.applications.ResNet50(include_top=False, input_shape=in_shape) else: in_shape = (299, 299, 3) base = keras.applications.InceptionV3(include_top=False, input_shape=in_shape) layer_num",
"= base(inputs) interpretable = keras.layers.Conv2D(filters=parts, kernel_size=1, activation='relu', kernel_initializer=kernel_initializer, kernel_regularizer=kernel_regularizer)(features) shape = interpretable.get_shape().as_list() if",
"parts=parts, bs=bs) train_set, test_set, info = voc_parts.build_dataset3(root + 'data', batch_size=32, shape=data_shape) test_model =",
"iter_num=2, temper=temper, atoms=16, bs=64, idx=1) def compute_entropy(root, backbone='InceptionV3', iter_num=2, activated=True, temper=10.0, atoms=16, routing='DR',",
"= 'DR' for backbone in backbones: print('backbone:', backbone) for parts in parts_list: print('parts:',",
"tensorflow as tf tf.get_logger().setLevel('ERROR') from tensorflow import keras from common.inputs.voc2010 import voc_parts from",
"layers, losses, utils, train, attacks from common.ops.routing import activated_entropy, coupling_entropy import numpy as",
"data_shape = (224, 224, 3) train_set, test_set, info = voc_parts.build_dataset3(batch_size=params.training.batch_size, shape=data_shape, arch=params.model.backbone) model,",
"= [i for i in range(6)] results = attacks.evaluate_attacks_success_rate_all_target(epsilons, test_set, model, loss, categories,",
"or routing == 'EM': model_dir += '_iter{}'.format(iter_num) model_dir += '_temper{}'.format(temper) model_dir += '_atoms{}'.format(atoms)",
"'VGG19': in_shape = (224, 224, 3) base = keras.applications.VGG19(include_top=False, input_shape=in_shape) elif backbone ==",
"ckpt = tf.train.Checkpoint(optimizer=model.optimizer, net=model) manager = tf.train.CheckpointManager(ckpt, model_dir, max_to_keep=3) ckpt.restore(manager.latest_checkpoint) if manager.latest_checkpoint: print(\"Restored",
"if all_target: epsilons = [0.1] evaluate_attack(epsilons, root=root, backbone=backbone, metric='success', all_target=all_target, method=method, steps=5, routing=routing,",
"= keras.Input(in_shape) features = base(inputs) interpretable = keras.layers.Conv2D(filters=parts, kernel_size=1, activation='relu', kernel_initializer=kernel_initializer, kernel_regularizer=kernel_regularizer)(features) shape",
"print('load black box source model') model_src, data_shape, model_dir = load_model(log=root + log, backbone=backbone,",
"temper=temper, activation='squash', pooling=False, log=log)((transformed_caps, child_prob)) log.add_hist('parent_activation', parent_probs[-1]) output = parent_probs[-1] return inputs, output,",
"model, loss, categories, method=method, steps=steps, label_sparse=False, cost=True, model_src=model_src) else: results = attacks.evaluate_attacks_success_rate(epsilons, test_set,",
"routing == 'DR' or routing == 'EM': model_dir += '_iter{}'.format(iter_num) model_dir += '_temper{}'.format(temper)",
"== 'score': compute_entropies(os.getcwd()) def load_ckpt(model, model_dir): model.compile(optimizer=keras.optimizers.Adam(0.0001), loss=keras.losses.CategoricalCrossentropy(from_logits=False), metrics=[]) ckpt = tf.train.Checkpoint(optimizer=model.optimizer, net=model)",
"return model_dir def load_model(backbone, iter_num, temper, atoms=16, log='log', routing='DR', finetune=0, parts=128, bs=128, idx=1):",
"== 'avg': pool = keras.layers.GlobalAveragePooling2D()(interpretable) output = keras.layers.Dense(num_out)(pool) elif routing == 'max': pool",
"= load_model(log=root + log, backbone=backbone, routing=routing, iter_num=iter_num, temper=temper, atoms=atoms, parts=parts, bs=bs, finetune=finetune, idx=2)",
"child_probs) else: entropy = coupling_entropy(c) results.append(entropy) results = np.concatenate(results, 0) mean = np.mean(results)",
"bs=64, idx=1) def compute_entropy(root, backbone='InceptionV3', iter_num=2, activated=True, temper=10.0, atoms=16, routing='DR', finetune=0, parts=128, bs=32):",
"= keras.regularizers.l2(WEIGHT_DECAY) kernel_initializer = keras.initializers.he_normal() BASE_NAME = 'ex4_3' def build_model_name(params): model_name = BASE_NAME",
"backbone=backbone, routing=routing, iter_num=iter_num, temper=temper, atoms=atoms, parts=parts, bs=bs, finetune=finetune, idx=2) else: model_src = model",
"losses, utils, train, attacks from common.ops.routing import activated_entropy, coupling_entropy import numpy as np",
"keras from common.inputs.voc2010 import voc_parts from common import layers, losses, utils, train, attacks",
"= layers.CapsuleTransformDense(num_out=num_out, out_atom=atoms, share_weights=False, initializer=keras.initializers.glorot_normal(), regularizer=kernel_regularizer)(child_pose) parent_poses, parent_probs, cs = layers.DynamicRouting(num_routing=iter_num, softmax_in=False, temper=temper,",
"output, log def main(): args, params = config.parse_args() if params.task == 'train': params.dataset.name",
"model, data_shape, model_dir def evaluate_attack(epsilons, root='', log='log', backbone='InceptionV3', metric='acc', all_target=False, method='FGSM', steps=10, finetune=0,",
"print('method:', method) if routing == 'avg' or routing == 'max': tempers = [-1]",
"test_model(images) c = cs[-1] if activated: entropy = activated_entropy(c, child_probs) else: entropy =",
"for w in layer.weights: if 'kernel' in w.name: r = kernel_regularizer(w) layer.add_loss(lambda: r)",
"model_src=model_src) return results def do_adv(root): epsilons = [0.1, 0.2, 0.3] tempers = [0.0,",
"60.0, 80.0] for temper in tempers: print('temper:{}'.format(temper)) compute_entropy(root, backbone='InceptionV3', iter_num=2, temper=temper, atoms=16, routing='DR',",
"loss, method=method, steps=steps, label_sparse=False, cost=True, model_src=model_src) elif metric == 'success': if all_target: categories",
"3) base = keras.applications.VGG19(include_top=False, input_shape=in_shape) elif backbone == 'InceptionV3': in_shape = (299, 299,",
"routing == 'max': tempers = [-1] for temper in tempers: print('temper:', temper) if",
"parts=128, bs=32, idx=1): model_dir = '{}/{}/{}_{}_fine{}_part{}_{}'.format(log, dataset, BASE_NAME, backbone, finetune, parts, routing) if",
"cost=True, model_src=model_src) elif metric == 'success': if all_target: categories = [i for i",
"method=method, steps=5, routing=routing, black_box=black_box, parts=parts, iter_num=2, temper=temper, atoms=16, bs=64, idx=1) def compute_entropy(root, backbone='InceptionV3',",
"[] for images, labels in test_set: (child_poses, child_probs), (parent_poses, parent_probs, cs) = test_model(images)",
"import layers, losses, utils, train, attacks from common.ops.routing import activated_entropy, coupling_entropy import numpy",
"model_name += '_bs{}'.format(str(params.training.batch_size)) if params.dataset.flip: model_name += '_flip' if params.dataset.crop: model_name += '_crop'",
"backbone='InceptionV3', metric='acc', all_target=False, method='FGSM', steps=10, finetune=0, routing='DR', black_box=False, iter_num=10, temper=1.0, atoms=16, parts=128, bs=64,",
"i < layer_num-fine: layer.trainable = False else: for w in layer.weights: if 'kernel'",
"routing == 'avg': pool = keras.layers.GlobalAveragePooling2D()(interpretable) output = keras.layers.Dense(num_out)(pool) elif routing == 'max':",
"+= '_atoms{}'.format(atoms) model_dir += '_trial{}_bs{}_flip_crop'.format(idx, bs) if not os.path.exists(model_dir): raise Exception('model not exist:{}'.format(model_dir))",
"tensor_log = build_model(num_out=info.features['label'].num_classes, params=params) trainer = train.Trainer(model, params, info, tensor_log, finetune=True, inference_label=False, max_save=1)",
"routing == 'max': pool = keras.layers.GlobalMaxPooling2D()(interpretable) output = keras.layers.Dense(num_out)(pool) elif routing == 'DR':",
"out_atom=atoms, share_weights=False, initializer=keras.initializers.glorot_normal(), regularizer=kernel_regularizer)(child_pose) parent_poses, parent_probs, cs = layers.DynamicRouting(num_routing=iter_num, softmax_in=False, temper=temper, activation='squash', pooling=False,",
"in tempers: print('temper:', temper) if all_target: epsilons = [0.1] evaluate_attack(epsilons, root=root, backbone=backbone, metric='success',",
"[0.1] evaluate_attack(epsilons, root=root, backbone=backbone, metric='success', all_target=all_target, method=method, steps=5, routing=routing, black_box=black_box, parts=parts, iter_num=2, temper=temper,",
"= [] for images, labels in test_set: (child_poses, child_probs), (parent_poses, parent_probs, cs) =",
"share_weights=False, initializer=keras.initializers.glorot_normal(), regularizer=kernel_regularizer)(child_pose) parent_poses, parent_probs, cs = layers.DynamicRouting(num_routing=iter_num, softmax_in=False, temper=temper, activation='squash', pooling=False, log=log)((transformed_caps,",
"= [0.0, 20.0, 40.0, 60.0, 80.0] for temper in tempers: print('temper:{}'.format(temper)) compute_entropy(root, backbone='InceptionV3',",
"train.Trainer(model, params, info, tensor_log, finetune=True, inference_label=False, max_save=1) trainer.metrics['accuracy'] = tf.keras.metrics.CategoricalAccuracy(name='accuracy') if args.train: trainer.fit(train_set,",
"iter_num=iter_num, temper=temper, atoms=atoms, parts=parts, bs=bs, finetune=finetune, idx=idx) if black_box: print('load black box source",
"probs, log = build(6, backbone, finetune, routing, iter_num, temper, parts, atoms) model =",
"= get_loss_opt(routing) _, test_set, info = voc_parts.build_dataset3(root + 'data', batch_size=32, shape=data_shape) acc_adv =",
"common.ops.routing import activated_entropy, coupling_entropy import numpy as np import config WEIGHT_DECAY = 1e-4",
"= len(base.layers) for i, layer in enumerate(base.layers): if i < layer_num-fine: layer.trainable =",
"= activated_entropy(c, child_probs) else: entropy = coupling_entropy(c) results.append(entropy) results = np.concatenate(results, 0) mean",
"finetune, routing, iter_num, temper, parts, atoms) model = keras.Model(inputs=inputs, outputs=probs, name='x') load_ckpt(model, model_dir)",
"model, loss, method=method, steps=steps, label_sparse=False, cost=True, model_src=model_src) return results def do_adv(root): epsilons =",
"routing=routing, iter_num=iter_num, temper=temper, atoms=atoms, parts=parts, bs=bs, finetune=finetune, idx=2) else: model_src = model loss,",
"model.summary() model.callbacks = [] return model, tensor_log def build(num_out, backbone, fine, routing, iter_num,",
"backbone='InceptionV3', iter_num=2, activated=True, temper=10.0, atoms=16, routing='DR', finetune=0, parts=128, bs=32): model, data_shape, model_dir =",
"if all_target: categories = [i for i in range(6)] results = attacks.evaluate_attacks_success_rate_all_target(epsilons, test_set,",
"cs) = test_model(images) c = cs[-1] if activated: entropy = activated_entropy(c, child_probs) else:",
"params.model.backbone == 'InceptionV3': data_shape = (299, 299, 3) else: data_shape = (224, 224,",
"keras.Model(inputs=inputs, outputs=tensor_log.get_outputs(), name=model_name + '_log') tensor_log.set_model(log_model) loss, optimizer = get_loss_opt(params.routing.type) model.compile(optimizer=optimizer, loss=loss, metrics=[])",
"backbones: print('backbone:', backbone) for parts in parts_list: print('parts:', parts) for method in methods:",
"= keras.applications.InceptionV3(include_top=False, input_shape=in_shape) layer_num = len(base.layers) for i, layer in enumerate(base.layers): if i",
"print('parts:', parts) for method in methods: print('method:', method) if routing == 'avg' or",
"'acc': results = attacks.evaluate_model_after_attacks(epsilons, acc_adv, test_set, model, loss, method=method, steps=steps, label_sparse=False, cost=True, model_src=model_src)",
"= keras.applications.ResNet50(include_top=False, input_shape=in_shape) else: in_shape = (299, 299, 3) base = keras.applications.InceptionV3(include_top=False, input_shape=in_shape)",
"keras.layers.Dense(num_out)(pool) elif routing == 'DR': child_pose, child_prob = layers.CapsuleGroups(height=shape[1], width=shape[2], channel=shape[3], atoms=16, method='channel',",
"'_fine{}'.format(params.model.fine) model_name += '_part{}'.format(params.caps.parts) model_name += '_{}'.format(params.routing.type) if params.routing.type == 'DR' or params.routing.type",
"load_model(log=root + log, backbone=backbone, routing=routing, iter_num=iter_num, temper=temper, atoms=atoms, parts=parts, bs=bs, finetune=finetune, idx=2) else:",
"steps=steps, label_sparse=False, cost=True, model_src=model_src) elif metric == 'success': if all_target: categories = [i",
"all_target: epsilons = [0.1] evaluate_attack(epsilons, root=root, backbone=backbone, metric='success', all_target=all_target, method=method, steps=5, routing=routing, black_box=black_box,",
"if backbone == 'VGG16': in_shape = (224, 224, 3) base = keras.applications.VGG16(include_top=False, input_shape=in_shape)",
"= kernel_regularizer(w) layer.add_loss(lambda: r) inputs = keras.Input(in_shape) features = base(inputs) interpretable = keras.layers.Conv2D(filters=parts,",
"input_shape=in_shape) elif backbone == 'InceptionV3': in_shape = (299, 299, 3) base = keras.applications.InceptionV3(include_top=False,",
"backbone == 'InceptionV3': in_shape = (299, 299, 3) base = keras.applications.InceptionV3(include_top=False, input_shape=in_shape) elif",
"loss, _ = get_loss_opt(routing) _, test_set, info = voc_parts.build_dataset3(root + 'data', batch_size=32, shape=data_shape)",
"compute_entropies(os.getcwd()) def load_ckpt(model, model_dir): model.compile(optimizer=keras.optimizers.Adam(0.0001), loss=keras.losses.CategoricalCrossentropy(from_logits=False), metrics=[]) ckpt = tf.train.Checkpoint(optimizer=model.optimizer, net=model) manager =",
"routing = 'DR' for backbone in backbones: print('backbone:', backbone) for parts in parts_list:",
"import os import sys sys.path.append(os.getcwd()) import tensorflow as tf tf.get_logger().setLevel('ERROR') from tensorflow import",
"model_name += '_crop' return model_name def get_loss_opt(type): optimizer = keras.optimizers.Adam(0.0001) if type ==",
"log=log)((transformed_caps, child_prob)) log.add_hist('parent_activation', parent_probs[-1]) output = parent_probs[-1] return inputs, output, log def main():",
"attacks.evaluate_attacks_success_rate_all_target(epsilons, test_set, model, loss, categories, method=method, steps=steps, label_sparse=False, cost=True, model_src=model_src) else: results =",
"20.0, 40.0, 60.0, 80.0] parts_list = [128] all_target = False black_box = False",
"+ 'data', batch_size=32, shape=data_shape) acc_adv = keras.metrics.CategoricalAccuracy(name='acc_adv') if metric == 'acc': results =",
"bottom_margin=0.1, down_weight=0.5) else: loss = keras.losses.CategoricalCrossentropy(from_logits=True) return loss, optimizer def build_model(num_out, params): model_name",
"BASE_NAME, backbone, finetune, parts, routing) if routing == 'DR' or routing == 'EM':",
"== 'EM': model_name += '_iter{}'.format(params.routing.iter_num) model_name += '_temper{}'.format(params.routing.temper) model_name += '_atoms{}'.format(params.caps.atoms) model_name +=",
"routing=routing, black_box=black_box, parts=parts, iter_num=2, temper=temper, atoms=16, bs=64, idx=1) def compute_entropy(root, backbone='InceptionV3', iter_num=2, activated=True,",
"model_dir += '_iter{}'.format(iter_num) model_dir += '_temper{}'.format(temper) model_dir += '_atoms{}'.format(atoms) model_dir += '_trial{}_bs{}_flip_crop'.format(idx, bs)",
"= config.parse_args() if params.task == 'train': params.dataset.name = 'voc2010' if params.model.backbone == 'InceptionV3':",
"'max': pool = keras.layers.GlobalMaxPooling2D()(interpretable) output = keras.layers.Dense(num_out)(pool) elif routing == 'DR': child_pose, child_prob",
"all_target=False, method='FGSM', steps=10, finetune=0, routing='DR', black_box=False, iter_num=10, temper=1.0, atoms=16, parts=128, bs=64, idx=1): model,",
"for i in range(6)] results = attacks.evaluate_attacks_success_rate_all_target(epsilons, test_set, model, loss, categories, method=method, steps=steps,",
"np import config WEIGHT_DECAY = 1e-4 kernel_regularizer = keras.regularizers.l2(WEIGHT_DECAY) kernel_initializer = keras.initializers.he_normal() BASE_NAME",
"+ '_log') tensor_log.set_model(log_model) loss, optimizer = get_loss_opt(params.routing.type) model.compile(optimizer=optimizer, loss=loss, metrics=[]) model.summary() model.callbacks =",
"model_name += '_flip' if params.dataset.crop: model_name += '_crop' return model_name def get_loss_opt(type): optimizer",
"layers.DynamicRouting(num_routing=iter_num, softmax_in=False, temper=temper, activation='squash', pooling=False, log=log)((transformed_caps, child_prob)) log.add_hist('parent_activation', parent_probs[-1]) output = parent_probs[-1] return",
"(224, 224, 3) base = keras.applications.VGG19(include_top=False, input_shape=in_shape) elif backbone == 'InceptionV3': in_shape =",
"idx=1): model_dir = '{}/{}/{}_{}_fine{}_part{}_{}'.format(log, dataset, BASE_NAME, backbone, finetune, parts, routing) if routing ==",
"steps=steps, label_sparse=False, cost=True, model_src=model_src) return results def do_adv(root): epsilons = [0.1, 0.2, 0.3]",
"model_dir += '_trial{}_bs{}_flip_crop'.format(idx, bs) if not os.path.exists(model_dir): raise Exception('model not exist:{}'.format(model_dir)) return model_dir",
"0.2, 0.3] tempers = [0.0, 20.0, 40.0, 60.0, 80.0] parts_list = [128] all_target",
"224, 3) base = keras.applications.VGG19(include_top=False, input_shape=in_shape) elif backbone == 'InceptionV3': in_shape = (299,",
"source model') model_src, data_shape, model_dir = load_model(log=root + log, backbone=backbone, routing=routing, iter_num=iter_num, temper=temper,",
"data_shape = (299, 299, 3) else: data_shape = (224, 224, 3) train_set, test_set,",
"def build_model_name(params): model_name = BASE_NAME model_name += '_{}'.format(params.model.backbone) model_name += '_fine{}'.format(params.model.fine) model_name +=",
"tensor_log.set_model(log_model) loss, optimizer = get_loss_opt(params.routing.type) model.compile(optimizer=optimizer, loss=loss, metrics=[]) model.summary() model.callbacks = [] return",
"atoms=16, parts=128, bs=64, idx=1): model, data_shape, model_dir = load_model(log=root + log, backbone=backbone, routing=routing,",
"(224, 224, 3) base = keras.applications.ResNet50(include_top=False, input_shape=in_shape) else: in_shape = (299, 299, 3)",
"'_bs{}'.format(str(params.training.batch_size)) if params.dataset.flip: model_name += '_flip' if params.dataset.crop: model_name += '_crop' return model_name",
"+= '_temper{}'.format(temper) model_dir += '_atoms{}'.format(atoms) model_dir += '_trial{}_bs{}_flip_crop'.format(idx, bs) if not os.path.exists(model_dir): raise",
"= build(num_out, params.model.backbone, params.model.fine, params.routing.type, params.routing.iter_num, params.routing.temper, params.caps.parts, params.caps.atoms ) model = keras.Model(inputs=inputs,",
"layer.weights: if 'kernel' in w.name: r = kernel_regularizer(w) layer.add_loss(lambda: r) inputs = keras.Input(in_shape)",
"parent_probs, cs = layers.DynamicRouting(num_routing=iter_num, softmax_in=False, temper=temper, activation='squash', pooling=False, log=log)((transformed_caps, child_prob)) log.add_hist('parent_activation', parent_probs[-1]) output",
"model_name def get_loss_opt(type): optimizer = keras.optimizers.Adam(0.0001) if type == 'DR' or type ==",
"= keras.initializers.he_normal() BASE_NAME = 'ex4_3' def build_model_name(params): model_name = BASE_NAME model_name += '_{}'.format(params.model.backbone)",
"layers.CapsuleGroups(height=shape[1], width=shape[2], channel=shape[3], atoms=16, method='channel', activation='squash')(interpretable) log.add_hist('child_activation', child_prob) transformed_caps = layers.CapsuleTransformDense(num_out=num_out, out_atom=atoms, share_weights=False,",
"parts=parts, bs=bs, finetune=finetune, idx=2) else: model_src = model loss, _ = get_loss_opt(routing) _,",
"tf tf.get_logger().setLevel('ERROR') from tensorflow import keras from common.inputs.voc2010 import voc_parts from common import",
"build_model(num_out=info.features['label'].num_classes, params=params) trainer = train.Trainer(model, params, info, tensor_log, finetune=True, inference_label=False, max_save=1) trainer.metrics['accuracy'] =",
"bs=bs, finetune=finetune, idx=2) else: model_src = model loss, _ = get_loss_opt(routing) _, test_set,",
"= keras.layers.Conv2D(filters=parts, kernel_size=1, activation='relu', kernel_initializer=kernel_initializer, kernel_regularizer=kernel_regularizer)(features) shape = interpretable.get_shape().as_list() if routing == 'avg':",
"(224, 224, 3) base = keras.applications.VGG16(include_top=False, input_shape=in_shape) elif backbone == 'VGG19': in_shape =",
"BASE_NAME model_name += '_{}'.format(params.model.backbone) model_name += '_fine{}'.format(params.model.fine) model_name += '_part{}'.format(params.caps.parts) model_name += '_{}'.format(params.routing.type)",
"params.caps.atoms ) model = keras.Model(inputs=inputs, outputs=probs, name=model_name) log_model = keras.Model(inputs=inputs, outputs=tensor_log.get_outputs(), name=model_name +",
"['InceptionV3'] routing = 'DR' for backbone in backbones: print('backbone:', backbone) for parts in",
"or routing == 'max': tempers = [-1] for temper in tempers: print('temper:', temper)",
"images, labels in test_set: (child_poses, child_probs), (parent_poses, parent_probs, cs) = test_model(images) c =",
"child_probs), (parent_poses, parent_probs, cs) = test_model(images) c = cs[-1] if activated: entropy =",
"+= '_bs{}'.format(str(params.training.batch_size)) if params.dataset.flip: model_name += '_flip' if params.dataset.crop: model_name += '_crop' return",
"params.routing.iter_num, params.routing.temper, params.caps.parts, params.caps.atoms ) model = keras.Model(inputs=inputs, outputs=probs, name=model_name) log_model = keras.Model(inputs=inputs,",
"3) base = keras.applications.VGG16(include_top=False, input_shape=in_shape) elif backbone == 'VGG19': in_shape = (224, 224,",
"[0.0, 20.0, 40.0, 60.0, 80.0] for temper in tempers: print('temper:{}'.format(temper)) compute_entropy(root, backbone='InceptionV3', iter_num=2,",
"temper in tempers: print('temper:', temper) if all_target: epsilons = [0.1] evaluate_attack(epsilons, root=root, backbone=backbone,",
"'_iter{}'.format(params.routing.iter_num) model_name += '_temper{}'.format(params.routing.temper) model_name += '_atoms{}'.format(params.caps.atoms) model_name += '_trial{}'.format(str(params.training.idx)) model_name += '_bs{}'.format(str(params.training.batch_size))",
"cost=True, model_src=model_src) else: results = attacks.evaluate_attacks_success_rate(epsilons, test_set, model, loss, method=method, steps=steps, label_sparse=False, cost=True,",
"['PGD', 'BIM', 'FGSM'] backbones = ['InceptionV3'] routing = 'DR' for backbone in backbones:",
"= [0.1, 0.2, 0.3] tempers = [0.0, 20.0, 40.0, 60.0, 80.0] parts_list =",
"'_temper{}'.format(params.routing.temper) model_name += '_atoms{}'.format(params.caps.atoms) model_name += '_trial{}'.format(str(params.training.idx)) model_name += '_bs{}'.format(str(params.training.batch_size)) if params.dataset.flip: model_name",
"[0.1, 0.2, 0.3] tempers = [0.0, 20.0, 40.0, 60.0, 80.0] parts_list = [128]",
"method in methods: print('method:', method) if routing == 'avg' or routing == 'max':",
"method=method, steps=steps, label_sparse=False, cost=True, model_src=model_src) return results def do_adv(root): epsilons = [0.1, 0.2,",
"keras.layers.Conv2D(filters=parts, kernel_size=1, activation='relu', kernel_initializer=kernel_initializer, kernel_regularizer=kernel_regularizer)(features) shape = interpretable.get_shape().as_list() if routing == 'avg': pool",
"keras.applications.VGG16(include_top=False, input_shape=in_shape) elif backbone == 'VGG19': in_shape = (224, 224, 3) base =",
"pool = keras.layers.GlobalMaxPooling2D()(interpretable) output = keras.layers.Dense(num_out)(pool) elif routing == 'DR': child_pose, child_prob =",
"299, 3) base = keras.applications.InceptionV3(include_top=False, input_shape=in_shape) elif backbone == 'ResNet50': in_shape = (224,",
"'DR' or routing == 'EM': model_dir += '_iter{}'.format(iter_num) model_dir += '_temper{}'.format(temper) model_dir +=",
"atoms=16, log='log', routing='DR', finetune=0, parts=128, bs=128, idx=1): data_shape = utils.get_shape(backbone) model_dir = get_model_dir(backbone=backbone,",
"model_dir = load_model(log=root + 'log', backbone=backbone, iter_num=iter_num, temper=temper, atoms=atoms, routing=routing, finetune=finetune, parts=parts, bs=bs)",
"iter_num, temper, parts, atoms): log = utils.TensorLog() if backbone == 'VGG16': in_shape =",
"tempers: print('temper:', temper) if all_target: epsilons = [0.1] evaluate_attack(epsilons, root=root, backbone=backbone, metric='success', all_target=all_target,",
"outputs=probs, name=model_name) log_model = keras.Model(inputs=inputs, outputs=tensor_log.get_outputs(), name=model_name + '_log') tensor_log.set_model(log_model) loss, optimizer =",
"{}\".format(manager.latest_checkpoint)) def get_model_dir(backbone, log='log', routing='avg', dataset='voc2010', iter_num=None, temper=None, atoms=None, finetune=0, parts=128, bs=32, idx=1):",
"utils.TensorLog() if backbone == 'VGG16': in_shape = (224, 224, 3) base = keras.applications.VGG16(include_top=False,",
"iter_num, temper, atoms=16, log='log', routing='DR', finetune=0, parts=128, bs=128, idx=1): data_shape = utils.get_shape(backbone) model_dir",
"= keras.applications.InceptionV3(include_top=False, input_shape=in_shape) elif backbone == 'ResNet50': in_shape = (224, 224, 3) base",
"finetune=finetune, parts=parts, bs=bs, iter_num=iter_num, temper=temper, atoms=atoms, idx=idx) inputs, probs, log = build(6, backbone,",
"backbone, finetune, routing, iter_num, temper, parts, atoms) model = keras.Model(inputs=inputs, outputs=probs, name='x') load_ckpt(model,",
"model_dir = load_model(log=root + log, backbone=backbone, routing=routing, iter_num=iter_num, temper=temper, atoms=atoms, parts=parts, bs=bs, finetune=finetune,",
"tf.keras.metrics.CategoricalAccuracy(name='accuracy') if args.train: trainer.fit(train_set, test_set) else: trainer.evaluate(test_set) elif params.task == 'attack': do_adv(os.getcwd()) elif",
"temper=None, atoms=None, finetune=0, parts=128, bs=32, idx=1): model_dir = '{}/{}/{}_{}_fine{}_part{}_{}'.format(log, dataset, BASE_NAME, backbone, finetune,",
"def get_model_dir(backbone, log='log', routing='avg', dataset='voc2010', iter_num=None, temper=None, atoms=None, finetune=0, parts=128, bs=32, idx=1): model_dir",
"entropy = activated_entropy(c, child_probs) else: entropy = coupling_entropy(c) results.append(entropy) results = np.concatenate(results, 0)",
"kernel_regularizer(w) layer.add_loss(lambda: r) inputs = keras.Input(in_shape) features = base(inputs) interpretable = keras.layers.Conv2D(filters=parts, kernel_size=1,",
"= keras.applications.VGG19(include_top=False, input_shape=in_shape) elif backbone == 'InceptionV3': in_shape = (299, 299, 3) base",
"softmax_in=False, temper=temper, activation='squash', pooling=False, log=log)((transformed_caps, child_prob)) log.add_hist('parent_activation', parent_probs[-1]) output = parent_probs[-1] return inputs,",
"utils.get_shape(backbone) model_dir = get_model_dir(backbone=backbone, log=log, routing=routing, finetune=finetune, parts=parts, bs=bs, iter_num=iter_num, temper=temper, atoms=atoms, idx=idx)",
"= build_model(num_out=info.features['label'].num_classes, params=params) trainer = train.Trainer(model, params, info, tensor_log, finetune=True, inference_label=False, max_save=1) trainer.metrics['accuracy']",
"else: in_shape = (299, 299, 3) base = keras.applications.InceptionV3(include_top=False, input_shape=in_shape) layer_num = len(base.layers)",
"elif backbone == 'InceptionV3': in_shape = (299, 299, 3) base = keras.applications.InceptionV3(include_top=False, input_shape=in_shape)",
"model.compile(optimizer=keras.optimizers.Adam(0.0001), loss=keras.losses.CategoricalCrossentropy(from_logits=False), metrics=[]) ckpt = tf.train.Checkpoint(optimizer=model.optimizer, net=model) manager = tf.train.CheckpointManager(ckpt, model_dir, max_to_keep=3) ckpt.restore(manager.latest_checkpoint)",
"transformed_caps = layers.CapsuleTransformDense(num_out=num_out, out_atom=atoms, share_weights=False, initializer=keras.initializers.glorot_normal(), regularizer=kernel_regularizer)(child_pose) parent_poses, parent_probs, cs = layers.DynamicRouting(num_routing=iter_num, softmax_in=False,",
"= (224, 224, 3) base = keras.applications.ResNet50(include_top=False, input_shape=in_shape) else: in_shape = (299, 299,",
"common.inputs.voc2010 import voc_parts from common import layers, losses, utils, train, attacks from common.ops.routing",
"= layers.CapsuleGroups(height=shape[1], width=shape[2], channel=shape[3], atoms=16, method='channel', activation='squash')(interpretable) log.add_hist('child_activation', child_prob) transformed_caps = layers.CapsuleTransformDense(num_out=num_out, out_atom=atoms,",
"Exception('model not exist:{}'.format(model_dir)) return model_dir def load_model(backbone, iter_num, temper, atoms=16, log='log', routing='DR', finetune=0,",
"for temper in tempers: print('temper:{}'.format(temper)) compute_entropy(root, backbone='InceptionV3', iter_num=2, temper=temper, atoms=16, routing='DR', finetune=0, parts=128,",
"base(inputs) interpretable = keras.layers.Conv2D(filters=parts, kernel_size=1, activation='relu', kernel_initializer=kernel_initializer, kernel_regularizer=kernel_regularizer)(features) shape = interpretable.get_shape().as_list() if routing",
"if params.dataset.crop: model_name += '_crop' return model_name def get_loss_opt(type): optimizer = keras.optimizers.Adam(0.0001) if",
"temper, atoms=16, log='log', routing='DR', finetune=0, parts=128, bs=128, idx=1): data_shape = utils.get_shape(backbone) model_dir =",
"False black_box = False methods = ['PGD', 'BIM', 'FGSM'] backbones = ['InceptionV3'] routing",
"False methods = ['PGD', 'BIM', 'FGSM'] backbones = ['InceptionV3'] routing = 'DR' for",
"model, tensor_log = build_model(num_out=info.features['label'].num_classes, params=params) trainer = train.Trainer(model, params, info, tensor_log, finetune=True, inference_label=False,",
"= attacks.evaluate_model_after_attacks(epsilons, acc_adv, test_set, model, loss, method=method, steps=steps, label_sparse=False, cost=True, model_src=model_src) elif metric",
"keras.layers.Dense(num_out)(pool) elif routing == 'max': pool = keras.layers.GlobalMaxPooling2D()(interpretable) output = keras.layers.Dense(num_out)(pool) elif routing",
"keras.Model(inputs=inputs, outputs=probs, name='x') load_ckpt(model, model_dir) return model, data_shape, model_dir def evaluate_attack(epsilons, root='', log='log',",
"else: results = attacks.evaluate_attacks_success_rate(epsilons, test_set, model, loss, method=method, steps=steps, label_sparse=False, cost=True, model_src=model_src) return",
"= get_loss_opt(params.routing.type) model.compile(optimizer=optimizer, loss=loss, metrics=[]) model.summary() model.callbacks = [] return model, tensor_log def",
"print('{:.4}/{:.3}'.format(mean, std)) def compute_entropies(root): tempers = [0.0, 20.0, 40.0, 60.0, 80.0] for temper",
"keras.applications.InceptionV3(include_top=False, input_shape=in_shape) layer_num = len(base.layers) for i, layer in enumerate(base.layers): if i <",
"model_dir def evaluate_attack(epsilons, root='', log='log', backbone='InceptionV3', metric='acc', all_target=False, method='FGSM', steps=10, finetune=0, routing='DR', black_box=False,",
"type == 'EM': loss = losses.MarginLoss(sparse=False, upper_margin=0.9, bottom_margin=0.1, down_weight=0.5) else: loss = keras.losses.CategoricalCrossentropy(from_logits=True)",
"base = keras.applications.ResNet50(include_top=False, input_shape=in_shape) else: in_shape = (299, 299, 3) base = keras.applications.InceptionV3(include_top=False,",
"train_set, test_set, info = voc_parts.build_dataset3(root + 'data', batch_size=32, shape=data_shape) test_model = keras.Model(model.layers[0].input, [model.layers[3].output,",
"'_atoms{}'.format(atoms) model_dir += '_trial{}_bs{}_flip_crop'.format(idx, bs) if not os.path.exists(model_dir): raise Exception('model not exist:{}'.format(model_dir)) return",
"20.0, 40.0, 60.0, 80.0] for temper in tempers: print('temper:{}'.format(temper)) compute_entropy(root, backbone='InceptionV3', iter_num=2, temper=temper,",
"loss = losses.MarginLoss(sparse=False, upper_margin=0.9, bottom_margin=0.1, down_weight=0.5) else: loss = keras.losses.CategoricalCrossentropy(from_logits=True) return loss, optimizer",
"keras.regularizers.l2(WEIGHT_DECAY) kernel_initializer = keras.initializers.he_normal() BASE_NAME = 'ex4_3' def build_model_name(params): model_name = BASE_NAME model_name",
"< layer_num-fine: layer.trainable = False else: for w in layer.weights: if 'kernel' in",
"load_model(log=root + 'log', backbone=backbone, iter_num=iter_num, temper=temper, atoms=atoms, routing=routing, finetune=finetune, parts=parts, bs=bs) train_set, test_set,",
"3) base = keras.applications.InceptionV3(include_top=False, input_shape=in_shape) elif backbone == 'ResNet50': in_shape = (224, 224,",
"tensor_log = build(num_out, params.model.backbone, params.model.fine, params.routing.type, params.routing.iter_num, params.routing.temper, params.caps.parts, params.caps.atoms ) model =",
"labels in test_set: (child_poses, child_probs), (parent_poses, parent_probs, cs) = test_model(images) c = cs[-1]",
"= (224, 224, 3) base = keras.applications.VGG19(include_top=False, input_shape=in_shape) elif backbone == 'InceptionV3': in_shape",
"info, tensor_log, finetune=True, inference_label=False, max_save=1) trainer.metrics['accuracy'] = tf.keras.metrics.CategoricalAccuracy(name='accuracy') if args.train: trainer.fit(train_set, test_set) else:",
"elif params.task == 'score': compute_entropies(os.getcwd()) def load_ckpt(model, model_dir): model.compile(optimizer=keras.optimizers.Adam(0.0001), loss=keras.losses.CategoricalCrossentropy(from_logits=False), metrics=[]) ckpt =",
"if manager.latest_checkpoint: print(\"Restored from {}\".format(manager.latest_checkpoint)) def get_model_dir(backbone, log='log', routing='avg', dataset='voc2010', iter_num=None, temper=None, atoms=None,",
"parts in parts_list: print('parts:', parts) for method in methods: print('method:', method) if routing",
"results = attacks.evaluate_attacks_success_rate_all_target(epsilons, test_set, model, loss, categories, method=method, steps=steps, label_sparse=False, cost=True, model_src=model_src) else:",
"model_src=model_src) elif metric == 'success': if all_target: categories = [i for i in",
"= [-1] for temper in tempers: print('temper:', temper) if all_target: epsilons = [0.1]",
"load_model(backbone, iter_num, temper, atoms=16, log='log', routing='DR', finetune=0, parts=128, bs=128, idx=1): data_shape = utils.get_shape(backbone)",
"net=model) manager = tf.train.CheckpointManager(ckpt, model_dir, max_to_keep=3) ckpt.restore(manager.latest_checkpoint) if manager.latest_checkpoint: print(\"Restored from {}\".format(manager.latest_checkpoint)) def",
"in_shape = (299, 299, 3) base = keras.applications.InceptionV3(include_top=False, input_shape=in_shape) layer_num = len(base.layers) for",
"temper, parts, atoms) model = keras.Model(inputs=inputs, outputs=probs, name='x') load_ckpt(model, model_dir) return model, data_shape,",
"activated_entropy, coupling_entropy import numpy as np import config WEIGHT_DECAY = 1e-4 kernel_regularizer =",
"model_name = build_model_name(params) inputs, probs, tensor_log = build(num_out, params.model.backbone, params.model.fine, params.routing.type, params.routing.iter_num, params.routing.temper,",
"== 'ResNet50': in_shape = (224, 224, 3) base = keras.applications.ResNet50(include_top=False, input_shape=in_shape) else: in_shape",
"test_set: (child_poses, child_probs), (parent_poses, parent_probs, cs) = test_model(images) c = cs[-1] if activated:",
"backbone) for parts in parts_list: print('parts:', parts) for method in methods: print('method:', method)",
"temper=temper, atoms=atoms, parts=parts, bs=bs, finetune=finetune, idx=idx) if black_box: print('load black box source model')",
"or type == 'EM': loss = losses.MarginLoss(sparse=False, upper_margin=0.9, bottom_margin=0.1, down_weight=0.5) else: loss =",
"attacks.evaluate_model_after_attacks(epsilons, acc_adv, test_set, model, loss, method=method, steps=steps, label_sparse=False, cost=True, model_src=model_src) elif metric ==",
"[0.0, 20.0, 40.0, 60.0, 80.0] parts_list = [128] all_target = False black_box =",
"atoms=atoms, idx=idx) inputs, probs, log = build(6, backbone, finetune, routing, iter_num, temper, parts,",
"input_shape=in_shape) elif backbone == 'ResNet50': in_shape = (224, 224, 3) base = keras.applications.ResNet50(include_top=False,",
"= [0.0, 20.0, 40.0, 60.0, 80.0] parts_list = [128] all_target = False black_box",
"voc_parts.build_dataset3(batch_size=params.training.batch_size, shape=data_shape, arch=params.model.backbone) model, tensor_log = build_model(num_out=info.features['label'].num_classes, params=params) trainer = train.Trainer(model, params, info,",
"'EM': model_dir += '_iter{}'.format(iter_num) model_dir += '_temper{}'.format(temper) model_dir += '_atoms{}'.format(atoms) model_dir += '_trial{}_bs{}_flip_crop'.format(idx,",
"method='channel', activation='squash')(interpretable) log.add_hist('child_activation', child_prob) transformed_caps = layers.CapsuleTransformDense(num_out=num_out, out_atom=atoms, share_weights=False, initializer=keras.initializers.glorot_normal(), regularizer=kernel_regularizer)(child_pose) parent_poses, parent_probs,",
"sys.path.append(os.getcwd()) import tensorflow as tf tf.get_logger().setLevel('ERROR') from tensorflow import keras from common.inputs.voc2010 import",
"log_model = keras.Model(inputs=inputs, outputs=tensor_log.get_outputs(), name=model_name + '_log') tensor_log.set_model(log_model) loss, optimizer = get_loss_opt(params.routing.type) model.compile(optimizer=optimizer,",
"input_shape=in_shape) layer_num = len(base.layers) for i, layer in enumerate(base.layers): if i < layer_num-fine:",
"model_dir += '_temper{}'.format(temper) model_dir += '_atoms{}'.format(atoms) model_dir += '_trial{}_bs{}_flip_crop'.format(idx, bs) if not os.path.exists(model_dir):",
"raise Exception('model not exist:{}'.format(model_dir)) return model_dir def load_model(backbone, iter_num, temper, atoms=16, log='log', routing='DR',",
"= get_model_dir(backbone=backbone, log=log, routing=routing, finetune=finetune, parts=parts, bs=bs, iter_num=iter_num, temper=temper, atoms=atoms, idx=idx) inputs, probs,",
"black_box = False methods = ['PGD', 'BIM', 'FGSM'] backbones = ['InceptionV3'] routing =",
"keras.optimizers.Adam(0.0001) if type == 'DR' or type == 'EM': loss = losses.MarginLoss(sparse=False, upper_margin=0.9,",
"= False methods = ['PGD', 'BIM', 'FGSM'] backbones = ['InceptionV3'] routing = 'DR'",
"model_dir = '{}/{}/{}_{}_fine{}_part{}_{}'.format(log, dataset, BASE_NAME, backbone, finetune, parts, routing) if routing == 'DR'",
"tf.get_logger().setLevel('ERROR') from tensorflow import keras from common.inputs.voc2010 import voc_parts from common import layers,",
"== 'success': if all_target: categories = [i for i in range(6)] results =",
"all_target=all_target, method=method, steps=5, routing=routing, black_box=black_box, parts=parts, iter_num=2, temper=temper, atoms=16, bs=64, idx=1) def compute_entropy(root,",
"kernel_initializer = keras.initializers.he_normal() BASE_NAME = 'ex4_3' def build_model_name(params): model_name = BASE_NAME model_name +=",
"'VGG16': in_shape = (224, 224, 3) base = keras.applications.VGG16(include_top=False, input_shape=in_shape) elif backbone ==",
"= tf.train.CheckpointManager(ckpt, model_dir, max_to_keep=3) ckpt.restore(manager.latest_checkpoint) if manager.latest_checkpoint: print(\"Restored from {}\".format(manager.latest_checkpoint)) def get_model_dir(backbone, log='log',",
"temper, parts, atoms): log = utils.TensorLog() if backbone == 'VGG16': in_shape = (224,",
"test_set, info = voc_parts.build_dataset3(root + 'data', batch_size=32, shape=data_shape) acc_adv = keras.metrics.CategoricalAccuracy(name='acc_adv') if metric",
"cost=True, model_src=model_src) return results def do_adv(root): epsilons = [0.1, 0.2, 0.3] tempers =",
"in test_set: (child_poses, child_probs), (parent_poses, parent_probs, cs) = test_model(images) c = cs[-1] if",
"= (299, 299, 3) else: data_shape = (224, 224, 3) train_set, test_set, info",
"(parent_poses, parent_probs, cs) = test_model(images) c = cs[-1] if activated: entropy = activated_entropy(c,",
"= attacks.evaluate_attacks_success_rate_all_target(epsilons, test_set, model, loss, categories, method=method, steps=steps, label_sparse=False, cost=True, model_src=model_src) else: results",
"'InceptionV3': in_shape = (299, 299, 3) base = keras.applications.InceptionV3(include_top=False, input_shape=in_shape) elif backbone ==",
"atoms=16, method='channel', activation='squash')(interpretable) log.add_hist('child_activation', child_prob) transformed_caps = layers.CapsuleTransformDense(num_out=num_out, out_atom=atoms, share_weights=False, initializer=keras.initializers.glorot_normal(), regularizer=kernel_regularizer)(child_pose) parent_poses,",
"= keras.layers.GlobalAveragePooling2D()(interpretable) output = keras.layers.Dense(num_out)(pool) elif routing == 'max': pool = keras.layers.GlobalMaxPooling2D()(interpretable) output",
"parts) for method in methods: print('method:', method) if routing == 'avg' or routing",
"child_prob = layers.CapsuleGroups(height=shape[1], width=shape[2], channel=shape[3], atoms=16, method='channel', activation='squash')(interpretable) log.add_hist('child_activation', child_prob) transformed_caps = layers.CapsuleTransformDense(num_out=num_out,",
"channel=shape[3], atoms=16, method='channel', activation='squash')(interpretable) log.add_hist('child_activation', child_prob) transformed_caps = layers.CapsuleTransformDense(num_out=num_out, out_atom=atoms, share_weights=False, initializer=keras.initializers.glorot_normal(), regularizer=kernel_regularizer)(child_pose)",
"trainer = train.Trainer(model, params, info, tensor_log, finetune=True, inference_label=False, max_save=1) trainer.metrics['accuracy'] = tf.keras.metrics.CategoricalAccuracy(name='accuracy') if",
"dataset, BASE_NAME, backbone, finetune, parts, routing) if routing == 'DR' or routing ==",
"os import sys sys.path.append(os.getcwd()) import tensorflow as tf tf.get_logger().setLevel('ERROR') from tensorflow import keras",
"initializer=keras.initializers.glorot_normal(), regularizer=kernel_regularizer)(child_pose) parent_poses, parent_probs, cs = layers.DynamicRouting(num_routing=iter_num, softmax_in=False, temper=temper, activation='squash', pooling=False, log=log)((transformed_caps, child_prob))",
"= model loss, _ = get_loss_opt(routing) _, test_set, info = voc_parts.build_dataset3(root + 'data',",
"= layers.DynamicRouting(num_routing=iter_num, softmax_in=False, temper=temper, activation='squash', pooling=False, log=log)((transformed_caps, child_prob)) log.add_hist('parent_activation', parent_probs[-1]) output = parent_probs[-1]",
"tensor_log, finetune=True, inference_label=False, max_save=1) trainer.metrics['accuracy'] = tf.keras.metrics.CategoricalAccuracy(name='accuracy') if args.train: trainer.fit(train_set, test_set) else: trainer.evaluate(test_set)",
"parts=128, bs=64, idx=1): model, data_shape, model_dir = load_model(log=root + log, backbone=backbone, routing=routing, iter_num=iter_num,",
"= keras.applications.VGG16(include_top=False, input_shape=in_shape) elif backbone == 'VGG19': in_shape = (224, 224, 3) base",
"keras.applications.VGG19(include_top=False, input_shape=in_shape) elif backbone == 'InceptionV3': in_shape = (299, 299, 3) base =",
"black box source model') model_src, data_shape, model_dir = load_model(log=root + log, backbone=backbone, routing=routing,",
"'BIM', 'FGSM'] backbones = ['InceptionV3'] routing = 'DR' for backbone in backbones: print('backbone:',",
"40.0, 60.0, 80.0] for temper in tempers: print('temper:{}'.format(temper)) compute_entropy(root, backbone='InceptionV3', iter_num=2, temper=temper, atoms=16,",
"+= '_flip' if params.dataset.crop: model_name += '_crop' return model_name def get_loss_opt(type): optimizer =",
"+= '_iter{}'.format(iter_num) model_dir += '_temper{}'.format(temper) model_dir += '_atoms{}'.format(atoms) model_dir += '_trial{}_bs{}_flip_crop'.format(idx, bs) if",
"log, backbone=backbone, routing=routing, iter_num=iter_num, temper=temper, atoms=atoms, parts=parts, bs=bs, finetune=finetune, idx=idx) if black_box: print('load",
"test_set, model, loss, method=method, steps=steps, label_sparse=False, cost=True, model_src=model_src) elif metric == 'success': if",
"0.3] tempers = [0.0, 20.0, 40.0, 60.0, 80.0] parts_list = [128] all_target =",
"if 'kernel' in w.name: r = kernel_regularizer(w) layer.add_loss(lambda: r) inputs = keras.Input(in_shape) features",
"voc_parts from common import layers, losses, utils, train, attacks from common.ops.routing import activated_entropy,",
"backbone == 'ResNet50': in_shape = (224, 224, 3) base = keras.applications.ResNet50(include_top=False, input_shape=in_shape) else:",
"base = keras.applications.VGG19(include_top=False, input_shape=in_shape) elif backbone == 'InceptionV3': in_shape = (299, 299, 3)",
"= tf.keras.metrics.CategoricalAccuracy(name='accuracy') if args.train: trainer.fit(train_set, test_set) else: trainer.evaluate(test_set) elif params.task == 'attack': do_adv(os.getcwd())",
"tensorflow import keras from common.inputs.voc2010 import voc_parts from common import layers, losses, utils,",
"= keras.optimizers.Adam(0.0001) if type == 'DR' or type == 'EM': loss = losses.MarginLoss(sparse=False,",
"= 'voc2010' if params.model.backbone == 'InceptionV3': data_shape = (299, 299, 3) else: data_shape",
"dataset='voc2010', iter_num=None, temper=None, atoms=None, finetune=0, parts=128, bs=32, idx=1): model_dir = '{}/{}/{}_{}_fine{}_part{}_{}'.format(log, dataset, BASE_NAME,",
"in parts_list: print('parts:', parts) for method in methods: print('method:', method) if routing ==",
"= load_model(log=root + 'log', backbone=backbone, iter_num=iter_num, temper=temper, atoms=atoms, routing=routing, finetune=finetune, parts=parts, bs=bs) train_set,",
"in tempers: print('temper:{}'.format(temper)) compute_entropy(root, backbone='InceptionV3', iter_num=2, temper=temper, atoms=16, routing='DR', finetune=0, parts=128, bs=64) if",
"parts_list: print('parts:', parts) for method in methods: print('method:', method) if routing == 'avg'",
"activated: entropy = activated_entropy(c, child_probs) else: entropy = coupling_entropy(c) results.append(entropy) results = np.concatenate(results,",
"[i for i in range(6)] results = attacks.evaluate_attacks_success_rate_all_target(epsilons, test_set, model, loss, categories, method=method,",
"args.train: trainer.fit(train_set, test_set) else: trainer.evaluate(test_set) elif params.task == 'attack': do_adv(os.getcwd()) elif params.task ==",
"0) mean = np.mean(results) std = np.std(results) print('{:.4}/{:.3}'.format(mean, std)) def compute_entropies(root): tempers =",
"+= '_crop' return model_name def get_loss_opt(type): optimizer = keras.optimizers.Adam(0.0001) if type == 'DR'",
"idx=idx) if black_box: print('load black box source model') model_src, data_shape, model_dir = load_model(log=root",
"= [128] all_target = False black_box = False methods = ['PGD', 'BIM', 'FGSM']",
"methods = ['PGD', 'BIM', 'FGSM'] backbones = ['InceptionV3'] routing = 'DR' for backbone",
"model, tensor_log def build(num_out, backbone, fine, routing, iter_num, temper, parts, atoms): log =",
"= utils.TensorLog() if backbone == 'VGG16': in_shape = (224, 224, 3) base =",
"keras.Input(in_shape) features = base(inputs) interpretable = keras.layers.Conv2D(filters=parts, kernel_size=1, activation='relu', kernel_initializer=kernel_initializer, kernel_regularizer=kernel_regularizer)(features) shape =",
"60.0, 80.0] parts_list = [128] all_target = False black_box = False methods =",
"methods: print('method:', method) if routing == 'avg' or routing == 'max': tempers =",
"get_loss_opt(type): optimizer = keras.optimizers.Adam(0.0001) if type == 'DR' or type == 'EM': loss",
"in enumerate(base.layers): if i < layer_num-fine: layer.trainable = False else: for w in",
"keras.losses.CategoricalCrossentropy(from_logits=True) return loss, optimizer def build_model(num_out, params): model_name = build_model_name(params) inputs, probs, tensor_log",
"_, test_set, info = voc_parts.build_dataset3(root + 'data', batch_size=32, shape=data_shape) acc_adv = keras.metrics.CategoricalAccuracy(name='acc_adv') if",
"backbone=backbone, metric='success', all_target=all_target, method=method, steps=5, routing=routing, black_box=black_box, parts=parts, iter_num=2, temper=temper, atoms=16, bs=64, idx=1)",
"build_model(num_out, params): model_name = build_model_name(params) inputs, probs, tensor_log = build(num_out, params.model.backbone, params.model.fine, params.routing.type,",
"all_target = False black_box = False methods = ['PGD', 'BIM', 'FGSM'] backbones =",
"params.task == 'train': params.dataset.name = 'voc2010' if params.model.backbone == 'InceptionV3': data_shape = (299,",
"= [0.1] evaluate_attack(epsilons, root=root, backbone=backbone, metric='success', all_target=all_target, method=method, steps=5, routing=routing, black_box=black_box, parts=parts, iter_num=2,",
"shape=data_shape) acc_adv = keras.metrics.CategoricalAccuracy(name='acc_adv') if metric == 'acc': results = attacks.evaluate_model_after_attacks(epsilons, acc_adv, test_set,",
"name=model_name + '_log') tensor_log.set_model(log_model) loss, optimizer = get_loss_opt(params.routing.type) model.compile(optimizer=optimizer, loss=loss, metrics=[]) model.summary() model.callbacks",
"metric='success', all_target=all_target, method=method, steps=5, routing=routing, black_box=black_box, parts=parts, iter_num=2, temper=temper, atoms=16, bs=64, idx=1) def",
"temper=temper, atoms=atoms, routing=routing, finetune=finetune, parts=parts, bs=bs) train_set, test_set, info = voc_parts.build_dataset3(root + 'data',",
"w in layer.weights: if 'kernel' in w.name: r = kernel_regularizer(w) layer.add_loss(lambda: r) inputs",
"3) train_set, test_set, info = voc_parts.build_dataset3(batch_size=params.training.batch_size, shape=data_shape, arch=params.model.backbone) model, tensor_log = build_model(num_out=info.features['label'].num_classes, params=params)",
"build_model_name(params): model_name = BASE_NAME model_name += '_{}'.format(params.model.backbone) model_name += '_fine{}'.format(params.model.fine) model_name += '_part{}'.format(params.caps.parts)",
"routing) if routing == 'DR' or routing == 'EM': model_dir += '_iter{}'.format(iter_num) model_dir",
"interpretable.get_shape().as_list() if routing == 'avg': pool = keras.layers.GlobalAveragePooling2D()(interpretable) output = keras.layers.Dense(num_out)(pool) elif routing",
"data_shape, model_dir = load_model(log=root + 'log', backbone=backbone, iter_num=iter_num, temper=temper, atoms=atoms, routing=routing, finetune=finetune, parts=parts,",
"from common import layers, losses, utils, train, attacks from common.ops.routing import activated_entropy, coupling_entropy",
"else: loss = keras.losses.CategoricalCrossentropy(from_logits=True) return loss, optimizer def build_model(num_out, params): model_name = build_model_name(params)",
"black_box=False, iter_num=10, temper=1.0, atoms=16, parts=128, bs=64, idx=1): model, data_shape, model_dir = load_model(log=root +",
"parts_list = [128] all_target = False black_box = False methods = ['PGD', 'BIM',",
"iter_num=None, temper=None, atoms=None, finetune=0, parts=128, bs=32, idx=1): model_dir = '{}/{}/{}_{}_fine{}_part{}_{}'.format(log, dataset, BASE_NAME, backbone,",
"bs=64, idx=1): model, data_shape, model_dir = load_model(log=root + log, backbone=backbone, routing=routing, iter_num=iter_num, temper=temper,",
"= utils.get_shape(backbone) model_dir = get_model_dir(backbone=backbone, log=log, routing=routing, finetune=finetune, parts=parts, bs=bs, iter_num=iter_num, temper=temper, atoms=atoms,",
"name='x') load_ckpt(model, model_dir) return model, data_shape, model_dir def evaluate_attack(epsilons, root='', log='log', backbone='InceptionV3', metric='acc',",
"'DR': child_pose, child_prob = layers.CapsuleGroups(height=shape[1], width=shape[2], channel=shape[3], atoms=16, method='channel', activation='squash')(interpretable) log.add_hist('child_activation', child_prob) transformed_caps",
"finetune=0, routing='DR', black_box=False, iter_num=10, temper=1.0, atoms=16, parts=128, bs=64, idx=1): model, data_shape, model_dir =",
"all_target: categories = [i for i in range(6)] results = attacks.evaluate_attacks_success_rate_all_target(epsilons, test_set, model,",
"routing, iter_num, temper, parts, atoms) model = keras.Model(inputs=inputs, outputs=probs, name='x') load_ckpt(model, model_dir) return",
"in_shape = (224, 224, 3) base = keras.applications.VGG19(include_top=False, input_shape=in_shape) elif backbone == 'InceptionV3':",
"routing, iter_num, temper, parts, atoms): log = utils.TensorLog() if backbone == 'VGG16': in_shape",
"i, layer in enumerate(base.layers): if i < layer_num-fine: layer.trainable = False else: for",
"atoms) model = keras.Model(inputs=inputs, outputs=probs, name='x') load_ckpt(model, model_dir) return model, data_shape, model_dir def",
"test_set, model, loss, method=method, steps=steps, label_sparse=False, cost=True, model_src=model_src) return results def do_adv(root): epsilons",
"if routing == 'avg' or routing == 'max': tempers = [-1] for temper",
"return model_name def get_loss_opt(type): optimizer = keras.optimizers.Adam(0.0001) if type == 'DR' or type",
"= (299, 299, 3) base = keras.applications.InceptionV3(include_top=False, input_shape=in_shape) elif backbone == 'ResNet50': in_shape",
"parts=parts, iter_num=2, temper=temper, atoms=16, bs=64, idx=1) def compute_entropy(root, backbone='InceptionV3', iter_num=2, activated=True, temper=10.0, atoms=16,",
"= False black_box = False methods = ['PGD', 'BIM', 'FGSM'] backbones = ['InceptionV3']",
"import numpy as np import config WEIGHT_DECAY = 1e-4 kernel_regularizer = keras.regularizers.l2(WEIGHT_DECAY) kernel_initializer",
"model_name += '_atoms{}'.format(params.caps.atoms) model_name += '_trial{}'.format(str(params.training.idx)) model_name += '_bs{}'.format(str(params.training.batch_size)) if params.dataset.flip: model_name +=",
"= ['PGD', 'BIM', 'FGSM'] backbones = ['InceptionV3'] routing = 'DR' for backbone in",
"method=method, steps=steps, label_sparse=False, cost=True, model_src=model_src) elif metric == 'success': if all_target: categories =",
"cs = layers.DynamicRouting(num_routing=iter_num, softmax_in=False, temper=temper, activation='squash', pooling=False, log=log)((transformed_caps, child_prob)) log.add_hist('parent_activation', parent_probs[-1]) output =",
"log.add_hist('child_activation', child_prob) transformed_caps = layers.CapsuleTransformDense(num_out=num_out, out_atom=atoms, share_weights=False, initializer=keras.initializers.glorot_normal(), regularizer=kernel_regularizer)(child_pose) parent_poses, parent_probs, cs =",
"base = keras.applications.VGG16(include_top=False, input_shape=in_shape) elif backbone == 'VGG19': in_shape = (224, 224, 3)",
"steps=5, routing=routing, black_box=black_box, parts=parts, iter_num=2, temper=temper, atoms=16, bs=64, idx=1) def compute_entropy(root, backbone='InceptionV3', iter_num=2,",
"= (224, 224, 3) base = keras.applications.VGG16(include_top=False, input_shape=in_shape) elif backbone == 'VGG19': in_shape",
"elif backbone == 'ResNet50': in_shape = (224, 224, 3) base = keras.applications.ResNet50(include_top=False, input_shape=in_shape)",
"parts=128, bs=32): model, data_shape, model_dir = load_model(log=root + 'log', backbone=backbone, iter_num=iter_num, temper=temper, atoms=atoms,",
"'_trial{}_bs{}_flip_crop'.format(idx, bs) if not os.path.exists(model_dir): raise Exception('model not exist:{}'.format(model_dir)) return model_dir def load_model(backbone,",
"params.caps.parts, params.caps.atoms ) model = keras.Model(inputs=inputs, outputs=probs, name=model_name) log_model = keras.Model(inputs=inputs, outputs=tensor_log.get_outputs(), name=model_name",
"model_name = BASE_NAME model_name += '_{}'.format(params.model.backbone) model_name += '_fine{}'.format(params.model.fine) model_name += '_part{}'.format(params.caps.parts) model_name",
"parts=parts, bs=bs, iter_num=iter_num, temper=temper, atoms=atoms, idx=idx) inputs, probs, log = build(6, backbone, finetune,",
"params = config.parse_args() if params.task == 'train': params.dataset.name = 'voc2010' if params.model.backbone ==",
"method='FGSM', steps=10, finetune=0, routing='DR', black_box=False, iter_num=10, temper=1.0, atoms=16, parts=128, bs=64, idx=1): model, data_shape,",
"model_name += '_iter{}'.format(params.routing.iter_num) model_name += '_temper{}'.format(params.routing.temper) model_name += '_atoms{}'.format(params.caps.atoms) model_name += '_trial{}'.format(str(params.training.idx)) model_name",
"= np.std(results) print('{:.4}/{:.3}'.format(mean, std)) def compute_entropies(root): tempers = [0.0, 20.0, 40.0, 60.0, 80.0]",
"inference_label=False, max_save=1) trainer.metrics['accuracy'] = tf.keras.metrics.CategoricalAccuracy(name='accuracy') if args.train: trainer.fit(train_set, test_set) else: trainer.evaluate(test_set) elif params.task",
"elif routing == 'max': pool = keras.layers.GlobalMaxPooling2D()(interpretable) output = keras.layers.Dense(num_out)(pool) elif routing ==",
"in layer.weights: if 'kernel' in w.name: r = kernel_regularizer(w) layer.add_loss(lambda: r) inputs =",
"elif metric == 'success': if all_target: categories = [i for i in range(6)]",
"80.0] parts_list = [128] all_target = False black_box = False methods = ['PGD',",
"fine, routing, iter_num, temper, parts, atoms): log = utils.TensorLog() if backbone == 'VGG16':",
"test_set, info = voc_parts.build_dataset3(root + 'data', batch_size=32, shape=data_shape) test_model = keras.Model(model.layers[0].input, [model.layers[3].output, model.layers[5].output])",
"as np import config WEIGHT_DECAY = 1e-4 kernel_regularizer = keras.regularizers.l2(WEIGHT_DECAY) kernel_initializer = keras.initializers.he_normal()",
"model_src = model loss, _ = get_loss_opt(routing) _, test_set, info = voc_parts.build_dataset3(root +",
"(child_poses, child_probs), (parent_poses, parent_probs, cs) = test_model(images) c = cs[-1] if activated: entropy",
"from common.inputs.voc2010 import voc_parts from common import layers, losses, utils, train, attacks from",
"data_shape, model_dir = load_model(log=root + log, backbone=backbone, routing=routing, iter_num=iter_num, temper=temper, atoms=atoms, parts=parts, bs=bs,",
"routing=routing, iter_num=iter_num, temper=temper, atoms=atoms, parts=parts, bs=bs, finetune=finetune, idx=idx) if black_box: print('load black box",
"config.parse_args() if params.task == 'train': params.dataset.name = 'voc2010' if params.model.backbone == 'InceptionV3': data_shape",
") model = keras.Model(inputs=inputs, outputs=probs, name=model_name) log_model = keras.Model(inputs=inputs, outputs=tensor_log.get_outputs(), name=model_name + '_log')",
"'train': params.dataset.name = 'voc2010' if params.model.backbone == 'InceptionV3': data_shape = (299, 299, 3)",
"get_loss_opt(params.routing.type) model.compile(optimizer=optimizer, loss=loss, metrics=[]) model.summary() model.callbacks = [] return model, tensor_log def build(num_out,",
"'_log') tensor_log.set_model(log_model) loss, optimizer = get_loss_opt(params.routing.type) model.compile(optimizer=optimizer, loss=loss, metrics=[]) model.summary() model.callbacks = []",
"backbone=backbone, routing=routing, iter_num=iter_num, temper=temper, atoms=atoms, parts=parts, bs=bs, finetune=finetune, idx=idx) if black_box: print('load black",
"params.model.fine, params.routing.type, params.routing.iter_num, params.routing.temper, params.caps.parts, params.caps.atoms ) model = keras.Model(inputs=inputs, outputs=probs, name=model_name) log_model",
"return model, tensor_log def build(num_out, backbone, fine, routing, iter_num, temper, parts, atoms): log",
"+= '_{}'.format(params.model.backbone) model_name += '_fine{}'.format(params.model.fine) model_name += '_part{}'.format(params.caps.parts) model_name += '_{}'.format(params.routing.type) if params.routing.type",
"== 'InceptionV3': data_shape = (299, 299, 3) else: data_shape = (224, 224, 3)",
"(224, 224, 3) train_set, test_set, info = voc_parts.build_dataset3(batch_size=params.training.batch_size, shape=data_shape, arch=params.model.backbone) model, tensor_log =",
"params=params) trainer = train.Trainer(model, params, info, tensor_log, finetune=True, inference_label=False, max_save=1) trainer.metrics['accuracy'] = tf.keras.metrics.CategoricalAccuracy(name='accuracy')",
"if black_box: print('load black box source model') model_src, data_shape, model_dir = load_model(log=root +",
"+= '_iter{}'.format(params.routing.iter_num) model_name += '_temper{}'.format(params.routing.temper) model_name += '_atoms{}'.format(params.caps.atoms) model_name += '_trial{}'.format(str(params.training.idx)) model_name +=",
"finetune=0, parts=128, bs=32, idx=1): model_dir = '{}/{}/{}_{}_fine{}_part{}_{}'.format(log, dataset, BASE_NAME, backbone, finetune, parts, routing)",
"[-1] for temper in tempers: print('temper:', temper) if all_target: epsilons = [0.1] evaluate_attack(epsilons,",
"backbone == 'VGG19': in_shape = (224, 224, 3) base = keras.applications.VGG19(include_top=False, input_shape=in_shape) elif",
"def load_ckpt(model, model_dir): model.compile(optimizer=keras.optimizers.Adam(0.0001), loss=keras.losses.CategoricalCrossentropy(from_logits=False), metrics=[]) ckpt = tf.train.Checkpoint(optimizer=model.optimizer, net=model) manager = tf.train.CheckpointManager(ckpt,",
"activated_entropy(c, child_probs) else: entropy = coupling_entropy(c) results.append(entropy) results = np.concatenate(results, 0) mean =",
"kernel_regularizer = keras.regularizers.l2(WEIGHT_DECAY) kernel_initializer = keras.initializers.he_normal() BASE_NAME = 'ex4_3' def build_model_name(params): model_name =",
"params.dataset.name = 'voc2010' if params.model.backbone == 'InceptionV3': data_shape = (299, 299, 3) else:",
"get_model_dir(backbone=backbone, log=log, routing=routing, finetune=finetune, parts=parts, bs=bs, iter_num=iter_num, temper=temper, atoms=atoms, idx=idx) inputs, probs, log",
"= keras.layers.GlobalMaxPooling2D()(interpretable) output = keras.layers.Dense(num_out)(pool) elif routing == 'DR': child_pose, child_prob = layers.CapsuleGroups(height=shape[1],",
"results.append(entropy) results = np.concatenate(results, 0) mean = np.mean(results) std = np.std(results) print('{:.4}/{:.3}'.format(mean, std))",
"i in range(6)] results = attacks.evaluate_attacks_success_rate_all_target(epsilons, test_set, model, loss, categories, method=method, steps=steps, label_sparse=False,",
"== 'train': params.dataset.name = 'voc2010' if params.model.backbone == 'InceptionV3': data_shape = (299, 299,",
"'attack': do_adv(os.getcwd()) elif params.task == 'score': compute_entropies(os.getcwd()) def load_ckpt(model, model_dir): model.compile(optimizer=keras.optimizers.Adam(0.0001), loss=keras.losses.CategoricalCrossentropy(from_logits=False), metrics=[])",
"results = attacks.evaluate_model_after_attacks(epsilons, acc_adv, test_set, model, loss, method=method, steps=steps, label_sparse=False, cost=True, model_src=model_src) elif",
"= (224, 224, 3) train_set, test_set, info = voc_parts.build_dataset3(batch_size=params.training.batch_size, shape=data_shape, arch=params.model.backbone) model, tensor_log",
"data_shape, model_dir def evaluate_attack(epsilons, root='', log='log', backbone='InceptionV3', metric='acc', all_target=False, method='FGSM', steps=10, finetune=0, routing='DR',",
"manager.latest_checkpoint: print(\"Restored from {}\".format(manager.latest_checkpoint)) def get_model_dir(backbone, log='log', routing='avg', dataset='voc2010', iter_num=None, temper=None, atoms=None, finetune=0,",
"metric='acc', all_target=False, method='FGSM', steps=10, finetune=0, routing='DR', black_box=False, iter_num=10, temper=1.0, atoms=16, parts=128, bs=64, idx=1):",
"elif backbone == 'VGG19': in_shape = (224, 224, 3) base = keras.applications.VGG19(include_top=False, input_shape=in_shape)",
"len(base.layers) for i, layer in enumerate(base.layers): if i < layer_num-fine: layer.trainable = False",
"temper=temper, atoms=atoms, parts=parts, bs=bs, finetune=finetune, idx=2) else: model_src = model loss, _ =",
"print('temper:{}'.format(temper)) compute_entropy(root, backbone='InceptionV3', iter_num=2, temper=temper, atoms=16, routing='DR', finetune=0, parts=128, bs=64) if __name__ ==",
"model loss, _ = get_loss_opt(routing) _, test_set, info = voc_parts.build_dataset3(root + 'data', batch_size=32,",
"'ResNet50': in_shape = (224, 224, 3) base = keras.applications.ResNet50(include_top=False, input_shape=in_shape) else: in_shape =",
"routing='DR', finetune=0, parts=128, bs=32): model, data_shape, model_dir = load_model(log=root + 'log', backbone=backbone, iter_num=iter_num,",
"ckpt.restore(manager.latest_checkpoint) if manager.latest_checkpoint: print(\"Restored from {}\".format(manager.latest_checkpoint)) def get_model_dir(backbone, log='log', routing='avg', dataset='voc2010', iter_num=None, temper=None,",
"not exist:{}'.format(model_dir)) return model_dir def load_model(backbone, iter_num, temper, atoms=16, log='log', routing='DR', finetune=0, parts=128,",
"do_adv(root): epsilons = [0.1, 0.2, 0.3] tempers = [0.0, 20.0, 40.0, 60.0, 80.0]",
"+= '_{}'.format(params.routing.type) if params.routing.type == 'DR' or params.routing.type == 'EM': model_name += '_iter{}'.format(params.routing.iter_num)",
"keras.Model(inputs=inputs, outputs=probs, name=model_name) log_model = keras.Model(inputs=inputs, outputs=tensor_log.get_outputs(), name=model_name + '_log') tensor_log.set_model(log_model) loss, optimizer",
"tf.train.CheckpointManager(ckpt, model_dir, max_to_keep=3) ckpt.restore(manager.latest_checkpoint) if manager.latest_checkpoint: print(\"Restored from {}\".format(manager.latest_checkpoint)) def get_model_dir(backbone, log='log', routing='avg',",
"loss=loss, metrics=[]) model.summary() model.callbacks = [] return model, tensor_log def build(num_out, backbone, fine,",
"[model.layers[3].output, model.layers[5].output]) results = [] for images, labels in test_set: (child_poses, child_probs), (parent_poses,",
"if type == 'DR' or type == 'EM': loss = losses.MarginLoss(sparse=False, upper_margin=0.9, bottom_margin=0.1,",
"coupling_entropy import numpy as np import config WEIGHT_DECAY = 1e-4 kernel_regularizer = keras.regularizers.l2(WEIGHT_DECAY)",
"losses.MarginLoss(sparse=False, upper_margin=0.9, bottom_margin=0.1, down_weight=0.5) else: loss = keras.losses.CategoricalCrossentropy(from_logits=True) return loss, optimizer def build_model(num_out,",
"std = np.std(results) print('{:.4}/{:.3}'.format(mean, std)) def compute_entropies(root): tempers = [0.0, 20.0, 40.0, 60.0,",
"evaluate_attack(epsilons, root='', log='log', backbone='InceptionV3', metric='acc', all_target=False, method='FGSM', steps=10, finetune=0, routing='DR', black_box=False, iter_num=10, temper=1.0,",
"routing=routing, finetune=finetune, parts=parts, bs=bs, iter_num=iter_num, temper=temper, atoms=atoms, idx=idx) inputs, probs, log = build(6,",
"'_temper{}'.format(temper) model_dir += '_atoms{}'.format(atoms) model_dir += '_trial{}_bs{}_flip_crop'.format(idx, bs) if not os.path.exists(model_dir): raise Exception('model",
"finetune=finetune, idx=2) else: model_src = model loss, _ = get_loss_opt(routing) _, test_set, info",
"for parts in parts_list: print('parts:', parts) for method in methods: print('method:', method) if",
"iter_num=iter_num, temper=temper, atoms=atoms, routing=routing, finetune=finetune, parts=parts, bs=bs) train_set, test_set, info = voc_parts.build_dataset3(root +",
"compute_entropy(root, backbone='InceptionV3', iter_num=2, temper=temper, atoms=16, routing='DR', finetune=0, parts=128, bs=64) if __name__ == \"__main__\":",
"std)) def compute_entropies(root): tempers = [0.0, 20.0, 40.0, 60.0, 80.0] for temper in",
"params.task == 'attack': do_adv(os.getcwd()) elif params.task == 'score': compute_entropies(os.getcwd()) def load_ckpt(model, model_dir): model.compile(optimizer=keras.optimizers.Adam(0.0001),",
"log = build(6, backbone, finetune, routing, iter_num, temper, parts, atoms) model = keras.Model(inputs=inputs,",
"trainer.fit(train_set, test_set) else: trainer.evaluate(test_set) elif params.task == 'attack': do_adv(os.getcwd()) elif params.task == 'score':",
"[128] all_target = False black_box = False methods = ['PGD', 'BIM', 'FGSM'] backbones",
"in w.name: r = kernel_regularizer(w) layer.add_loss(lambda: r) inputs = keras.Input(in_shape) features = base(inputs)",
"model.callbacks = [] return model, tensor_log def build(num_out, backbone, fine, routing, iter_num, temper,",
"c = cs[-1] if activated: entropy = activated_entropy(c, child_probs) else: entropy = coupling_entropy(c)",
"regularizer=kernel_regularizer)(child_pose) parent_poses, parent_probs, cs = layers.DynamicRouting(num_routing=iter_num, softmax_in=False, temper=temper, activation='squash', pooling=False, log=log)((transformed_caps, child_prob)) log.add_hist('parent_activation',",
"return inputs, output, log def main(): args, params = config.parse_args() if params.task ==",
"get_model_dir(backbone, log='log', routing='avg', dataset='voc2010', iter_num=None, temper=None, atoms=None, finetune=0, parts=128, bs=32, idx=1): model_dir =",
"else: trainer.evaluate(test_set) elif params.task == 'attack': do_adv(os.getcwd()) elif params.task == 'score': compute_entropies(os.getcwd()) def",
"'voc2010' if params.model.backbone == 'InceptionV3': data_shape = (299, 299, 3) else: data_shape =",
"== 'EM': model_dir += '_iter{}'.format(iter_num) model_dir += '_temper{}'.format(temper) model_dir += '_atoms{}'.format(atoms) model_dir +=",
"steps=steps, label_sparse=False, cost=True, model_src=model_src) else: results = attacks.evaluate_attacks_success_rate(epsilons, test_set, model, loss, method=method, steps=steps,",
"= np.concatenate(results, 0) mean = np.mean(results) std = np.std(results) print('{:.4}/{:.3}'.format(mean, std)) def compute_entropies(root):",
"compute_entropy(root, backbone='InceptionV3', iter_num=2, activated=True, temper=10.0, atoms=16, routing='DR', finetune=0, parts=128, bs=32): model, data_shape, model_dir",
"params.dataset.flip: model_name += '_flip' if params.dataset.crop: model_name += '_crop' return model_name def get_loss_opt(type):",
"pool = keras.layers.GlobalAveragePooling2D()(interpretable) output = keras.layers.Dense(num_out)(pool) elif routing == 'max': pool = keras.layers.GlobalMaxPooling2D()(interpretable)",
"def compute_entropies(root): tempers = [0.0, 20.0, 40.0, 60.0, 80.0] for temper in tempers:",
"= cs[-1] if activated: entropy = activated_entropy(c, child_probs) else: entropy = coupling_entropy(c) results.append(entropy)",
"3) else: data_shape = (224, 224, 3) train_set, test_set, info = voc_parts.build_dataset3(batch_size=params.training.batch_size, shape=data_shape,",
"method) if routing == 'avg' or routing == 'max': tempers = [-1] for",
"activation='relu', kernel_initializer=kernel_initializer, kernel_regularizer=kernel_regularizer)(features) shape = interpretable.get_shape().as_list() if routing == 'avg': pool = keras.layers.GlobalAveragePooling2D()(interpretable)",
"== 'InceptionV3': in_shape = (299, 299, 3) base = keras.applications.InceptionV3(include_top=False, input_shape=in_shape) elif backbone",
"metrics=[]) ckpt = tf.train.Checkpoint(optimizer=model.optimizer, net=model) manager = tf.train.CheckpointManager(ckpt, model_dir, max_to_keep=3) ckpt.restore(manager.latest_checkpoint) if manager.latest_checkpoint:",
"build(6, backbone, finetune, routing, iter_num, temper, parts, atoms) model = keras.Model(inputs=inputs, outputs=probs, name='x')",
"else: model_src = model loss, _ = get_loss_opt(routing) _, test_set, info = voc_parts.build_dataset3(root",
"info = voc_parts.build_dataset3(root + 'data', batch_size=32, shape=data_shape) test_model = keras.Model(model.layers[0].input, [model.layers[3].output, model.layers[5].output]) results",
"model, loss, method=method, steps=steps, label_sparse=False, cost=True, model_src=model_src) elif metric == 'success': if all_target:",
"routing='avg', dataset='voc2010', iter_num=None, temper=None, atoms=None, finetune=0, parts=128, bs=32, idx=1): model_dir = '{}/{}/{}_{}_fine{}_part{}_{}'.format(log, dataset,",
"'DR' or type == 'EM': loss = losses.MarginLoss(sparse=False, upper_margin=0.9, bottom_margin=0.1, down_weight=0.5) else: loss",
"= keras.losses.CategoricalCrossentropy(from_logits=True) return loss, optimizer def build_model(num_out, params): model_name = build_model_name(params) inputs, probs,",
"r = kernel_regularizer(w) layer.add_loss(lambda: r) inputs = keras.Input(in_shape) features = base(inputs) interpretable =",
"model_dir): model.compile(optimizer=keras.optimizers.Adam(0.0001), loss=keras.losses.CategoricalCrossentropy(from_logits=False), metrics=[]) ckpt = tf.train.Checkpoint(optimizer=model.optimizer, net=model) manager = tf.train.CheckpointManager(ckpt, model_dir, max_to_keep=3)",
"activation='squash', pooling=False, log=log)((transformed_caps, child_prob)) log.add_hist('parent_activation', parent_probs[-1]) output = parent_probs[-1] return inputs, output, log",
"= voc_parts.build_dataset3(batch_size=params.training.batch_size, shape=data_shape, arch=params.model.backbone) model, tensor_log = build_model(num_out=info.features['label'].num_classes, params=params) trainer = train.Trainer(model, params,",
"utils, train, attacks from common.ops.routing import activated_entropy, coupling_entropy import numpy as np import",
"'EM': model_name += '_iter{}'.format(params.routing.iter_num) model_name += '_temper{}'.format(params.routing.temper) model_name += '_atoms{}'.format(params.caps.atoms) model_name += '_trial{}'.format(str(params.training.idx))",
"trainer.evaluate(test_set) elif params.task == 'attack': do_adv(os.getcwd()) elif params.task == 'score': compute_entropies(os.getcwd()) def load_ckpt(model,",
"model, data_shape, model_dir = load_model(log=root + log, backbone=backbone, routing=routing, iter_num=iter_num, temper=temper, atoms=atoms, parts=parts,",
"iter_num=iter_num, temper=temper, atoms=atoms, idx=idx) inputs, probs, log = build(6, backbone, finetune, routing, iter_num,",
"== 'avg' or routing == 'max': tempers = [-1] for temper in tempers:",
"model_name += '_part{}'.format(params.caps.parts) model_name += '_{}'.format(params.routing.type) if params.routing.type == 'DR' or params.routing.type ==",
"bs=bs, iter_num=iter_num, temper=temper, atoms=atoms, idx=idx) inputs, probs, log = build(6, backbone, finetune, routing,",
"entropy = coupling_entropy(c) results.append(entropy) results = np.concatenate(results, 0) mean = np.mean(results) std =",
"= coupling_entropy(c) results.append(entropy) results = np.concatenate(results, 0) mean = np.mean(results) std = np.std(results)",
"root='', log='log', backbone='InceptionV3', metric='acc', all_target=False, method='FGSM', steps=10, finetune=0, routing='DR', black_box=False, iter_num=10, temper=1.0, atoms=16,",
"parts=parts, bs=bs, finetune=finetune, idx=idx) if black_box: print('load black box source model') model_src, data_shape,",
"print('temper:', temper) if all_target: epsilons = [0.1] evaluate_attack(epsilons, root=root, backbone=backbone, metric='success', all_target=all_target, method=method,",
"'InceptionV3': data_shape = (299, 299, 3) else: data_shape = (224, 224, 3) train_set,",
"base = keras.applications.InceptionV3(include_top=False, input_shape=in_shape) layer_num = len(base.layers) for i, layer in enumerate(base.layers): if",
"attacks.evaluate_attacks_success_rate(epsilons, test_set, model, loss, method=method, steps=steps, label_sparse=False, cost=True, model_src=model_src) return results def do_adv(root):",
"log='log', backbone='InceptionV3', metric='acc', all_target=False, method='FGSM', steps=10, finetune=0, routing='DR', black_box=False, iter_num=10, temper=1.0, atoms=16, parts=128,",
"tempers = [0.0, 20.0, 40.0, 60.0, 80.0] parts_list = [128] all_target = False",
"== 'DR' or params.routing.type == 'EM': model_name += '_iter{}'.format(params.routing.iter_num) model_name += '_temper{}'.format(params.routing.temper) model_name",
"optimizer def build_model(num_out, params): model_name = build_model_name(params) inputs, probs, tensor_log = build(num_out, params.model.backbone,",
"layer.add_loss(lambda: r) inputs = keras.Input(in_shape) features = base(inputs) interpretable = keras.layers.Conv2D(filters=parts, kernel_size=1, activation='relu',",
"categories, method=method, steps=steps, label_sparse=False, cost=True, model_src=model_src) else: results = attacks.evaluate_attacks_success_rate(epsilons, test_set, model, loss,",
"activation='squash')(interpretable) log.add_hist('child_activation', child_prob) transformed_caps = layers.CapsuleTransformDense(num_out=num_out, out_atom=atoms, share_weights=False, initializer=keras.initializers.glorot_normal(), regularizer=kernel_regularizer)(child_pose) parent_poses, parent_probs, cs",
"iter_num, temper, parts, atoms) model = keras.Model(inputs=inputs, outputs=probs, name='x') load_ckpt(model, model_dir) return model,",
"mean = np.mean(results) std = np.std(results) print('{:.4}/{:.3}'.format(mean, std)) def compute_entropies(root): tempers = [0.0,",
"+ 'log', backbone=backbone, iter_num=iter_num, temper=temper, atoms=atoms, routing=routing, finetune=finetune, parts=parts, bs=bs) train_set, test_set, info",
"model_name += '_fine{}'.format(params.model.fine) model_name += '_part{}'.format(params.caps.parts) model_name += '_{}'.format(params.routing.type) if params.routing.type == 'DR'",
"log = utils.TensorLog() if backbone == 'VGG16': in_shape = (224, 224, 3) base",
"info = voc_parts.build_dataset3(root + 'data', batch_size=32, shape=data_shape) acc_adv = keras.metrics.CategoricalAccuracy(name='acc_adv') if metric ==",
"backbone, finetune, parts, routing) if routing == 'DR' or routing == 'EM': model_dir",
"= train.Trainer(model, params, info, tensor_log, finetune=True, inference_label=False, max_save=1) trainer.metrics['accuracy'] = tf.keras.metrics.CategoricalAccuracy(name='accuracy') if args.train:",
"from {}\".format(manager.latest_checkpoint)) def get_model_dir(backbone, log='log', routing='avg', dataset='voc2010', iter_num=None, temper=None, atoms=None, finetune=0, parts=128, bs=32,",
"trainer.metrics['accuracy'] = tf.keras.metrics.CategoricalAccuracy(name='accuracy') if args.train: trainer.fit(train_set, test_set) else: trainer.evaluate(test_set) elif params.task == 'attack':",
"bs) if not os.path.exists(model_dir): raise Exception('model not exist:{}'.format(model_dir)) return model_dir def load_model(backbone, iter_num,",
"if params.dataset.flip: model_name += '_flip' if params.dataset.crop: model_name += '_crop' return model_name def",
"train_set, test_set, info = voc_parts.build_dataset3(batch_size=params.training.batch_size, shape=data_shape, arch=params.model.backbone) model, tensor_log = build_model(num_out=info.features['label'].num_classes, params=params) trainer",
"outputs=tensor_log.get_outputs(), name=model_name + '_log') tensor_log.set_model(log_model) loss, optimizer = get_loss_opt(params.routing.type) model.compile(optimizer=optimizer, loss=loss, metrics=[]) model.summary()",
"model_name += '_temper{}'.format(params.routing.temper) model_name += '_atoms{}'.format(params.caps.atoms) model_name += '_trial{}'.format(str(params.training.idx)) model_name += '_bs{}'.format(str(params.training.batch_size)) if",
"routing == 'avg' or routing == 'max': tempers = [-1] for temper in",
"'_crop' return model_name def get_loss_opt(type): optimizer = keras.optimizers.Adam(0.0001) if type == 'DR' or",
"'_{}'.format(params.routing.type) if params.routing.type == 'DR' or params.routing.type == 'EM': model_name += '_iter{}'.format(params.routing.iter_num) model_name",
"return model, data_shape, model_dir def evaluate_attack(epsilons, root='', log='log', backbone='InceptionV3', metric='acc', all_target=False, method='FGSM', steps=10,",
"model_dir += '_atoms{}'.format(atoms) model_dir += '_trial{}_bs{}_flip_crop'.format(idx, bs) if not os.path.exists(model_dir): raise Exception('model not",
"not os.path.exists(model_dir): raise Exception('model not exist:{}'.format(model_dir)) return model_dir def load_model(backbone, iter_num, temper, atoms=16,",
"if args.train: trainer.fit(train_set, test_set) else: trainer.evaluate(test_set) elif params.task == 'attack': do_adv(os.getcwd()) elif params.task",
"'_atoms{}'.format(params.caps.atoms) model_name += '_trial{}'.format(str(params.training.idx)) model_name += '_bs{}'.format(str(params.training.batch_size)) if params.dataset.flip: model_name += '_flip' if",
"kernel_initializer=kernel_initializer, kernel_regularizer=kernel_regularizer)(features) shape = interpretable.get_shape().as_list() if routing == 'avg': pool = keras.layers.GlobalAveragePooling2D()(interpretable) output",
"tf.train.Checkpoint(optimizer=model.optimizer, net=model) manager = tf.train.CheckpointManager(ckpt, model_dir, max_to_keep=3) ckpt.restore(manager.latest_checkpoint) if manager.latest_checkpoint: print(\"Restored from {}\".format(manager.latest_checkpoint))",
"or params.routing.type == 'EM': model_name += '_iter{}'.format(params.routing.iter_num) model_name += '_temper{}'.format(params.routing.temper) model_name += '_atoms{}'.format(params.caps.atoms)",
"common import layers, losses, utils, train, attacks from common.ops.routing import activated_entropy, coupling_entropy import",
"== 'DR': child_pose, child_prob = layers.CapsuleGroups(height=shape[1], width=shape[2], channel=shape[3], atoms=16, method='channel', activation='squash')(interpretable) log.add_hist('child_activation', child_prob)",
"bs=bs, finetune=finetune, idx=idx) if black_box: print('load black box source model') model_src, data_shape, model_dir",
"backbone='InceptionV3', iter_num=2, temper=temper, atoms=16, routing='DR', finetune=0, parts=128, bs=64) if __name__ == \"__main__\": main()",
"coupling_entropy(c) results.append(entropy) results = np.concatenate(results, 0) mean = np.mean(results) std = np.std(results) print('{:.4}/{:.3}'.format(mean,",
"sys sys.path.append(os.getcwd()) import tensorflow as tf tf.get_logger().setLevel('ERROR') from tensorflow import keras from common.inputs.voc2010",
"WEIGHT_DECAY = 1e-4 kernel_regularizer = keras.regularizers.l2(WEIGHT_DECAY) kernel_initializer = keras.initializers.he_normal() BASE_NAME = 'ex4_3' def",
"atoms=atoms, parts=parts, bs=bs, finetune=finetune, idx=idx) if black_box: print('load black box source model') model_src,",
"kernel_size=1, activation='relu', kernel_initializer=kernel_initializer, kernel_regularizer=kernel_regularizer)(features) shape = interpretable.get_shape().as_list() if routing == 'avg': pool =",
"np.mean(results) std = np.std(results) print('{:.4}/{:.3}'.format(mean, std)) def compute_entropies(root): tempers = [0.0, 20.0, 40.0,",
"+= '_fine{}'.format(params.model.fine) model_name += '_part{}'.format(params.caps.parts) model_name += '_{}'.format(params.routing.type) if params.routing.type == 'DR' or",
"layer_num-fine: layer.trainable = False else: for w in layer.weights: if 'kernel' in w.name:",
"from tensorflow import keras from common.inputs.voc2010 import voc_parts from common import layers, losses,",
"params): model_name = build_model_name(params) inputs, probs, tensor_log = build(num_out, params.model.backbone, params.model.fine, params.routing.type, params.routing.iter_num,",
"299, 3) base = keras.applications.InceptionV3(include_top=False, input_shape=in_shape) layer_num = len(base.layers) for i, layer in",
"params.routing.type, params.routing.iter_num, params.routing.temper, params.caps.parts, params.caps.atoms ) model = keras.Model(inputs=inputs, outputs=probs, name=model_name) log_model =",
"cs[-1] if activated: entropy = activated_entropy(c, child_probs) else: entropy = coupling_entropy(c) results.append(entropy) results",
"import keras from common.inputs.voc2010 import voc_parts from common import layers, losses, utils, train,",
"backbone == 'VGG16': in_shape = (224, 224, 3) base = keras.applications.VGG16(include_top=False, input_shape=in_shape) elif",
"params.routing.type == 'EM': model_name += '_iter{}'.format(params.routing.iter_num) model_name += '_temper{}'.format(params.routing.temper) model_name += '_atoms{}'.format(params.caps.atoms) model_name",
"optimizer = keras.optimizers.Adam(0.0001) if type == 'DR' or type == 'EM': loss =",
"loss, optimizer = get_loss_opt(params.routing.type) model.compile(optimizer=optimizer, loss=loss, metrics=[]) model.summary() model.callbacks = [] return model,",
"black_box: print('load black box source model') model_src, data_shape, model_dir = load_model(log=root + log,",
"if routing == 'avg': pool = keras.layers.GlobalAveragePooling2D()(interpretable) output = keras.layers.Dense(num_out)(pool) elif routing ==",
"optimizer = get_loss_opt(params.routing.type) model.compile(optimizer=optimizer, loss=loss, metrics=[]) model.summary() model.callbacks = [] return model, tensor_log",
"base = keras.applications.InceptionV3(include_top=False, input_shape=in_shape) elif backbone == 'ResNet50': in_shape = (224, 224, 3)",
"+ log, backbone=backbone, routing=routing, iter_num=iter_num, temper=temper, atoms=atoms, parts=parts, bs=bs, finetune=finetune, idx=2) else: model_src",
"input_shape=in_shape) else: in_shape = (299, 299, 3) base = keras.applications.InceptionV3(include_top=False, input_shape=in_shape) layer_num =",
"kernel_regularizer=kernel_regularizer)(features) shape = interpretable.get_shape().as_list() if routing == 'avg': pool = keras.layers.GlobalAveragePooling2D()(interpretable) output =",
"import voc_parts from common import layers, losses, utils, train, attacks from common.ops.routing import",
"= losses.MarginLoss(sparse=False, upper_margin=0.9, bottom_margin=0.1, down_weight=0.5) else: loss = keras.losses.CategoricalCrossentropy(from_logits=True) return loss, optimizer def",
"_ = get_loss_opt(routing) _, test_set, info = voc_parts.build_dataset3(root + 'data', batch_size=32, shape=data_shape) acc_adv",
"bs=bs) train_set, test_set, info = voc_parts.build_dataset3(root + 'data', batch_size=32, shape=data_shape) test_model = keras.Model(model.layers[0].input,",
"if params.routing.type == 'DR' or params.routing.type == 'EM': model_name += '_iter{}'.format(params.routing.iter_num) model_name +=",
"epsilons = [0.1, 0.2, 0.3] tempers = [0.0, 20.0, 40.0, 60.0, 80.0] parts_list",
"== 'VGG19': in_shape = (224, 224, 3) base = keras.applications.VGG19(include_top=False, input_shape=in_shape) elif backbone",
"params.model.backbone, params.model.fine, params.routing.type, params.routing.iter_num, params.routing.temper, params.caps.parts, params.caps.atoms ) model = keras.Model(inputs=inputs, outputs=probs, name=model_name)",
"else: entropy = coupling_entropy(c) results.append(entropy) results = np.concatenate(results, 0) mean = np.mean(results) std",
"label_sparse=False, cost=True, model_src=model_src) return results def do_adv(root): epsilons = [0.1, 0.2, 0.3] tempers",
"= parent_probs[-1] return inputs, output, log def main(): args, params = config.parse_args() if",
"numpy as np import config WEIGHT_DECAY = 1e-4 kernel_regularizer = keras.regularizers.l2(WEIGHT_DECAY) kernel_initializer =",
"compute_entropies(root): tempers = [0.0, 20.0, 40.0, 60.0, 80.0] for temper in tempers: print('temper:{}'.format(temper))",
"model_name += '_{}'.format(params.routing.type) if params.routing.type == 'DR' or params.routing.type == 'EM': model_name +=",
"(299, 299, 3) base = keras.applications.InceptionV3(include_top=False, input_shape=in_shape) layer_num = len(base.layers) for i, layer",
"def do_adv(root): epsilons = [0.1, 0.2, 0.3] tempers = [0.0, 20.0, 40.0, 60.0,",
"log='log', routing='DR', finetune=0, parts=128, bs=128, idx=1): data_shape = utils.get_shape(backbone) model_dir = get_model_dir(backbone=backbone, log=log,",
"import activated_entropy, coupling_entropy import numpy as np import config WEIGHT_DECAY = 1e-4 kernel_regularizer",
"max_to_keep=3) ckpt.restore(manager.latest_checkpoint) if manager.latest_checkpoint: print(\"Restored from {}\".format(manager.latest_checkpoint)) def get_model_dir(backbone, log='log', routing='avg', dataset='voc2010', iter_num=None,",
"child_prob)) log.add_hist('parent_activation', parent_probs[-1]) output = parent_probs[-1] return inputs, output, log def main(): args,",
"model.layers[5].output]) results = [] for images, labels in test_set: (child_poses, child_probs), (parent_poses, parent_probs,",
"= BASE_NAME model_name += '_{}'.format(params.model.backbone) model_name += '_fine{}'.format(params.model.fine) model_name += '_part{}'.format(params.caps.parts) model_name +=",
"width=shape[2], channel=shape[3], atoms=16, method='channel', activation='squash')(interpretable) log.add_hist('child_activation', child_prob) transformed_caps = layers.CapsuleTransformDense(num_out=num_out, out_atom=atoms, share_weights=False, initializer=keras.initializers.glorot_normal(),",
"load_ckpt(model, model_dir): model.compile(optimizer=keras.optimizers.Adam(0.0001), loss=keras.losses.CategoricalCrossentropy(from_logits=False), metrics=[]) ckpt = tf.train.Checkpoint(optimizer=model.optimizer, net=model) manager = tf.train.CheckpointManager(ckpt, model_dir,",
"if activated: entropy = activated_entropy(c, child_probs) else: entropy = coupling_entropy(c) results.append(entropy) results =",
"results = [] for images, labels in test_set: (child_poses, child_probs), (parent_poses, parent_probs, cs)",
"model_name += '_{}'.format(params.model.backbone) model_name += '_fine{}'.format(params.model.fine) model_name += '_part{}'.format(params.caps.parts) model_name += '_{}'.format(params.routing.type) if",
"output = parent_probs[-1] return inputs, output, log def main(): args, params = config.parse_args()",
"(299, 299, 3) else: data_shape = (224, 224, 3) train_set, test_set, info =",
"finetune=True, inference_label=False, max_save=1) trainer.metrics['accuracy'] = tf.keras.metrics.CategoricalAccuracy(name='accuracy') if args.train: trainer.fit(train_set, test_set) else: trainer.evaluate(test_set) elif",
"inputs, probs, log = build(6, backbone, finetune, routing, iter_num, temper, parts, atoms) model",
"def build(num_out, backbone, fine, routing, iter_num, temper, parts, atoms): log = utils.TensorLog() if",
"keras.metrics.CategoricalAccuracy(name='acc_adv') if metric == 'acc': results = attacks.evaluate_model_after_attacks(epsilons, acc_adv, test_set, model, loss, method=method,",
"input_shape=in_shape) elif backbone == 'VGG19': in_shape = (224, 224, 3) base = keras.applications.VGG19(include_top=False,",
"idx=1): data_shape = utils.get_shape(backbone) model_dir = get_model_dir(backbone=backbone, log=log, routing=routing, finetune=finetune, parts=parts, bs=bs, iter_num=iter_num,",
"model_src, data_shape, model_dir = load_model(log=root + log, backbone=backbone, routing=routing, iter_num=iter_num, temper=temper, atoms=atoms, parts=parts,",
"== 'DR' or routing == 'EM': model_dir += '_iter{}'.format(iter_num) model_dir += '_temper{}'.format(temper) model_dir",
"import sys sys.path.append(os.getcwd()) import tensorflow as tf tf.get_logger().setLevel('ERROR') from tensorflow import keras from",
"keras.layers.GlobalAveragePooling2D()(interpretable) output = keras.layers.Dense(num_out)(pool) elif routing == 'max': pool = keras.layers.GlobalMaxPooling2D()(interpretable) output =",
"max_save=1) trainer.metrics['accuracy'] = tf.keras.metrics.CategoricalAccuracy(name='accuracy') if args.train: trainer.fit(train_set, test_set) else: trainer.evaluate(test_set) elif params.task ==",
"temper=temper, atoms=atoms, idx=idx) inputs, probs, log = build(6, backbone, finetune, routing, iter_num, temper,",
"temper=1.0, atoms=16, parts=128, bs=64, idx=1): model, data_shape, model_dir = load_model(log=root + log, backbone=backbone,",
"idx=2) else: model_src = model loss, _ = get_loss_opt(routing) _, test_set, info =",
"method=method, steps=steps, label_sparse=False, cost=True, model_src=model_src) else: results = attacks.evaluate_attacks_success_rate(epsilons, test_set, model, loss, method=method,",
"data_shape = utils.get_shape(backbone) model_dir = get_model_dir(backbone=backbone, log=log, routing=routing, finetune=finetune, parts=parts, bs=bs, iter_num=iter_num, temper=temper,",
"parts, atoms) model = keras.Model(inputs=inputs, outputs=probs, name='x') load_ckpt(model, model_dir) return model, data_shape, model_dir",
"def build_model(num_out, params): model_name = build_model_name(params) inputs, probs, tensor_log = build(num_out, params.model.backbone, params.model.fine,",
"= tf.train.Checkpoint(optimizer=model.optimizer, net=model) manager = tf.train.CheckpointManager(ckpt, model_dir, max_to_keep=3) ckpt.restore(manager.latest_checkpoint) if manager.latest_checkpoint: print(\"Restored from",
"224, 3) base = keras.applications.ResNet50(include_top=False, input_shape=in_shape) else: in_shape = (299, 299, 3) base",
"config WEIGHT_DECAY = 1e-4 kernel_regularizer = keras.regularizers.l2(WEIGHT_DECAY) kernel_initializer = keras.initializers.he_normal() BASE_NAME = 'ex4_3'",
"log.add_hist('parent_activation', parent_probs[-1]) output = parent_probs[-1] return inputs, output, log def main(): args, params",
"= voc_parts.build_dataset3(root + 'data', batch_size=32, shape=data_shape) acc_adv = keras.metrics.CategoricalAccuracy(name='acc_adv') if metric == 'acc':",
"atoms=atoms, parts=parts, bs=bs, finetune=finetune, idx=2) else: model_src = model loss, _ = get_loss_opt(routing)",
"== 'DR' or type == 'EM': loss = losses.MarginLoss(sparse=False, upper_margin=0.9, bottom_margin=0.1, down_weight=0.5) else:",
"iter_num=2, activated=True, temper=10.0, atoms=16, routing='DR', finetune=0, parts=128, bs=32): model, data_shape, model_dir = load_model(log=root",
"'score': compute_entropies(os.getcwd()) def load_ckpt(model, model_dir): model.compile(optimizer=keras.optimizers.Adam(0.0001), loss=keras.losses.CategoricalCrossentropy(from_logits=False), metrics=[]) ckpt = tf.train.Checkpoint(optimizer=model.optimizer, net=model) manager",
"for i, layer in enumerate(base.layers): if i < layer_num-fine: layer.trainable = False else:",
"= keras.layers.Dense(num_out)(pool) elif routing == 'max': pool = keras.layers.GlobalMaxPooling2D()(interpretable) output = keras.layers.Dense(num_out)(pool) elif",
"voc_parts.build_dataset3(root + 'data', batch_size=32, shape=data_shape) acc_adv = keras.metrics.CategoricalAccuracy(name='acc_adv') if metric == 'acc': results",
"if params.task == 'train': params.dataset.name = 'voc2010' if params.model.backbone == 'InceptionV3': data_shape =",
"== 'attack': do_adv(os.getcwd()) elif params.task == 'score': compute_entropies(os.getcwd()) def load_ckpt(model, model_dir): model.compile(optimizer=keras.optimizers.Adam(0.0001), loss=keras.losses.CategoricalCrossentropy(from_logits=False),",
"routing == 'EM': model_dir += '_iter{}'.format(iter_num) model_dir += '_temper{}'.format(temper) model_dir += '_atoms{}'.format(atoms) model_dir",
"= 'ex4_3' def build_model_name(params): model_name = BASE_NAME model_name += '_{}'.format(params.model.backbone) model_name += '_fine{}'.format(params.model.fine)",
"from common.ops.routing import activated_entropy, coupling_entropy import numpy as np import config WEIGHT_DECAY =",
"if not os.path.exists(model_dir): raise Exception('model not exist:{}'.format(model_dir)) return model_dir def load_model(backbone, iter_num, temper,",
"def load_model(backbone, iter_num, temper, atoms=16, log='log', routing='DR', finetune=0, parts=128, bs=128, idx=1): data_shape =",
"== 'max': pool = keras.layers.GlobalMaxPooling2D()(interpretable) output = keras.layers.Dense(num_out)(pool) elif routing == 'DR': child_pose,",
"+= '_atoms{}'.format(params.caps.atoms) model_name += '_trial{}'.format(str(params.training.idx)) model_name += '_bs{}'.format(str(params.training.batch_size)) if params.dataset.flip: model_name += '_flip'",
"test_set) else: trainer.evaluate(test_set) elif params.task == 'attack': do_adv(os.getcwd()) elif params.task == 'score': compute_entropies(os.getcwd())",
"model_dir) return model, data_shape, model_dir def evaluate_attack(epsilons, root='', log='log', backbone='InceptionV3', metric='acc', all_target=False, method='FGSM',",
"'success': if all_target: categories = [i for i in range(6)] results = attacks.evaluate_attacks_success_rate_all_target(epsilons,",
"parent_probs[-1] return inputs, output, log def main(): args, params = config.parse_args() if params.task",
"acc_adv = keras.metrics.CategoricalAccuracy(name='acc_adv') if metric == 'acc': results = attacks.evaluate_model_after_attacks(epsilons, acc_adv, test_set, model,",
"else: data_shape = (224, 224, 3) train_set, test_set, info = voc_parts.build_dataset3(batch_size=params.training.batch_size, shape=data_shape, arch=params.model.backbone)",
"acc_adv, test_set, model, loss, method=method, steps=steps, label_sparse=False, cost=True, model_src=model_src) elif metric == 'success':",
"log, backbone=backbone, routing=routing, iter_num=iter_num, temper=temper, atoms=atoms, parts=parts, bs=bs, finetune=finetune, idx=2) else: model_src =",
"model.compile(optimizer=optimizer, loss=loss, metrics=[]) model.summary() model.callbacks = [] return model, tensor_log def build(num_out, backbone,",
"metric == 'success': if all_target: categories = [i for i in range(6)] results",
"= keras.Model(inputs=inputs, outputs=probs, name=model_name) log_model = keras.Model(inputs=inputs, outputs=tensor_log.get_outputs(), name=model_name + '_log') tensor_log.set_model(log_model) loss,",
"loss=keras.losses.CategoricalCrossentropy(from_logits=False), metrics=[]) ckpt = tf.train.Checkpoint(optimizer=model.optimizer, net=model) manager = tf.train.CheckpointManager(ckpt, model_dir, max_to_keep=3) ckpt.restore(manager.latest_checkpoint) if",
"routing == 'DR': child_pose, child_prob = layers.CapsuleGroups(height=shape[1], width=shape[2], channel=shape[3], atoms=16, method='channel', activation='squash')(interpretable) log.add_hist('child_activation',",
"params.routing.type == 'DR' or params.routing.type == 'EM': model_name += '_iter{}'.format(params.routing.iter_num) model_name += '_temper{}'.format(params.routing.temper)",
"idx=1): model, data_shape, model_dir = load_model(log=root + log, backbone=backbone, routing=routing, iter_num=iter_num, temper=temper, atoms=atoms,",
"backbones = ['InceptionV3'] routing = 'DR' for backbone in backbones: print('backbone:', backbone) for",
"+= '_trial{}'.format(str(params.training.idx)) model_name += '_bs{}'.format(str(params.training.batch_size)) if params.dataset.flip: model_name += '_flip' if params.dataset.crop: model_name",
"finetune, parts, routing) if routing == 'DR' or routing == 'EM': model_dir +=",
"routing=routing, finetune=finetune, parts=parts, bs=bs) train_set, test_set, info = voc_parts.build_dataset3(root + 'data', batch_size=32, shape=data_shape)",
"w.name: r = kernel_regularizer(w) layer.add_loss(lambda: r) inputs = keras.Input(in_shape) features = base(inputs) interpretable",
"loss, categories, method=method, steps=steps, label_sparse=False, cost=True, model_src=model_src) else: results = attacks.evaluate_attacks_success_rate(epsilons, test_set, model,",
"attacks from common.ops.routing import activated_entropy, coupling_entropy import numpy as np import config WEIGHT_DECAY",
"parts, routing) if routing == 'DR' or routing == 'EM': model_dir += '_iter{}'.format(iter_num)",
"steps=10, finetune=0, routing='DR', black_box=False, iter_num=10, temper=1.0, atoms=16, parts=128, bs=64, idx=1): model, data_shape, model_dir",
"loss, method=method, steps=steps, label_sparse=False, cost=True, model_src=model_src) return results def do_adv(root): epsilons = [0.1,",
"keras.Model(model.layers[0].input, [model.layers[3].output, model.layers[5].output]) results = [] for images, labels in test_set: (child_poses, child_probs),",
"bs=128, idx=1): data_shape = utils.get_shape(backbone) model_dir = get_model_dir(backbone=backbone, log=log, routing=routing, finetune=finetune, parts=parts, bs=bs,",
"log='log', routing='avg', dataset='voc2010', iter_num=None, temper=None, atoms=None, finetune=0, parts=128, bs=32, idx=1): model_dir = '{}/{}/{}_{}_fine{}_part{}_{}'.format(log,",
"def evaluate_attack(epsilons, root='', log='log', backbone='InceptionV3', metric='acc', all_target=False, method='FGSM', steps=10, finetune=0, routing='DR', black_box=False, iter_num=10,",
"results = np.concatenate(results, 0) mean = np.mean(results) std = np.std(results) print('{:.4}/{:.3}'.format(mean, std)) def",
"import config WEIGHT_DECAY = 1e-4 kernel_regularizer = keras.regularizers.l2(WEIGHT_DECAY) kernel_initializer = keras.initializers.he_normal() BASE_NAME =",
"features = base(inputs) interpretable = keras.layers.Conv2D(filters=parts, kernel_size=1, activation='relu', kernel_initializer=kernel_initializer, kernel_regularizer=kernel_regularizer)(features) shape = interpretable.get_shape().as_list()",
"in_shape = (299, 299, 3) base = keras.applications.InceptionV3(include_top=False, input_shape=in_shape) elif backbone == 'ResNet50':",
"+= '_trial{}_bs{}_flip_crop'.format(idx, bs) if not os.path.exists(model_dir): raise Exception('model not exist:{}'.format(model_dir)) return model_dir def",
"model_dir, max_to_keep=3) ckpt.restore(manager.latest_checkpoint) if manager.latest_checkpoint: print(\"Restored from {}\".format(manager.latest_checkpoint)) def get_model_dir(backbone, log='log', routing='avg', dataset='voc2010',",
"np.std(results) print('{:.4}/{:.3}'.format(mean, std)) def compute_entropies(root): tempers = [0.0, 20.0, 40.0, 60.0, 80.0] for",
"train, attacks from common.ops.routing import activated_entropy, coupling_entropy import numpy as np import config",
"iter_num=10, temper=1.0, atoms=16, parts=128, bs=64, idx=1): model, data_shape, model_dir = load_model(log=root + log,",
"224, 3) train_set, test_set, info = voc_parts.build_dataset3(batch_size=params.training.batch_size, shape=data_shape, arch=params.model.backbone) model, tensor_log = build_model(num_out=info.features['label'].num_classes,",
"= (299, 299, 3) base = keras.applications.InceptionV3(include_top=False, input_shape=in_shape) layer_num = len(base.layers) for i,",
"results = attacks.evaluate_attacks_success_rate(epsilons, test_set, model, loss, method=method, steps=steps, label_sparse=False, cost=True, model_src=model_src) return results",
"enumerate(base.layers): if i < layer_num-fine: layer.trainable = False else: for w in layer.weights:",
"in range(6)] results = attacks.evaluate_attacks_success_rate_all_target(epsilons, test_set, model, loss, categories, method=method, steps=steps, label_sparse=False, cost=True,",
"+= '_temper{}'.format(params.routing.temper) model_name += '_atoms{}'.format(params.caps.atoms) model_name += '_trial{}'.format(str(params.training.idx)) model_name += '_bs{}'.format(str(params.training.batch_size)) if params.dataset.flip:",
"== 'acc': results = attacks.evaluate_model_after_attacks(epsilons, acc_adv, test_set, model, loss, method=method, steps=steps, label_sparse=False, cost=True,",
"probs, tensor_log = build(num_out, params.model.backbone, params.model.fine, params.routing.type, params.routing.iter_num, params.routing.temper, params.caps.parts, params.caps.atoms ) model",
"layers.CapsuleTransformDense(num_out=num_out, out_atom=atoms, share_weights=False, initializer=keras.initializers.glorot_normal(), regularizer=kernel_regularizer)(child_pose) parent_poses, parent_probs, cs = layers.DynamicRouting(num_routing=iter_num, softmax_in=False, temper=temper, activation='squash',",
"parent_probs[-1]) output = parent_probs[-1] return inputs, output, log def main(): args, params =",
"range(6)] results = attacks.evaluate_attacks_success_rate_all_target(epsilons, test_set, model, loss, categories, method=method, steps=steps, label_sparse=False, cost=True, model_src=model_src)",
"params, info, tensor_log, finetune=True, inference_label=False, max_save=1) trainer.metrics['accuracy'] = tf.keras.metrics.CategoricalAccuracy(name='accuracy') if args.train: trainer.fit(train_set, test_set)",
"3) base = keras.applications.InceptionV3(include_top=False, input_shape=in_shape) layer_num = len(base.layers) for i, layer in enumerate(base.layers):",
"= keras.Model(inputs=inputs, outputs=probs, name='x') load_ckpt(model, model_dir) return model, data_shape, model_dir def evaluate_attack(epsilons, root='',",
"+ 'data', batch_size=32, shape=data_shape) test_model = keras.Model(model.layers[0].input, [model.layers[3].output, model.layers[5].output]) results = [] for",
"keras.layers.GlobalMaxPooling2D()(interpretable) output = keras.layers.Dense(num_out)(pool) elif routing == 'DR': child_pose, child_prob = layers.CapsuleGroups(height=shape[1], width=shape[2],",
"finetune=finetune, idx=idx) if black_box: print('load black box source model') model_src, data_shape, model_dir =",
"batch_size=32, shape=data_shape) acc_adv = keras.metrics.CategoricalAccuracy(name='acc_adv') if metric == 'acc': results = attacks.evaluate_model_after_attacks(epsilons, acc_adv,",
"if metric == 'acc': results = attacks.evaluate_model_after_attacks(epsilons, acc_adv, test_set, model, loss, method=method, steps=steps,",
"= keras.layers.Dense(num_out)(pool) elif routing == 'DR': child_pose, child_prob = layers.CapsuleGroups(height=shape[1], width=shape[2], channel=shape[3], atoms=16,",
"inputs, output, log def main(): args, params = config.parse_args() if params.task == 'train':",
"'_flip' if params.dataset.crop: model_name += '_crop' return model_name def get_loss_opt(type): optimizer = keras.optimizers.Adam(0.0001)",
"for images, labels in test_set: (child_poses, child_probs), (parent_poses, parent_probs, cs) = test_model(images) c",
"metric == 'acc': results = attacks.evaluate_model_after_attacks(epsilons, acc_adv, test_set, model, loss, method=method, steps=steps, label_sparse=False,",
"return loss, optimizer def build_model(num_out, params): model_name = build_model_name(params) inputs, probs, tensor_log =",
"= keras.Model(inputs=inputs, outputs=tensor_log.get_outputs(), name=model_name + '_log') tensor_log.set_model(log_model) loss, optimizer = get_loss_opt(params.routing.type) model.compile(optimizer=optimizer, loss=loss,",
"load_ckpt(model, model_dir) return model, data_shape, model_dir def evaluate_attack(epsilons, root='', log='log', backbone='InceptionV3', metric='acc', all_target=False,",
"loss, optimizer def build_model(num_out, params): model_name = build_model_name(params) inputs, probs, tensor_log = build(num_out,",
"import tensorflow as tf tf.get_logger().setLevel('ERROR') from tensorflow import keras from common.inputs.voc2010 import voc_parts"
] |
[
"tensorflow string representation into numbers tf_image_string = tf.placeholder(tf.string) decoder = tf.image.decode_jpeg(tf_image_string) fig =",
"in range(args.rows * args.columns): ax = fig.add_subplot(args.rows, args.columns, i+1) img = session.run(decoder, feed_dict",
"-*- \"\"\" Displays some of the augmented images. Can be used to visually",
"tf.placeholder(tf.string) decoder = tf.image.decode_jpeg(tf_image_string) fig = plt.figure(figsize=(16,10)) with tf.Session() as session: session.run(tf.global_variables_initializer()) for",
"of the augmented images. Can be used to visually check that augmentation is",
"images. Can be used to visually check that augmentation is working fine. Created",
"of columns', default = 4) args = parser.parse_args() with open(args.input_file, \"rb\") as f:",
"'--rows', type = int, help = 'number of rows', default = 3) parser.add_argument('-c',",
"lbechberger \"\"\" import argparse, pickle import matplotlib.pyplot as plt import tensorflow as tf",
"* args.columns): ax = fig.add_subplot(args.rows, args.columns, i+1) img = session.run(decoder, feed_dict = {tf_image_string",
"\"\"\" import argparse, pickle import matplotlib.pyplot as plt import tensorflow as tf parser",
"columns', default = 4) args = parser.parse_args() with open(args.input_file, \"rb\") as f: images",
"feed_dict = {tf_image_string : images[i]}) # deal with greyscale images if img.shape[2] ==",
"== 1: img = img.reshape((img.shape[0], img.shape[1])) ax.imshow(img, cmap = \"gray\") else: ax.imshow(img) plt.show()",
"as session: session.run(tf.global_variables_initializer()) for i in range(args.rows * args.columns): ax = fig.add_subplot(args.rows, args.columns,",
"type = int, help = 'number of columns', default = 4) args =",
"fig.add_subplot(args.rows, args.columns, i+1) img = session.run(decoder, feed_dict = {tf_image_string : images[i]}) # deal",
"as tf parser = argparse.ArgumentParser(description='Visualizing augmented images') parser.add_argument('input_file', help = 'pickle file containing",
"'number of columns', default = 4) args = parser.parse_args() with open(args.input_file, \"rb\") as",
"tensorflow as tf parser = argparse.ArgumentParser(description='Visualizing augmented images') parser.add_argument('input_file', help = 'pickle file",
"to convert tensorflow string representation into numbers tf_image_string = tf.placeholder(tf.string) decoder = tf.image.decode_jpeg(tf_image_string)",
"be used to visually check that augmentation is working fine. Created on Wed",
"open(args.input_file, \"rb\") as f: images = pickle.load(f) # need to convert tensorflow string",
"argparse, pickle import matplotlib.pyplot as plt import tensorflow as tf parser = argparse.ArgumentParser(description='Visualizing",
"= 'number of columns', default = 4) args = parser.parse_args() with open(args.input_file, \"rb\")",
"as plt import tensorflow as tf parser = argparse.ArgumentParser(description='Visualizing augmented images') parser.add_argument('input_file', help",
"args = parser.parse_args() with open(args.input_file, \"rb\") as f: images = pickle.load(f) # need",
"{tf_image_string : images[i]}) # deal with greyscale images if img.shape[2] == 1: img",
"augmentation is working fine. Created on Wed May 8 12:12:26 2019 @author: lbechberger",
"session.run(tf.global_variables_initializer()) for i in range(args.rows * args.columns): ax = fig.add_subplot(args.rows, args.columns, i+1) img",
"'pickle file containing the augmented images to display') parser.add_argument('-r', '--rows', type = int,",
"as f: images = pickle.load(f) # need to convert tensorflow string representation into",
"images = pickle.load(f) # need to convert tensorflow string representation into numbers tf_image_string",
"= tf.placeholder(tf.string) decoder = tf.image.decode_jpeg(tf_image_string) fig = plt.figure(figsize=(16,10)) with tf.Session() as session: session.run(tf.global_variables_initializer())",
"fine. Created on Wed May 8 12:12:26 2019 @author: lbechberger \"\"\" import argparse,",
"is working fine. Created on Wed May 8 12:12:26 2019 @author: lbechberger \"\"\"",
"fig = plt.figure(figsize=(16,10)) with tf.Session() as session: session.run(tf.global_variables_initializer()) for i in range(args.rows *",
"f: images = pickle.load(f) # need to convert tensorflow string representation into numbers",
"pickle.load(f) # need to convert tensorflow string representation into numbers tf_image_string = tf.placeholder(tf.string)",
"with greyscale images if img.shape[2] == 1: img = img.reshape((img.shape[0], img.shape[1])) ax.imshow(img, cmap",
"help = 'number of columns', default = 4) args = parser.parse_args() with open(args.input_file,",
"= {tf_image_string : images[i]}) # deal with greyscale images if img.shape[2] == 1:",
"coding: utf-8 -*- \"\"\" Displays some of the augmented images. Can be used",
"numbers tf_image_string = tf.placeholder(tf.string) decoder = tf.image.decode_jpeg(tf_image_string) fig = plt.figure(figsize=(16,10)) with tf.Session() as",
"tf.image.decode_jpeg(tf_image_string) fig = plt.figure(figsize=(16,10)) with tf.Session() as session: session.run(tf.global_variables_initializer()) for i in range(args.rows",
"parser.add_argument('-c', '--columns', type = int, help = 'number of columns', default = 4)",
"the augmented images. Can be used to visually check that augmentation is working",
"with open(args.input_file, \"rb\") as f: images = pickle.load(f) # need to convert tensorflow",
"= int, help = 'number of rows', default = 3) parser.add_argument('-c', '--columns', type",
"tf.Session() as session: session.run(tf.global_variables_initializer()) for i in range(args.rows * args.columns): ax = fig.add_subplot(args.rows,",
"matplotlib.pyplot as plt import tensorflow as tf parser = argparse.ArgumentParser(description='Visualizing augmented images') parser.add_argument('input_file',",
"parser.add_argument('-r', '--rows', type = int, help = 'number of rows', default = 3)",
"type = int, help = 'number of rows', default = 3) parser.add_argument('-c', '--columns',",
"range(args.rows * args.columns): ax = fig.add_subplot(args.rows, args.columns, i+1) img = session.run(decoder, feed_dict =",
"deal with greyscale images if img.shape[2] == 1: img = img.reshape((img.shape[0], img.shape[1])) ax.imshow(img,",
"12:12:26 2019 @author: lbechberger \"\"\" import argparse, pickle import matplotlib.pyplot as plt import",
"-*- coding: utf-8 -*- \"\"\" Displays some of the augmented images. Can be",
"for i in range(args.rows * args.columns): ax = fig.add_subplot(args.rows, args.columns, i+1) img =",
"augmented images to display') parser.add_argument('-r', '--rows', type = int, help = 'number of",
"Displays some of the augmented images. Can be used to visually check that",
"on Wed May 8 12:12:26 2019 @author: lbechberger \"\"\" import argparse, pickle import",
"3) parser.add_argument('-c', '--columns', type = int, help = 'number of columns', default =",
"import argparse, pickle import matplotlib.pyplot as plt import tensorflow as tf parser =",
"display') parser.add_argument('-r', '--rows', type = int, help = 'number of rows', default =",
"\"\"\" Displays some of the augmented images. Can be used to visually check",
"= argparse.ArgumentParser(description='Visualizing augmented images') parser.add_argument('input_file', help = 'pickle file containing the augmented images",
"import matplotlib.pyplot as plt import tensorflow as tf parser = argparse.ArgumentParser(description='Visualizing augmented images')",
"to display') parser.add_argument('-r', '--rows', type = int, help = 'number of rows', default",
"img.shape[2] == 1: img = img.reshape((img.shape[0], img.shape[1])) ax.imshow(img, cmap = \"gray\") else: ax.imshow(img)",
"'number of rows', default = 3) parser.add_argument('-c', '--columns', type = int, help =",
"Wed May 8 12:12:26 2019 @author: lbechberger \"\"\" import argparse, pickle import matplotlib.pyplot",
"= fig.add_subplot(args.rows, args.columns, i+1) img = session.run(decoder, feed_dict = {tf_image_string : images[i]}) #",
"8 12:12:26 2019 @author: lbechberger \"\"\" import argparse, pickle import matplotlib.pyplot as plt",
"parser.add_argument('input_file', help = 'pickle file containing the augmented images to display') parser.add_argument('-r', '--rows',",
"pickle import matplotlib.pyplot as plt import tensorflow as tf parser = argparse.ArgumentParser(description='Visualizing augmented",
"Created on Wed May 8 12:12:26 2019 @author: lbechberger \"\"\" import argparse, pickle",
"= tf.image.decode_jpeg(tf_image_string) fig = plt.figure(figsize=(16,10)) with tf.Session() as session: session.run(tf.global_variables_initializer()) for i in",
"containing the augmented images to display') parser.add_argument('-r', '--rows', type = int, help =",
"= plt.figure(figsize=(16,10)) with tf.Session() as session: session.run(tf.global_variables_initializer()) for i in range(args.rows * args.columns):",
"i in range(args.rows * args.columns): ax = fig.add_subplot(args.rows, args.columns, i+1) img = session.run(decoder,",
"used to visually check that augmentation is working fine. Created on Wed May",
"May 8 12:12:26 2019 @author: lbechberger \"\"\" import argparse, pickle import matplotlib.pyplot as",
"= parser.parse_args() with open(args.input_file, \"rb\") as f: images = pickle.load(f) # need to",
"representation into numbers tf_image_string = tf.placeholder(tf.string) decoder = tf.image.decode_jpeg(tf_image_string) fig = plt.figure(figsize=(16,10)) with",
"plt import tensorflow as tf parser = argparse.ArgumentParser(description='Visualizing augmented images') parser.add_argument('input_file', help =",
"file containing the augmented images to display') parser.add_argument('-r', '--rows', type = int, help",
"some of the augmented images. Can be used to visually check that augmentation",
": images[i]}) # deal with greyscale images if img.shape[2] == 1: img =",
"int, help = 'number of rows', default = 3) parser.add_argument('-c', '--columns', type =",
"import tensorflow as tf parser = argparse.ArgumentParser(description='Visualizing augmented images') parser.add_argument('input_file', help = 'pickle",
"= 3) parser.add_argument('-c', '--columns', type = int, help = 'number of columns', default",
"to visually check that augmentation is working fine. Created on Wed May 8",
"if img.shape[2] == 1: img = img.reshape((img.shape[0], img.shape[1])) ax.imshow(img, cmap = \"gray\") else:",
"with tf.Session() as session: session.run(tf.global_variables_initializer()) for i in range(args.rows * args.columns): ax =",
"tf_image_string = tf.placeholder(tf.string) decoder = tf.image.decode_jpeg(tf_image_string) fig = plt.figure(figsize=(16,10)) with tf.Session() as session:",
"help = 'pickle file containing the augmented images to display') parser.add_argument('-r', '--rows', type",
"'--columns', type = int, help = 'number of columns', default = 4) args",
"tf parser = argparse.ArgumentParser(description='Visualizing augmented images') parser.add_argument('input_file', help = 'pickle file containing the",
"greyscale images if img.shape[2] == 1: img = img.reshape((img.shape[0], img.shape[1])) ax.imshow(img, cmap =",
"parser.parse_args() with open(args.input_file, \"rb\") as f: images = pickle.load(f) # need to convert",
"ax = fig.add_subplot(args.rows, args.columns, i+1) img = session.run(decoder, feed_dict = {tf_image_string : images[i]})",
"\"rb\") as f: images = pickle.load(f) # need to convert tensorflow string representation",
"working fine. Created on Wed May 8 12:12:26 2019 @author: lbechberger \"\"\" import",
"= int, help = 'number of columns', default = 4) args = parser.parse_args()",
"utf-8 -*- \"\"\" Displays some of the augmented images. Can be used to",
"session.run(decoder, feed_dict = {tf_image_string : images[i]}) # deal with greyscale images if img.shape[2]",
"Can be used to visually check that augmentation is working fine. Created on",
"= 'pickle file containing the augmented images to display') parser.add_argument('-r', '--rows', type =",
"session: session.run(tf.global_variables_initializer()) for i in range(args.rows * args.columns): ax = fig.add_subplot(args.rows, args.columns, i+1)",
"augmented images') parser.add_argument('input_file', help = 'pickle file containing the augmented images to display')",
"argparse.ArgumentParser(description='Visualizing augmented images') parser.add_argument('input_file', help = 'pickle file containing the augmented images to",
"# deal with greyscale images if img.shape[2] == 1: img = img.reshape((img.shape[0], img.shape[1]))",
"= session.run(decoder, feed_dict = {tf_image_string : images[i]}) # deal with greyscale images if",
"@author: lbechberger \"\"\" import argparse, pickle import matplotlib.pyplot as plt import tensorflow as",
"img = session.run(decoder, feed_dict = {tf_image_string : images[i]}) # deal with greyscale images",
"parser = argparse.ArgumentParser(description='Visualizing augmented images') parser.add_argument('input_file', help = 'pickle file containing the augmented",
"the augmented images to display') parser.add_argument('-r', '--rows', type = int, help = 'number",
"# need to convert tensorflow string representation into numbers tf_image_string = tf.placeholder(tf.string) decoder",
"decoder = tf.image.decode_jpeg(tf_image_string) fig = plt.figure(figsize=(16,10)) with tf.Session() as session: session.run(tf.global_variables_initializer()) for i",
"string representation into numbers tf_image_string = tf.placeholder(tf.string) decoder = tf.image.decode_jpeg(tf_image_string) fig = plt.figure(figsize=(16,10))",
"default = 4) args = parser.parse_args() with open(args.input_file, \"rb\") as f: images =",
"plt.figure(figsize=(16,10)) with tf.Session() as session: session.run(tf.global_variables_initializer()) for i in range(args.rows * args.columns): ax",
"check that augmentation is working fine. Created on Wed May 8 12:12:26 2019",
"into numbers tf_image_string = tf.placeholder(tf.string) decoder = tf.image.decode_jpeg(tf_image_string) fig = plt.figure(figsize=(16,10)) with tf.Session()",
"that augmentation is working fine. Created on Wed May 8 12:12:26 2019 @author:",
"args.columns): ax = fig.add_subplot(args.rows, args.columns, i+1) img = session.run(decoder, feed_dict = {tf_image_string :",
"images if img.shape[2] == 1: img = img.reshape((img.shape[0], img.shape[1])) ax.imshow(img, cmap = \"gray\")",
"images to display') parser.add_argument('-r', '--rows', type = int, help = 'number of rows',",
"2019 @author: lbechberger \"\"\" import argparse, pickle import matplotlib.pyplot as plt import tensorflow",
"int, help = 'number of columns', default = 4) args = parser.parse_args() with",
"need to convert tensorflow string representation into numbers tf_image_string = tf.placeholder(tf.string) decoder =",
"= 'number of rows', default = 3) parser.add_argument('-c', '--columns', type = int, help",
"of rows', default = 3) parser.add_argument('-c', '--columns', type = int, help = 'number",
"= pickle.load(f) # need to convert tensorflow string representation into numbers tf_image_string =",
"images[i]}) # deal with greyscale images if img.shape[2] == 1: img = img.reshape((img.shape[0],",
"4) args = parser.parse_args() with open(args.input_file, \"rb\") as f: images = pickle.load(f) #",
"convert tensorflow string representation into numbers tf_image_string = tf.placeholder(tf.string) decoder = tf.image.decode_jpeg(tf_image_string) fig",
"images') parser.add_argument('input_file', help = 'pickle file containing the augmented images to display') parser.add_argument('-r',",
"i+1) img = session.run(decoder, feed_dict = {tf_image_string : images[i]}) # deal with greyscale",
"rows', default = 3) parser.add_argument('-c', '--columns', type = int, help = 'number of",
"visually check that augmentation is working fine. Created on Wed May 8 12:12:26",
"help = 'number of rows', default = 3) parser.add_argument('-c', '--columns', type = int,",
"# -*- coding: utf-8 -*- \"\"\" Displays some of the augmented images. Can",
"= 4) args = parser.parse_args() with open(args.input_file, \"rb\") as f: images = pickle.load(f)",
"args.columns, i+1) img = session.run(decoder, feed_dict = {tf_image_string : images[i]}) # deal with",
"augmented images. Can be used to visually check that augmentation is working fine.",
"default = 3) parser.add_argument('-c', '--columns', type = int, help = 'number of columns',"
] |
[
"sleep import urllib.parse import urllib.request bot = commands.Bot(command_prefix=\"n!\", case_insensitive=True) client = discord.Client() @bot.event",
"discord.Embed( title = 'Help', description = 'Help For Commands!', colour = 0x33F2FF )",
"client = discord.Client() @bot.event async def on_ready(): print(\"bot ready!\") @bot.command() async def hello(ctx):",
"youtube for videos') @bot.command() async def ping(ctx): await ctx.send(f\"Pong! - {round(bot.latency * 1000)}ms!\")",
"await ctx.send(f\"Pong! - {round(bot.latency * 1000)}ms!\") @bot.command() async def youtube(ctx, *, search): query_string",
"= discord.Embed( title = 'UselessEmbed', colour = 0x33F2FF ) embed.set_footer(text=\"\") embed.set_author(name=ctx.message.author.name) embed.add_field(name='Why', value='Did",
"ctx.channel.purge(limit=amount) @bot.command() async def kick(ctx, member : discord.Member, *, reason=None): await member.kick(reason=reason) @bot.command()",
"search }) htm_content = urllib.request.urlopen( 'http://www.youtube.com/results?' + query_string ) search_results = re.findall(\"href=\\\"\\\\/watch\\\\?v=(.{11})\", htm_content.read().decode())",
"embed.set_image(url='https://cdn.discordapp.com/avatars/582670290950291476/5723169a306c581dd6d0d9ae41fa6a3c.png?size=1024') await ctx.send(embed=embed) @bot.command() async def dm(ctx,member : discord.Member,*,message= \"\"): await member.send(f\"{message}\") await",
"member.kick(reason=reason) @bot.command() async def ban(ctx, member : discord.Member, *, reason=None): await member.ban(reason=reason) @bot.command()",
"os, random, time from discord.ext import commands, tasks from asyncio import sleep import",
"@bot.command() async def misc(ctx): embed = discord.Embed( title = 'Misc', description = 'Misc",
"commands') await ctx.send(embed=embed) @bot.command() async def misc(ctx): embed = discord.Embed( title = 'Misc',",
"'Help For Commands!', colour = 0x33F2FF ) embed.set_footer(text=\"\") embed.set_author(name=ctx.message.author.name) embed.add_field(name='Misc', value='`n!misc` for misc",
"'Misc', description = 'Misc Commands', colour = 0x33F2FF ) embed.set_footer(text=\"Misc\") embed.set_author(name=ctx.message.author.name) embed.add_field(name='Youtube', value='`n!Youtube",
"'UselessEmbed', colour = 0x33F2FF ) embed.set_footer(text=\"\") embed.set_author(name=ctx.message.author.name) embed.add_field(name='Why', value='Did u use this command?')",
"ctx.channel.purge(limit=1) person = await bot.fetch_user(member.id) await ctx.channel.send(f\"The DM to **{person}** was sent!\") keep_alive.keep_alive()",
"urllib.parse.urlencode({ 'search_query': search }) htm_content = urllib.request.urlopen( 'http://www.youtube.com/results?' + query_string ) search_results =",
"@bot.command() async def CommandHelp(ctx): embed = discord.Embed( title = 'Help', description = 'Help",
"= re.findall(\"href=\\\"\\\\/watch\\\\?v=(.{11})\", htm_content.read().decode()) await ctx.send('http://www.youtube.com/watch?v=' + search_results[0]) @bot.command() async def purge(ctx, amount): await",
"sent!\") keep_alive.keep_alive() token = os.environ.get(\"token\") bot.run(token, bot=True, reconnect=True) @client.event async def on_member_join(member): await",
"async def embed(ctx): embed = discord.Embed( title = 'UselessEmbed', colour = 0x33F2FF )",
"member : discord.Member, *, reason=None): await member.kick(reason=reason) @bot.command() async def ban(ctx, member :",
"embed = discord.Embed( title = 'UselessEmbed', colour = 0x33F2FF ) embed.set_footer(text=\"\") embed.set_author(name=ctx.message.author.name) embed.add_field(name='Why',",
"import discord, keep_alive, os, random, time from discord.ext import commands, tasks from asyncio",
"time from discord.ext import commands, tasks from asyncio import sleep import urllib.parse import",
"def purge(ctx, amount): await ctx.channel.purge(limit=amount) @bot.command() async def kick(ctx, member : discord.Member, *,",
"async def kick(ctx, member : discord.Member, *, reason=None): await member.kick(reason=reason) @bot.command() async def",
"this will search youtube for videos') @bot.command() async def ping(ctx): await ctx.send(f\"Pong! -",
"'search_query': search }) htm_content = urllib.request.urlopen( 'http://www.youtube.com/results?' + query_string ) search_results = re.findall(\"href=\\\"\\\\/watch\\\\?v=(.{11})\",",
"*, reason=None): await member.kick(reason=reason) @bot.command() async def ban(ctx, member : discord.Member, *, reason=None):",
"youtube(ctx, *, search): query_string = urllib.parse.urlencode({ 'search_query': search }) htm_content = urllib.request.urlopen( 'http://www.youtube.com/results?'",
"@bot.command() async def purge(ctx, amount): await ctx.channel.purge(limit=amount) @bot.command() async def kick(ctx, member :",
"colour = 0x33F2FF ) embed.set_footer(text=\"\") embed.set_author(name=ctx.message.author.name) embed.add_field(name='Why', value='Did u use this command?') embed.set_image(url='https://cdn.discordapp.com/avatars/582670290950291476/5723169a306c581dd6d0d9ae41fa6a3c.png?size=1024')",
"= 'Help For Commands!', colour = 0x33F2FF ) embed.set_footer(text=\"\") embed.set_author(name=ctx.message.author.name) embed.add_field(name='Misc', value='`n!misc` for",
"def ping(ctx): await ctx.send(f\"Pong! - {round(bot.latency * 1000)}ms!\") @bot.command() async def youtube(ctx, *,",
"await bot.fetch_user(member.id) await ctx.channel.send(f\"The DM to **{person}** was sent!\") keep_alive.keep_alive() token = os.environ.get(\"token\")",
"to **{person}** was sent!\") keep_alive.keep_alive() token = os.environ.get(\"token\") bot.run(token, bot=True, reconnect=True) @client.event async",
"embed.set_footer(text=\"Misc\") embed.set_author(name=ctx.message.author.name) embed.add_field(name='Youtube', value='`n!Youtube (video) this will search youtube for videos') @bot.command() async",
"{round(bot.latency * 1000)}ms!\") @bot.command() async def youtube(ctx, *, search): query_string = urllib.parse.urlencode({ 'search_query':",
"}) htm_content = urllib.request.urlopen( 'http://www.youtube.com/results?' + query_string ) search_results = re.findall(\"href=\\\"\\\\/watch\\\\?v=(.{11})\", htm_content.read().decode()) await",
"await ctx.send(f\"Hello\") @bot.command() async def CommandHelp(ctx): embed = discord.Embed( title = 'Help', description",
"ready!\") @bot.command() async def hello(ctx): await ctx.send(f\"Hello\") @bot.command() async def CommandHelp(ctx): embed =",
"value='`n!Youtube (video) this will search youtube for videos') @bot.command() async def ping(ctx): await",
"https://discord.gg/YYfyYjJuH6\") @bot.command() async def embed(ctx): embed = discord.Embed( title = 'UselessEmbed', colour =",
"async def ban(ctx, member : discord.Member, *, reason=None): await member.ban(reason=reason) @bot.command() async def",
"async def ping(ctx): await ctx.send(f\"Pong! - {round(bot.latency * 1000)}ms!\") @bot.command() async def youtube(ctx,",
"async def CommandHelp(ctx): embed = discord.Embed( title = 'Help', description = 'Help For",
"def misc(ctx): embed = discord.Embed( title = 'Misc', description = 'Misc Commands', colour",
"search_results[0]) @bot.command() async def purge(ctx, amount): await ctx.channel.purge(limit=amount) @bot.command() async def kick(ctx, member",
"from asyncio import sleep import urllib.parse import urllib.request bot = commands.Bot(command_prefix=\"n!\", case_insensitive=True) client",
"= 'UselessEmbed', colour = 0x33F2FF ) embed.set_footer(text=\"\") embed.set_author(name=ctx.message.author.name) embed.add_field(name='Why', value='Did u use this",
"def on_ready(): print(\"bot ready!\") @bot.command() async def hello(ctx): await ctx.send(f\"Hello\") @bot.command() async def",
"on_ready(): print(\"bot ready!\") @bot.command() async def hello(ctx): await ctx.send(f\"Hello\") @bot.command() async def CommandHelp(ctx):",
"embed = discord.Embed( title = 'Help', description = 'Help For Commands!', colour =",
"@bot.command() async def ping(ctx): await ctx.send(f\"Pong! - {round(bot.latency * 1000)}ms!\") @bot.command() async def",
"kick(ctx, member : discord.Member, *, reason=None): await member.kick(reason=reason) @bot.command() async def ban(ctx, member",
"@bot.command() async def neon(ctx): await ctx.send(f\"Join NeonGDPS today! https://discord.gg/YYfyYjJuH6\") @bot.command() async def embed(ctx):",
"videos') @bot.command() async def ping(ctx): await ctx.send(f\"Pong! - {round(bot.latency * 1000)}ms!\") @bot.command() async",
"= discord.Embed( title = 'Misc', description = 'Misc Commands', colour = 0x33F2FF )",
"misc commands') await ctx.send(embed=embed) @bot.command() async def misc(ctx): embed = discord.Embed( title =",
"will search youtube for videos') @bot.command() async def ping(ctx): await ctx.send(f\"Pong! - {round(bot.latency",
"discord.Embed( title = 'UselessEmbed', colour = 0x33F2FF ) embed.set_footer(text=\"\") embed.set_author(name=ctx.message.author.name) embed.add_field(name='Why', value='Did u",
"- {round(bot.latency * 1000)}ms!\") @bot.command() async def youtube(ctx, *, search): query_string = urllib.parse.urlencode({",
"def embed(ctx): embed = discord.Embed( title = 'UselessEmbed', colour = 0x33F2FF ) embed.set_footer(text=\"\")",
"for misc commands') await ctx.send(embed=embed) @bot.command() async def misc(ctx): embed = discord.Embed( title",
"misc(ctx): embed = discord.Embed( title = 'Misc', description = 'Misc Commands', colour =",
"htm_content = urllib.request.urlopen( 'http://www.youtube.com/results?' + query_string ) search_results = re.findall(\"href=\\\"\\\\/watch\\\\?v=(.{11})\", htm_content.read().decode()) await ctx.send('http://www.youtube.com/watch?v='",
"colour = 0x33F2FF ) embed.set_footer(text=\"\") embed.set_author(name=ctx.message.author.name) embed.add_field(name='Misc', value='`n!misc` for misc commands') await ctx.send(embed=embed)",
"@bot.command() async def hello(ctx): await ctx.send(f\"Hello\") @bot.command() async def CommandHelp(ctx): embed = discord.Embed(",
"await member.ban(reason=reason) @bot.command() async def neon(ctx): await ctx.send(f\"Join NeonGDPS today! https://discord.gg/YYfyYjJuH6\") @bot.command() async",
"embed.set_author(name=ctx.message.author.name) embed.add_field(name='Why', value='Did u use this command?') embed.set_image(url='https://cdn.discordapp.com/avatars/582670290950291476/5723169a306c581dd6d0d9ae41fa6a3c.png?size=1024') await ctx.send(embed=embed) @bot.command() async def",
"ctx.send(embed=embed) @bot.command() async def dm(ctx,member : discord.Member,*,message= \"\"): await member.send(f\"{message}\") await ctx.channel.purge(limit=1) person",
"token = os.environ.get(\"token\") bot.run(token, bot=True, reconnect=True) @client.event async def on_member_join(member): await member.send(f\"Welcome To",
"value='`n!misc` for misc commands') await ctx.send(embed=embed) @bot.command() async def misc(ctx): embed = discord.Embed(",
"ctx.send(f\"Pong! - {round(bot.latency * 1000)}ms!\") @bot.command() async def youtube(ctx, *, search): query_string =",
"reason=None): await member.kick(reason=reason) @bot.command() async def ban(ctx, member : discord.Member, *, reason=None): await",
"= 'Misc', description = 'Misc Commands', colour = 0x33F2FF ) embed.set_footer(text=\"Misc\") embed.set_author(name=ctx.message.author.name) embed.add_field(name='Youtube',",
"asyncio import sleep import urllib.parse import urllib.request bot = commands.Bot(command_prefix=\"n!\", case_insensitive=True) client =",
"embed.add_field(name='Youtube', value='`n!Youtube (video) this will search youtube for videos') @bot.command() async def ping(ctx):",
"@bot.command() async def ban(ctx, member : discord.Member, *, reason=None): await member.ban(reason=reason) @bot.command() async",
"htm_content.read().decode()) await ctx.send('http://www.youtube.com/watch?v=' + search_results[0]) @bot.command() async def purge(ctx, amount): await ctx.channel.purge(limit=amount) @bot.command()",
"person = await bot.fetch_user(member.id) await ctx.channel.send(f\"The DM to **{person}** was sent!\") keep_alive.keep_alive() token",
"re.findall(\"href=\\\"\\\\/watch\\\\?v=(.{11})\", htm_content.read().decode()) await ctx.send('http://www.youtube.com/watch?v=' + search_results[0]) @bot.command() async def purge(ctx, amount): await ctx.channel.purge(limit=amount)",
"def kick(ctx, member : discord.Member, *, reason=None): await member.kick(reason=reason) @bot.command() async def ban(ctx,",
"Commands', colour = 0x33F2FF ) embed.set_footer(text=\"Misc\") embed.set_author(name=ctx.message.author.name) embed.add_field(name='Youtube', value='`n!Youtube (video) this will search",
"async def neon(ctx): await ctx.send(f\"Join NeonGDPS today! https://discord.gg/YYfyYjJuH6\") @bot.command() async def embed(ctx): embed",
"0x33F2FF ) embed.set_footer(text=\"Misc\") embed.set_author(name=ctx.message.author.name) embed.add_field(name='Youtube', value='`n!Youtube (video) this will search youtube for videos')",
"async def dm(ctx,member : discord.Member,*,message= \"\"): await member.send(f\"{message}\") await ctx.channel.purge(limit=1) person = await",
"use this command?') embed.set_image(url='https://cdn.discordapp.com/avatars/582670290950291476/5723169a306c581dd6d0d9ae41fa6a3c.png?size=1024') await ctx.send(embed=embed) @bot.command() async def dm(ctx,member : discord.Member,*,message= \"\"):",
": discord.Member,*,message= \"\"): await member.send(f\"{message}\") await ctx.channel.purge(limit=1) person = await bot.fetch_user(member.id) await ctx.channel.send(f\"The",
"bot.fetch_user(member.id) await ctx.channel.send(f\"The DM to **{person}** was sent!\") keep_alive.keep_alive() token = os.environ.get(\"token\") bot.run(token,",
"await ctx.send(embed=embed) @bot.command() async def misc(ctx): embed = discord.Embed( title = 'Misc', description",
"@bot.command() async def youtube(ctx, *, search): query_string = urllib.parse.urlencode({ 'search_query': search }) htm_content",
"embed.add_field(name='Why', value='Did u use this command?') embed.set_image(url='https://cdn.discordapp.com/avatars/582670290950291476/5723169a306c581dd6d0d9ae41fa6a3c.png?size=1024') await ctx.send(embed=embed) @bot.command() async def dm(ctx,member",
"discord.Member, *, reason=None): await member.ban(reason=reason) @bot.command() async def neon(ctx): await ctx.send(f\"Join NeonGDPS today!",
"search): query_string = urllib.parse.urlencode({ 'search_query': search }) htm_content = urllib.request.urlopen( 'http://www.youtube.com/results?' + query_string",
"command?') embed.set_image(url='https://cdn.discordapp.com/avatars/582670290950291476/5723169a306c581dd6d0d9ae41fa6a3c.png?size=1024') await ctx.send(embed=embed) @bot.command() async def dm(ctx,member : discord.Member,*,message= \"\"): await member.send(f\"{message}\")",
"await ctx.channel.purge(limit=amount) @bot.command() async def kick(ctx, member : discord.Member, *, reason=None): await member.kick(reason=reason)",
"+ search_results[0]) @bot.command() async def purge(ctx, amount): await ctx.channel.purge(limit=amount) @bot.command() async def kick(ctx,",
": discord.Member, *, reason=None): await member.ban(reason=reason) @bot.command() async def neon(ctx): await ctx.send(f\"Join NeonGDPS",
"neon(ctx): await ctx.send(f\"Join NeonGDPS today! https://discord.gg/YYfyYjJuH6\") @bot.command() async def embed(ctx): embed = discord.Embed(",
"bot = commands.Bot(command_prefix=\"n!\", case_insensitive=True) client = discord.Client() @bot.event async def on_ready(): print(\"bot ready!\")",
"urllib.parse import urllib.request bot = commands.Bot(command_prefix=\"n!\", case_insensitive=True) client = discord.Client() @bot.event async def",
"async def misc(ctx): embed = discord.Embed( title = 'Misc', description = 'Misc Commands',",
"'Help', description = 'Help For Commands!', colour = 0x33F2FF ) embed.set_footer(text=\"\") embed.set_author(name=ctx.message.author.name) embed.add_field(name='Misc',",
") search_results = re.findall(\"href=\\\"\\\\/watch\\\\?v=(.{11})\", htm_content.read().decode()) await ctx.send('http://www.youtube.com/watch?v=' + search_results[0]) @bot.command() async def purge(ctx,",
"ban(ctx, member : discord.Member, *, reason=None): await member.ban(reason=reason) @bot.command() async def neon(ctx): await",
"search youtube for videos') @bot.command() async def ping(ctx): await ctx.send(f\"Pong! - {round(bot.latency *",
"= 0x33F2FF ) embed.set_footer(text=\"\") embed.set_author(name=ctx.message.author.name) embed.add_field(name='Misc', value='`n!misc` for misc commands') await ctx.send(embed=embed) @bot.command()",
"def youtube(ctx, *, search): query_string = urllib.parse.urlencode({ 'search_query': search }) htm_content = urllib.request.urlopen(",
"import sleep import urllib.parse import urllib.request bot = commands.Bot(command_prefix=\"n!\", case_insensitive=True) client = discord.Client()",
"NeonGDPS today! https://discord.gg/YYfyYjJuH6\") @bot.command() async def embed(ctx): embed = discord.Embed( title = 'UselessEmbed',",
"= 'Help', description = 'Help For Commands!', colour = 0x33F2FF ) embed.set_footer(text=\"\") embed.set_author(name=ctx.message.author.name)",
"colour = 0x33F2FF ) embed.set_footer(text=\"Misc\") embed.set_author(name=ctx.message.author.name) embed.add_field(name='Youtube', value='`n!Youtube (video) this will search youtube",
"async def purge(ctx, amount): await ctx.channel.purge(limit=amount) @bot.command() async def kick(ctx, member : discord.Member,",
"import urllib.request bot = commands.Bot(command_prefix=\"n!\", case_insensitive=True) client = discord.Client() @bot.event async def on_ready():",
"for videos') @bot.command() async def ping(ctx): await ctx.send(f\"Pong! - {round(bot.latency * 1000)}ms!\") @bot.command()",
"@bot.command() async def embed(ctx): embed = discord.Embed( title = 'UselessEmbed', colour = 0x33F2FF",
"= os.environ.get(\"token\") bot.run(token, bot=True, reconnect=True) @client.event async def on_member_join(member): await member.send(f\"Welcome To The",
"import urllib.parse import urllib.request bot = commands.Bot(command_prefix=\"n!\", case_insensitive=True) client = discord.Client() @bot.event async",
"keep_alive.keep_alive() token = os.environ.get(\"token\") bot.run(token, bot=True, reconnect=True) @client.event async def on_member_join(member): await member.send(f\"Welcome",
"= commands.Bot(command_prefix=\"n!\", case_insensitive=True) client = discord.Client() @bot.event async def on_ready(): print(\"bot ready!\") @bot.command()",
"@bot.event async def on_ready(): print(\"bot ready!\") @bot.command() async def hello(ctx): await ctx.send(f\"Hello\") @bot.command()",
"(video) this will search youtube for videos') @bot.command() async def ping(ctx): await ctx.send(f\"Pong!",
"@bot.command() async def dm(ctx,member : discord.Member,*,message= \"\"): await member.send(f\"{message}\") await ctx.channel.purge(limit=1) person =",
"embed(ctx): embed = discord.Embed( title = 'UselessEmbed', colour = 0x33F2FF ) embed.set_footer(text=\"\") embed.set_author(name=ctx.message.author.name)",
") embed.set_footer(text=\"\") embed.set_author(name=ctx.message.author.name) embed.add_field(name='Why', value='Did u use this command?') embed.set_image(url='https://cdn.discordapp.com/avatars/582670290950291476/5723169a306c581dd6d0d9ae41fa6a3c.png?size=1024') await ctx.send(embed=embed) @bot.command()",
"this command?') embed.set_image(url='https://cdn.discordapp.com/avatars/582670290950291476/5723169a306c581dd6d0d9ae41fa6a3c.png?size=1024') await ctx.send(embed=embed) @bot.command() async def dm(ctx,member : discord.Member,*,message= \"\"): await",
"title = 'Help', description = 'Help For Commands!', colour = 0x33F2FF ) embed.set_footer(text=\"\")",
"await ctx.channel.purge(limit=1) person = await bot.fetch_user(member.id) await ctx.channel.send(f\"The DM to **{person}** was sent!\")",
"import commands, tasks from asyncio import sleep import urllib.parse import urllib.request bot =",
"= 0x33F2FF ) embed.set_footer(text=\"\") embed.set_author(name=ctx.message.author.name) embed.add_field(name='Why', value='Did u use this command?') embed.set_image(url='https://cdn.discordapp.com/avatars/582670290950291476/5723169a306c581dd6d0d9ae41fa6a3c.png?size=1024') await",
"ctx.send(f\"Hello\") @bot.command() async def CommandHelp(ctx): embed = discord.Embed( title = 'Help', description =",
"today! https://discord.gg/YYfyYjJuH6\") @bot.command() async def embed(ctx): embed = discord.Embed( title = 'UselessEmbed', colour",
"embed.set_footer(text=\"\") embed.set_author(name=ctx.message.author.name) embed.add_field(name='Why', value='Did u use this command?') embed.set_image(url='https://cdn.discordapp.com/avatars/582670290950291476/5723169a306c581dd6d0d9ae41fa6a3c.png?size=1024') await ctx.send(embed=embed) @bot.command() async",
"<filename>main.py import discord, keep_alive, os, random, time from discord.ext import commands, tasks from",
"description = 'Help For Commands!', colour = 0x33F2FF ) embed.set_footer(text=\"\") embed.set_author(name=ctx.message.author.name) embed.add_field(name='Misc', value='`n!misc`",
"*, search): query_string = urllib.parse.urlencode({ 'search_query': search }) htm_content = urllib.request.urlopen( 'http://www.youtube.com/results?' +",
"ping(ctx): await ctx.send(f\"Pong! - {round(bot.latency * 1000)}ms!\") @bot.command() async def youtube(ctx, *, search):",
"value='Did u use this command?') embed.set_image(url='https://cdn.discordapp.com/avatars/582670290950291476/5723169a306c581dd6d0d9ae41fa6a3c.png?size=1024') await ctx.send(embed=embed) @bot.command() async def dm(ctx,member :",
"ctx.send(embed=embed) @bot.command() async def misc(ctx): embed = discord.Embed( title = 'Misc', description =",
"*, reason=None): await member.ban(reason=reason) @bot.command() async def neon(ctx): await ctx.send(f\"Join NeonGDPS today! https://discord.gg/YYfyYjJuH6\")",
"member.send(f\"{message}\") await ctx.channel.purge(limit=1) person = await bot.fetch_user(member.id) await ctx.channel.send(f\"The DM to **{person}** was",
"amount): await ctx.channel.purge(limit=amount) @bot.command() async def kick(ctx, member : discord.Member, *, reason=None): await",
"embed.set_footer(text=\"\") embed.set_author(name=ctx.message.author.name) embed.add_field(name='Misc', value='`n!misc` for misc commands') await ctx.send(embed=embed) @bot.command() async def misc(ctx):",
"await ctx.send(embed=embed) @bot.command() async def dm(ctx,member : discord.Member,*,message= \"\"): await member.send(f\"{message}\") await ctx.channel.purge(limit=1)",
"embed.set_author(name=ctx.message.author.name) embed.add_field(name='Youtube', value='`n!Youtube (video) this will search youtube for videos') @bot.command() async def",
": discord.Member, *, reason=None): await member.kick(reason=reason) @bot.command() async def ban(ctx, member : discord.Member,",
"title = 'Misc', description = 'Misc Commands', colour = 0x33F2FF ) embed.set_footer(text=\"Misc\") embed.set_author(name=ctx.message.author.name)",
"await member.kick(reason=reason) @bot.command() async def ban(ctx, member : discord.Member, *, reason=None): await member.ban(reason=reason)",
"urllib.request bot = commands.Bot(command_prefix=\"n!\", case_insensitive=True) client = discord.Client() @bot.event async def on_ready(): print(\"bot",
"For Commands!', colour = 0x33F2FF ) embed.set_footer(text=\"\") embed.set_author(name=ctx.message.author.name) embed.add_field(name='Misc', value='`n!misc` for misc commands')",
"discord.ext import commands, tasks from asyncio import sleep import urllib.parse import urllib.request bot",
"ctx.send('http://www.youtube.com/watch?v=' + search_results[0]) @bot.command() async def purge(ctx, amount): await ctx.channel.purge(limit=amount) @bot.command() async def",
"= discord.Client() @bot.event async def on_ready(): print(\"bot ready!\") @bot.command() async def hello(ctx): await",
"os.environ.get(\"token\") bot.run(token, bot=True, reconnect=True) @client.event async def on_member_join(member): await member.send(f\"Welcome To The discord!\")",
"commands.Bot(command_prefix=\"n!\", case_insensitive=True) client = discord.Client() @bot.event async def on_ready(): print(\"bot ready!\") @bot.command() async",
"async def hello(ctx): await ctx.send(f\"Hello\") @bot.command() async def CommandHelp(ctx): embed = discord.Embed( title",
"ctx.send(f\"Join NeonGDPS today! https://discord.gg/YYfyYjJuH6\") @bot.command() async def embed(ctx): embed = discord.Embed( title =",
"random, time from discord.ext import commands, tasks from asyncio import sleep import urllib.parse",
"query_string ) search_results = re.findall(\"href=\\\"\\\\/watch\\\\?v=(.{11})\", htm_content.read().decode()) await ctx.send('http://www.youtube.com/watch?v=' + search_results[0]) @bot.command() async def",
"DM to **{person}** was sent!\") keep_alive.keep_alive() token = os.environ.get(\"token\") bot.run(token, bot=True, reconnect=True) @client.event",
"await ctx.send(f\"Join NeonGDPS today! https://discord.gg/YYfyYjJuH6\") @bot.command() async def embed(ctx): embed = discord.Embed( title",
"print(\"bot ready!\") @bot.command() async def hello(ctx): await ctx.send(f\"Hello\") @bot.command() async def CommandHelp(ctx): embed",
"search_results = re.findall(\"href=\\\"\\\\/watch\\\\?v=(.{11})\", htm_content.read().decode()) await ctx.send('http://www.youtube.com/watch?v=' + search_results[0]) @bot.command() async def purge(ctx, amount):",
"u use this command?') embed.set_image(url='https://cdn.discordapp.com/avatars/582670290950291476/5723169a306c581dd6d0d9ae41fa6a3c.png?size=1024') await ctx.send(embed=embed) @bot.command() async def dm(ctx,member : discord.Member,*,message=",
"dm(ctx,member : discord.Member,*,message= \"\"): await member.send(f\"{message}\") await ctx.channel.purge(limit=1) person = await bot.fetch_user(member.id) await",
"was sent!\") keep_alive.keep_alive() token = os.environ.get(\"token\") bot.run(token, bot=True, reconnect=True) @client.event async def on_member_join(member):",
"def dm(ctx,member : discord.Member,*,message= \"\"): await member.send(f\"{message}\") await ctx.channel.purge(limit=1) person = await bot.fetch_user(member.id)",
"= urllib.request.urlopen( 'http://www.youtube.com/results?' + query_string ) search_results = re.findall(\"href=\\\"\\\\/watch\\\\?v=(.{11})\", htm_content.read().decode()) await ctx.send('http://www.youtube.com/watch?v=' +",
"= urllib.parse.urlencode({ 'search_query': search }) htm_content = urllib.request.urlopen( 'http://www.youtube.com/results?' + query_string ) search_results",
"discord, keep_alive, os, random, time from discord.ext import commands, tasks from asyncio import",
"discord.Client() @bot.event async def on_ready(): print(\"bot ready!\") @bot.command() async def hello(ctx): await ctx.send(f\"Hello\")",
"0x33F2FF ) embed.set_footer(text=\"\") embed.set_author(name=ctx.message.author.name) embed.add_field(name='Misc', value='`n!misc` for misc commands') await ctx.send(embed=embed) @bot.command() async",
"def ban(ctx, member : discord.Member, *, reason=None): await member.ban(reason=reason) @bot.command() async def neon(ctx):",
"title = 'UselessEmbed', colour = 0x33F2FF ) embed.set_footer(text=\"\") embed.set_author(name=ctx.message.author.name) embed.add_field(name='Why', value='Did u use",
"query_string = urllib.parse.urlencode({ 'search_query': search }) htm_content = urllib.request.urlopen( 'http://www.youtube.com/results?' + query_string )",
"async def on_ready(): print(\"bot ready!\") @bot.command() async def hello(ctx): await ctx.send(f\"Hello\") @bot.command() async",
"discord.Member, *, reason=None): await member.kick(reason=reason) @bot.command() async def ban(ctx, member : discord.Member, *,",
"async def youtube(ctx, *, search): query_string = urllib.parse.urlencode({ 'search_query': search }) htm_content =",
"from discord.ext import commands, tasks from asyncio import sleep import urllib.parse import urllib.request",
"def neon(ctx): await ctx.send(f\"Join NeonGDPS today! https://discord.gg/YYfyYjJuH6\") @bot.command() async def embed(ctx): embed =",
"embed.add_field(name='Misc', value='`n!misc` for misc commands') await ctx.send(embed=embed) @bot.command() async def misc(ctx): embed =",
"'http://www.youtube.com/results?' + query_string ) search_results = re.findall(\"href=\\\"\\\\/watch\\\\?v=(.{11})\", htm_content.read().decode()) await ctx.send('http://www.youtube.com/watch?v=' + search_results[0]) @bot.command()",
"def CommandHelp(ctx): embed = discord.Embed( title = 'Help', description = 'Help For Commands!',",
"embed = discord.Embed( title = 'Misc', description = 'Misc Commands', colour = 0x33F2FF",
"discord.Embed( title = 'Misc', description = 'Misc Commands', colour = 0x33F2FF ) embed.set_footer(text=\"Misc\")",
"description = 'Misc Commands', colour = 0x33F2FF ) embed.set_footer(text=\"Misc\") embed.set_author(name=ctx.message.author.name) embed.add_field(name='Youtube', value='`n!Youtube (video)",
"member.ban(reason=reason) @bot.command() async def neon(ctx): await ctx.send(f\"Join NeonGDPS today! https://discord.gg/YYfyYjJuH6\") @bot.command() async def",
"\"\"): await member.send(f\"{message}\") await ctx.channel.purge(limit=1) person = await bot.fetch_user(member.id) await ctx.channel.send(f\"The DM to",
"'Misc Commands', colour = 0x33F2FF ) embed.set_footer(text=\"Misc\") embed.set_author(name=ctx.message.author.name) embed.add_field(name='Youtube', value='`n!Youtube (video) this will",
"1000)}ms!\") @bot.command() async def youtube(ctx, *, search): query_string = urllib.parse.urlencode({ 'search_query': search })",
"await ctx.channel.send(f\"The DM to **{person}** was sent!\") keep_alive.keep_alive() token = os.environ.get(\"token\") bot.run(token, bot=True,",
"def hello(ctx): await ctx.send(f\"Hello\") @bot.command() async def CommandHelp(ctx): embed = discord.Embed( title =",
"keep_alive, os, random, time from discord.ext import commands, tasks from asyncio import sleep",
"+ query_string ) search_results = re.findall(\"href=\\\"\\\\/watch\\\\?v=(.{11})\", htm_content.read().decode()) await ctx.send('http://www.youtube.com/watch?v=' + search_results[0]) @bot.command() async",
"0x33F2FF ) embed.set_footer(text=\"\") embed.set_author(name=ctx.message.author.name) embed.add_field(name='Why', value='Did u use this command?') embed.set_image(url='https://cdn.discordapp.com/avatars/582670290950291476/5723169a306c581dd6d0d9ae41fa6a3c.png?size=1024') await ctx.send(embed=embed)",
") embed.set_footer(text=\"Misc\") embed.set_author(name=ctx.message.author.name) embed.add_field(name='Youtube', value='`n!Youtube (video) this will search youtube for videos') @bot.command()",
"member : discord.Member, *, reason=None): await member.ban(reason=reason) @bot.command() async def neon(ctx): await ctx.send(f\"Join",
"= discord.Embed( title = 'Help', description = 'Help For Commands!', colour = 0x33F2FF",
"* 1000)}ms!\") @bot.command() async def youtube(ctx, *, search): query_string = urllib.parse.urlencode({ 'search_query': search",
"embed.set_author(name=ctx.message.author.name) embed.add_field(name='Misc', value='`n!misc` for misc commands') await ctx.send(embed=embed) @bot.command() async def misc(ctx): embed",
"reason=None): await member.ban(reason=reason) @bot.command() async def neon(ctx): await ctx.send(f\"Join NeonGDPS today! https://discord.gg/YYfyYjJuH6\") @bot.command()",
"= await bot.fetch_user(member.id) await ctx.channel.send(f\"The DM to **{person}** was sent!\") keep_alive.keep_alive() token =",
"purge(ctx, amount): await ctx.channel.purge(limit=amount) @bot.command() async def kick(ctx, member : discord.Member, *, reason=None):",
") embed.set_footer(text=\"\") embed.set_author(name=ctx.message.author.name) embed.add_field(name='Misc', value='`n!misc` for misc commands') await ctx.send(embed=embed) @bot.command() async def",
"commands, tasks from asyncio import sleep import urllib.parse import urllib.request bot = commands.Bot(command_prefix=\"n!\",",
"CommandHelp(ctx): embed = discord.Embed( title = 'Help', description = 'Help For Commands!', colour",
"Commands!', colour = 0x33F2FF ) embed.set_footer(text=\"\") embed.set_author(name=ctx.message.author.name) embed.add_field(name='Misc', value='`n!misc` for misc commands') await",
"await ctx.send('http://www.youtube.com/watch?v=' + search_results[0]) @bot.command() async def purge(ctx, amount): await ctx.channel.purge(limit=amount) @bot.command() async",
"discord.Member,*,message= \"\"): await member.send(f\"{message}\") await ctx.channel.purge(limit=1) person = await bot.fetch_user(member.id) await ctx.channel.send(f\"The DM",
"ctx.channel.send(f\"The DM to **{person}** was sent!\") keep_alive.keep_alive() token = os.environ.get(\"token\") bot.run(token, bot=True, reconnect=True)",
"tasks from asyncio import sleep import urllib.parse import urllib.request bot = commands.Bot(command_prefix=\"n!\", case_insensitive=True)",
"= 'Misc Commands', colour = 0x33F2FF ) embed.set_footer(text=\"Misc\") embed.set_author(name=ctx.message.author.name) embed.add_field(name='Youtube', value='`n!Youtube (video) this",
"= 0x33F2FF ) embed.set_footer(text=\"Misc\") embed.set_author(name=ctx.message.author.name) embed.add_field(name='Youtube', value='`n!Youtube (video) this will search youtube for",
"hello(ctx): await ctx.send(f\"Hello\") @bot.command() async def CommandHelp(ctx): embed = discord.Embed( title = 'Help',",
"urllib.request.urlopen( 'http://www.youtube.com/results?' + query_string ) search_results = re.findall(\"href=\\\"\\\\/watch\\\\?v=(.{11})\", htm_content.read().decode()) await ctx.send('http://www.youtube.com/watch?v=' + search_results[0])",
"@bot.command() async def kick(ctx, member : discord.Member, *, reason=None): await member.kick(reason=reason) @bot.command() async",
"await member.send(f\"{message}\") await ctx.channel.purge(limit=1) person = await bot.fetch_user(member.id) await ctx.channel.send(f\"The DM to **{person}**",
"**{person}** was sent!\") keep_alive.keep_alive() token = os.environ.get(\"token\") bot.run(token, bot=True, reconnect=True) @client.event async def",
"case_insensitive=True) client = discord.Client() @bot.event async def on_ready(): print(\"bot ready!\") @bot.command() async def"
] |
[
"combinations f = open(\"p105_text.txt\") fr = f.readline() sets = [] while fr: fs",
"m in range(1,len(ret_set)+1): for s in list(combinations(ret_set, m)): if sum(s) == sum(com): return",
"True spec_sum_sets_sum = 0 for i in range(len(sets)): if test_2(sets[i]) and test_1(sets[i]): #",
"not test_rest(s,c): return False return True # If B contains more elements than",
"= int(fs[i]) fs.sort() sets.append(fs) fr = f.readline() def test_rest(set, com): ret_set = list(set)",
"= f.readline() def test_rest(set, com): ret_set = list(set) for num in com: del(ret_set[ret_set.index(num)])",
"in range(1,(len(s) / 2) + 1): for c in combinations(s, size): if not",
"= sum(s[right:]) if not sum_1 > sum_2: return False left += 1 right",
"left += 1 right -= 1 return True spec_sum_sets_sum = 0 for i",
"order for speed # print i, '\\t', sets[i] spec_sum_sets_sum += sum(sets[i]) # for",
"right >= left: sum_1 = sum(s[:left]) sum_2 = sum(s[right:]) if not sum_1 >",
"= l - 1 while right >= left: sum_1 = sum(s[:left]) sum_2 =",
"range(len(fs)): fs[i] = int(fs[i]) fs.sort() sets.append(fs) fr = f.readline() def test_rest(set, com): ret_set",
"c in combinations(s, size): if not test_rest(s,c): return False return True # If",
"sets.append(fs) fr = f.readline() def test_rest(set, com): ret_set = list(set) for num in",
"in list(combinations(ret_set, m)): if sum(s) == sum(com): return False return True # sum(B)",
"1): for c in combinations(s, size): if not test_rest(s,c): return False return True",
"subsets B and C def test_1(s): for size in range(1,(len(s) / 2) +",
"ret_set = list(set) for num in com: del(ret_set[ret_set.index(num)]) for m in range(1,len(ret_set)+1): for",
"If B contains more elements than C then S(B) > S(C). def test_2(s):",
"from itertools import combinations f = open(\"p105_text.txt\") fr = f.readline() sets = []",
"len(s) left = 2 right = l - 1 while right >= left:",
"-= 1 return True spec_sum_sets_sum = 0 for i in range(len(sets)): if test_2(sets[i])",
"1 return True spec_sum_sets_sum = 0 for i in range(len(sets)): if test_2(sets[i]) and",
"False return True # sum(B) != sum(C) for non-empty, disjoint subsets B and",
"2) + 1): for c in combinations(s, size): if not test_rest(s,c): return False",
"num in com: del(ret_set[ret_set.index(num)]) for m in range(1,len(ret_set)+1): for s in list(combinations(ret_set, m)):",
"# for set in sets: # if test_2(set) and test_1(set): # spec_sum_sets_sum +=",
"C def test_1(s): for size in range(1,(len(s) / 2) + 1): for c",
"right -= 1 return True spec_sum_sets_sum = 0 for i in range(len(sets)): if",
"for num in com: del(ret_set[ret_set.index(num)]) for m in range(1,len(ret_set)+1): for s in list(combinations(ret_set,",
"test_1(s): for size in range(1,(len(s) / 2) + 1): for c in combinations(s,",
"sum_1 > sum_2: return False left += 1 right -= 1 return True",
"reverse order for speed # print i, '\\t', sets[i] spec_sum_sets_sum += sum(sets[i]) #",
"# sum(B) != sum(C) for non-empty, disjoint subsets B and C def test_1(s):",
"sum(B) != sum(C) for non-empty, disjoint subsets B and C def test_1(s): for",
"+ 1): for c in combinations(s, size): if not test_rest(s,c): return False return",
"set in sets: # if test_2(set) and test_1(set): # spec_sum_sets_sum += sum(set) print",
"B contains more elements than C then S(B) > S(C). def test_2(s): l",
"import combinations f = open(\"p105_text.txt\") fr = f.readline() sets = [] while fr:",
"= open(\"p105_text.txt\") fr = f.readline() sets = [] while fr: fs = (fr.strip()).split()",
"f.readline() sets = [] while fr: fs = (fr.strip()).split() for i in range(len(fs)):",
"i in range(len(sets)): if test_2(sets[i]) and test_1(sets[i]): # reverse order for speed #",
"print i, '\\t', sets[i] spec_sum_sets_sum += sum(sets[i]) # for set in sets: #",
"sum(C) for non-empty, disjoint subsets B and C def test_1(s): for size in",
"sum_1 = sum(s[:left]) sum_2 = sum(s[right:]) if not sum_1 > sum_2: return False",
"> S(C). def test_2(s): l = len(s) left = 2 right = l",
"non-empty, disjoint subsets B and C def test_1(s): for size in range(1,(len(s) /",
"test_2(sets[i]) and test_1(sets[i]): # reverse order for speed # print i, '\\t', sets[i]",
"# reverse order for speed # print i, '\\t', sets[i] spec_sum_sets_sum += sum(sets[i])",
"= sum(s[:left]) sum_2 = sum(s[right:]) if not sum_1 > sum_2: return False left",
"return False return True # sum(B) != sum(C) for non-empty, disjoint subsets B",
"sum_2: return False left += 1 right -= 1 return True spec_sum_sets_sum =",
"+= sum(sets[i]) # for set in sets: # if test_2(set) and test_1(set): #",
"in sets: # if test_2(set) and test_1(set): # spec_sum_sets_sum += sum(set) print spec_sum_sets_sum",
"def test_2(s): l = len(s) left = 2 right = l - 1",
"com: del(ret_set[ret_set.index(num)]) for m in range(1,len(ret_set)+1): for s in list(combinations(ret_set, m)): if sum(s)",
"speed # print i, '\\t', sets[i] spec_sum_sets_sum += sum(sets[i]) # for set in",
"# print i, '\\t', sets[i] spec_sum_sets_sum += sum(sets[i]) # for set in sets:",
"sum(s[right:]) if not sum_1 > sum_2: return False left += 1 right -=",
"for c in combinations(s, size): if not test_rest(s,c): return False return True #",
"False return True # If B contains more elements than C then S(B)",
"1 right -= 1 return True spec_sum_sets_sum = 0 for i in range(len(sets)):",
"spec_sum_sets_sum += sum(sets[i]) # for set in sets: # if test_2(set) and test_1(set):",
"f.readline() def test_rest(set, com): ret_set = list(set) for num in com: del(ret_set[ret_set.index(num)]) for",
"f = open(\"p105_text.txt\") fr = f.readline() sets = [] while fr: fs =",
"size): if not test_rest(s,c): return False return True # If B contains more",
"fs[i] = int(fs[i]) fs.sort() sets.append(fs) fr = f.readline() def test_rest(set, com): ret_set =",
"return True # If B contains more elements than C then S(B) >",
"test_1(sets[i]): # reverse order for speed # print i, '\\t', sets[i] spec_sum_sets_sum +=",
"for non-empty, disjoint subsets B and C def test_1(s): for size in range(1,(len(s)",
"sum(s[:left]) sum_2 = sum(s[right:]) if not sum_1 > sum_2: return False left +=",
"and C def test_1(s): for size in range(1,(len(s) / 2) + 1): for",
"= len(s) left = 2 right = l - 1 while right >=",
"False left += 1 right -= 1 return True spec_sum_sets_sum = 0 for",
"[] while fr: fs = (fr.strip()).split() for i in range(len(fs)): fs[i] = int(fs[i])",
"True # If B contains more elements than C then S(B) > S(C).",
"0 for i in range(len(sets)): if test_2(sets[i]) and test_1(sets[i]): # reverse order for",
"fr: fs = (fr.strip()).split() for i in range(len(fs)): fs[i] = int(fs[i]) fs.sort() sets.append(fs)",
"= 2 right = l - 1 while right >= left: sum_1 =",
"> sum_2: return False left += 1 right -= 1 return True spec_sum_sets_sum",
"and test_1(sets[i]): # reverse order for speed # print i, '\\t', sets[i] spec_sum_sets_sum",
"if not sum_1 > sum_2: return False left += 1 right -= 1",
"in range(len(fs)): fs[i] = int(fs[i]) fs.sort() sets.append(fs) fr = f.readline() def test_rest(set, com):",
"sum(sets[i]) # for set in sets: # if test_2(set) and test_1(set): # spec_sum_sets_sum",
"1 while right >= left: sum_1 = sum(s[:left]) sum_2 = sum(s[right:]) if not",
"fs = (fr.strip()).split() for i in range(len(fs)): fs[i] = int(fs[i]) fs.sort() sets.append(fs) fr",
"list(set) for num in com: del(ret_set[ret_set.index(num)]) for m in range(1,len(ret_set)+1): for s in",
"sum(com): return False return True # sum(B) != sum(C) for non-empty, disjoint subsets",
"'\\t', sets[i] spec_sum_sets_sum += sum(sets[i]) # for set in sets: # if test_2(set)",
"if not test_rest(s,c): return False return True # If B contains more elements",
"for set in sets: # if test_2(set) and test_1(set): # spec_sum_sets_sum += sum(set)",
"fs.sort() sets.append(fs) fr = f.readline() def test_rest(set, com): ret_set = list(set) for num",
"!= sum(C) for non-empty, disjoint subsets B and C def test_1(s): for size",
"for size in range(1,(len(s) / 2) + 1): for c in combinations(s, size):",
"elements than C then S(B) > S(C). def test_2(s): l = len(s) left",
"for i in range(len(sets)): if test_2(sets[i]) and test_1(sets[i]): # reverse order for speed",
"for i in range(len(fs)): fs[i] = int(fs[i]) fs.sort() sets.append(fs) fr = f.readline() def",
"+= 1 right -= 1 return True spec_sum_sets_sum = 0 for i in",
"- 1 while right >= left: sum_1 = sum(s[:left]) sum_2 = sum(s[right:]) if",
"= list(set) for num in com: del(ret_set[ret_set.index(num)]) for m in range(1,len(ret_set)+1): for s",
"in range(len(sets)): if test_2(sets[i]) and test_1(sets[i]): # reverse order for speed # print",
"return True spec_sum_sets_sum = 0 for i in range(len(sets)): if test_2(sets[i]) and test_1(sets[i]):",
"sets = [] while fr: fs = (fr.strip()).split() for i in range(len(fs)): fs[i]",
"l - 1 while right >= left: sum_1 = sum(s[:left]) sum_2 = sum(s[right:])",
"= (fr.strip()).split() for i in range(len(fs)): fs[i] = int(fs[i]) fs.sort() sets.append(fs) fr =",
"disjoint subsets B and C def test_1(s): for size in range(1,(len(s) / 2)",
"i in range(len(fs)): fs[i] = int(fs[i]) fs.sort() sets.append(fs) fr = f.readline() def test_rest(set,",
"/ 2) + 1): for c in combinations(s, size): if not test_rest(s,c): return",
"return False left += 1 right -= 1 return True spec_sum_sets_sum = 0",
"test_rest(set, com): ret_set = list(set) for num in com: del(ret_set[ret_set.index(num)]) for m in",
"for m in range(1,len(ret_set)+1): for s in list(combinations(ret_set, m)): if sum(s) == sum(com):",
"B and C def test_1(s): for size in range(1,(len(s) / 2) + 1):",
"test_rest(s,c): return False return True # If B contains more elements than C",
"than C then S(B) > S(C). def test_2(s): l = len(s) left =",
"if sum(s) == sum(com): return False return True # sum(B) != sum(C) for",
"m)): if sum(s) == sum(com): return False return True # sum(B) != sum(C)",
"if test_2(sets[i]) and test_1(sets[i]): # reverse order for speed # print i, '\\t',",
"= [] while fr: fs = (fr.strip()).split() for i in range(len(fs)): fs[i] =",
"right = l - 1 while right >= left: sum_1 = sum(s[:left]) sum_2",
"fr = f.readline() sets = [] while fr: fs = (fr.strip()).split() for i",
"range(len(sets)): if test_2(sets[i]) and test_1(sets[i]): # reverse order for speed # print i,",
"fr = f.readline() def test_rest(set, com): ret_set = list(set) for num in com:",
"del(ret_set[ret_set.index(num)]) for m in range(1,len(ret_set)+1): for s in list(combinations(ret_set, m)): if sum(s) ==",
"for s in list(combinations(ret_set, m)): if sum(s) == sum(com): return False return True",
"in combinations(s, size): if not test_rest(s,c): return False return True # If B",
"int(fs[i]) fs.sort() sets.append(fs) fr = f.readline() def test_rest(set, com): ret_set = list(set) for",
"not sum_1 > sum_2: return False left += 1 right -= 1 return",
"= f.readline() sets = [] while fr: fs = (fr.strip()).split() for i in",
"in com: del(ret_set[ret_set.index(num)]) for m in range(1,len(ret_set)+1): for s in list(combinations(ret_set, m)): if",
"spec_sum_sets_sum = 0 for i in range(len(sets)): if test_2(sets[i]) and test_1(sets[i]): # reverse",
"= 0 for i in range(len(sets)): if test_2(sets[i]) and test_1(sets[i]): # reverse order",
"def test_1(s): for size in range(1,(len(s) / 2) + 1): for c in",
"# If B contains more elements than C then S(B) > S(C). def",
"range(1,len(ret_set)+1): for s in list(combinations(ret_set, m)): if sum(s) == sum(com): return False return",
"(fr.strip()).split() for i in range(len(fs)): fs[i] = int(fs[i]) fs.sort() sets.append(fs) fr = f.readline()",
"size in range(1,(len(s) / 2) + 1): for c in combinations(s, size): if",
"range(1,(len(s) / 2) + 1): for c in combinations(s, size): if not test_rest(s,c):",
"com): ret_set = list(set) for num in com: del(ret_set[ret_set.index(num)]) for m in range(1,len(ret_set)+1):",
"while fr: fs = (fr.strip()).split() for i in range(len(fs)): fs[i] = int(fs[i]) fs.sort()",
"in range(1,len(ret_set)+1): for s in list(combinations(ret_set, m)): if sum(s) == sum(com): return False",
"== sum(com): return False return True # sum(B) != sum(C) for non-empty, disjoint",
"l = len(s) left = 2 right = l - 1 while right",
"s in list(combinations(ret_set, m)): if sum(s) == sum(com): return False return True #",
"for speed # print i, '\\t', sets[i] spec_sum_sets_sum += sum(sets[i]) # for set",
"list(combinations(ret_set, m)): if sum(s) == sum(com): return False return True # sum(B) !=",
"True # sum(B) != sum(C) for non-empty, disjoint subsets B and C def",
"combinations(s, size): if not test_rest(s,c): return False return True # If B contains",
"more elements than C then S(B) > S(C). def test_2(s): l = len(s)",
"test_2(s): l = len(s) left = 2 right = l - 1 while",
"then S(B) > S(C). def test_2(s): l = len(s) left = 2 right",
"S(B) > S(C). def test_2(s): l = len(s) left = 2 right =",
"sum_2 = sum(s[right:]) if not sum_1 > sum_2: return False left += 1",
"return True # sum(B) != sum(C) for non-empty, disjoint subsets B and C",
"def test_rest(set, com): ret_set = list(set) for num in com: del(ret_set[ret_set.index(num)]) for m",
"open(\"p105_text.txt\") fr = f.readline() sets = [] while fr: fs = (fr.strip()).split() for",
"2 right = l - 1 while right >= left: sum_1 = sum(s[:left])",
"C then S(B) > S(C). def test_2(s): l = len(s) left = 2",
"return False return True # If B contains more elements than C then",
"itertools import combinations f = open(\"p105_text.txt\") fr = f.readline() sets = [] while",
"left = 2 right = l - 1 while right >= left: sum_1",
"left: sum_1 = sum(s[:left]) sum_2 = sum(s[right:]) if not sum_1 > sum_2: return",
"sets[i] spec_sum_sets_sum += sum(sets[i]) # for set in sets: # if test_2(set) and",
"S(C). def test_2(s): l = len(s) left = 2 right = l -",
"while right >= left: sum_1 = sum(s[:left]) sum_2 = sum(s[right:]) if not sum_1",
">= left: sum_1 = sum(s[:left]) sum_2 = sum(s[right:]) if not sum_1 > sum_2:",
"contains more elements than C then S(B) > S(C). def test_2(s): l =",
"sum(s) == sum(com): return False return True # sum(B) != sum(C) for non-empty,",
"i, '\\t', sets[i] spec_sum_sets_sum += sum(sets[i]) # for set in sets: # if"
] |
[
". import a_weighting from . import audio_format from . import speech_voltmeter_svp56 from .",
"a_weighting from . import audio_format from . import speech_voltmeter_svp56 from . import voice_activity_detection",
"from . import a_weighting from . import audio_format from . import speech_voltmeter_svp56 from",
"import a_weighting from . import audio_format from . import speech_voltmeter_svp56 from . import",
"<reponame>neural-reckoning/HumanlikeHearing from . import a_weighting from . import audio_format from . import speech_voltmeter_svp56"
] |
[
"= int(self.disp_mag) mag_max = int(200) cv2.createTrackbar(\"Exp[ms]\", \"img\", exp_cur, exp_max, self._changeExposure) cv2.createTrackbar(\"Gain[dB]\", \"img\", gain_cur,",
"number of connected cameras, camera name, etc. self.devices = self.factory.EnumerateDevices() if len(self.devices) ==",
"= {0}'.format(self.camera.ExposureAuto.GetValue())) print('ExposureTime = {0}[us]'.format(self.camera.ExposureTime.GetValue())) print('GainAuto = {0}'.format(self.camera.GainAuto.GetValue())) print('Gain = {0}'.format(self.camera.Gain.GetValue())) self.camera.Close() #",
"val): exp = cv2.getTrackbarPos(\"Exp[ms]\", \"img\") self.setExposureTime(exp * 1000, False) def _changeGain(self, val): gain",
"self.camera.ExposureTime.SetValue(exposure_us) if gain == -1.0: self.camera.GainAuto.SetValue('Continuous') else: self.camera.GainAuto.SetValue('Off') self.camera.Gain.SetValue(gain) print('--------------------') print('CameraPylon.__init__') print('--------------------') print('Name",
"en_print=True): \"\"\" Set gain. * When gain is -1, auto gain is enabled.",
"CameraPylon: def __init__(self, id=0, exposure_us=30000, gain=0.0): \"\"\" Init * When exposure_us is zero,",
"settings cannot be changed without opening. self.camera.Open() if exposure_us == 0: self.camera.ExposureAuto.SetValue('Continuous') else:",
"be changed without opening. self.camera.Open() if exposure_us == 0: self.camera.ExposureAuto.SetValue('Continuous') else: self.camera.ExposureAuto.SetValue('Off') self.camera.ExposureTime.SetValue(exposure_us)",
"= 0 while k != 27: img = self.grab(en_print=False) w = int(self.camera.Width.GetValue() *",
"24-bit BGR. * When en_print is True, display the set value. \"\"\" if",
"open.') t_start = time.time() self.camera.StartGrabbing(pylon.GrabStrategy_LatestImageOnly) grabResult = self.camera.RetrieveResult(timeout, pylon.TimeoutHandling_ThrowException) rslt_conv = self.converter_bgr.Convert(grabResult) grabResult.Release()",
"proc_time = time.time() - t_start if en_print: print('grab time : {0} ms'.format(proc_time)) return",
"connected cameras, camera name, etc. self.devices = self.factory.EnumerateDevices() if len(self.devices) == 0: raise",
"gain. * When gain is -1, auto gain is enabled. * When en_print",
"self.camera = pylon.InstantCamera(self.factory.CreateDevice(self.devices[id])) # The camera settings cannot be changed without opening. self.camera.Open()",
"print('GainAuto = {0}'.format(self.camera.GainAuto.GetValue())) print('Gain = {0}[dB]'.format(self.camera.Gain.GetValue())) def grab(self, timeout=1000, en_print=True): \"\"\" Grab. *",
"pylon.TimeoutHandling_ThrowException) rslt_conv = self.converter_bgr.Convert(grabResult) grabResult.Release() self.camera.StopGrabbing() proc_time = time.time() - t_start if en_print:",
"exposure_us == 0: self.camera.ExposureAuto.SetValue('Continuous') else: self.camera.ExposureAuto.SetValue('Off') self.camera.ExposureTime.SetValue(exposure_us) if gain == -1.0: self.camera.GainAuto.SetValue('Continuous') else:",
"\"\"\" Set gain. * When gain is -1, auto gain is enabled. *",
"cv2.createTrackbar(\"Mag[%]\", \"img\", mag_cur, mag_max, self._changeMag) k = cv2.waitKey(delay) cv2.destroyAllWindows() def _changeExposure(self, val): exp",
"t_start = time.time() self.camera.StartGrabbing(pylon.GrabStrategy_LatestImageOnly) grabResult = self.camera.RetrieveResult(timeout, pylon.TimeoutHandling_ThrowException) rslt_conv = self.converter_bgr.Convert(grabResult) grabResult.Release() self.camera.StopGrabbing()",
"\"img\", gain_cur, gain_max, self._changeGain) cv2.createTrackbar(\"Mag[%]\", \"img\", mag_cur, mag_max, self._changeMag) k = cv2.waitKey(delay) cv2.destroyAllWindows()",
"rslt_conv = self.converter_bgr.Convert(grabResult) grabResult.Release() self.camera.StopGrabbing() proc_time = time.time() - t_start if en_print: print('grab",
"== 0: self.camera.ExposureAuto.SetValue('Continuous') else: self.camera.ExposureAuto.SetValue('Off') self.camera.ExposureTime.SetValue(exposure_us) if gain == -1.0: self.camera.GainAuto.SetValue('Continuous') else: self.camera.GainAuto.SetValue('Off')",
"/ 1000) gain_cur = int(self.camera.Gain.GetValue()) gain_max = int(self.camera.AutoGainUpperLimit.GetValue()) mag_cur = int(self.disp_mag) mag_max =",
"is zero, auto gain is enabled. \"\"\" self.factory = pylon.TlFactory.GetInstance() # DeviceInfo class",
"-*- coding: utf-8 -*- import time from pypylon import pylon import cv2 class",
"class CameraPylon: def __init__(self, id=0, exposure_us=30000, gain=0.0): \"\"\" Init * When exposure_us is",
"exp_max = int(self.camera.AutoExposureTimeUpperLimit.GetValue() / 1000) gain_cur = int(self.camera.Gain.GetValue()) gain_max = int(self.camera.AutoGainUpperLimit.GetValue()) mag_cur =",
"convert to 24-bit BGR. * When en_print is True, display the set value.",
"print('--------------------') print('Name = {0}'.format(self.devices[id].GetFriendlyName())) print('Width = {0}'.format(self.camera.Width.GetValue())) print('Height = {0}'.format(self.camera.Height.GetValue())) print('ExposureAuto = {0}'.format(self.camera.ExposureAuto.GetValue()))",
"close(self): \"\"\" Close. \"\"\" self.camera.Close() def setExposureTime(self, exposure_us=10000, en_print=True): \"\"\" Set exposure time.",
"value. \"\"\" if not self.camera.IsOpen(): raise Exception('camera is not open.') t_start = time.time()",
"self.camera.GainAuto.SetValue('Continuous') else: self.camera.GainAuto.SetValue('Off') self.camera.Gain.SetValue(gain) print('--------------------') print('CameraPylon.__init__') print('--------------------') print('Name = {0}'.format(self.devices[id].GetFriendlyName())) print('Width = {0}'.format(self.camera.Width.GetValue()))",
"pylon.ImageFormatConverter() self.converter_bgr.OutputPixelFormat = pylon.PixelType_BGR8packed self.converter_bgr.OutputBitAlignment = 'MsbAligned' # Set display magnification. self.disp_mag =",
"StartGrabbing and StopGrabbing each time. * All convert to 24-bit BGR. * When",
"ESC. \"\"\" if not self.camera.IsOpen(): raise Exception('camera is not open.') k = 0",
"27: img = self.grab(en_print=False) w = int(self.camera.Width.GetValue() * self.disp_mag / 100) h =",
"\"\"\" Init * When exposure_us is zero, auto exposure is enabled. * When",
"self.setExposureTime(exp * 1000, False) def _changeGain(self, val): gain = cv2.getTrackbarPos(\"Gain[dB]\", \"img\") self.setGain(gain, False)",
"* When exposure_us is zero, auto exposure is enabled. * When gain is",
"self.camera.Close() # Set ImageFormatConverter. self.converter_bgr = pylon.ImageFormatConverter() self.converter_bgr.OutputPixelFormat = pylon.PixelType_BGR8packed self.converter_bgr.OutputBitAlignment = 'MsbAligned'",
"self._changeExposure) cv2.createTrackbar(\"Gain[dB]\", \"img\", gain_cur, gain_max, self._changeGain) cv2.createTrackbar(\"Mag[%]\", \"img\", mag_cur, mag_max, self._changeMag) k =",
"is zero, auto exposure is enabled. * When en_print is True, display the",
"open.') k = 0 while k != 27: img = self.grab(en_print=False) w =",
"= pylon.ImageFormatConverter() self.converter_bgr.OutputPixelFormat = pylon.PixelType_BGR8packed self.converter_bgr.OutputBitAlignment = 'MsbAligned' # Set display magnification. self.disp_mag",
"* When exposure_us is zero, auto exposure is enabled. * When en_print is",
"= self.factory.EnumerateDevices() if len(self.devices) == 0: raise Exception('no camera present.') # Create a",
"self.disp_mag / 100) img_resize = cv2.resize(img, (w, h)) cv2.imshow(\"img\", img_resize) exp_cur = int(self.camera.ExposureTime.GetValue()",
"def setGain(self, gain=0.0, en_print=True): \"\"\" Set gain. * When gain is -1, auto",
"= cv2.waitKey(delay) cv2.destroyAllWindows() def _changeExposure(self, val): exp = cv2.getTrackbarPos(\"Exp[ms]\", \"img\") self.setExposureTime(exp * 1000,",
"StopGrabbing each time. * All convert to 24-bit BGR. * When en_print is",
"the set value. \"\"\" if not self.camera.IsOpen(): raise Exception('camera is not open.') if",
"opening. self.camera.Open() if exposure_us == 0: self.camera.ExposureAuto.SetValue('Continuous') else: self.camera.ExposureAuto.SetValue('Off') self.camera.ExposureTime.SetValue(exposure_us) if gain ==",
"zero, auto exposure is enabled. * When gain is zero, auto gain is",
"else: self.camera.ExposureAuto.SetValue('Off') self.camera.ExposureTime.SetValue(exposure_us) if en_print: print('ExposureAuto = {0}'.format(self.camera.ExposureAuto.GetValue())) print('ExposureTime = {0}[us]'.format(self.camera.ExposureTime.GetValue())) def setGain(self,",
"exp_max, self._changeExposure) cv2.createTrackbar(\"Gain[dB]\", \"img\", gain_cur, gain_max, self._changeGain) cv2.createTrackbar(\"Mag[%]\", \"img\", mag_cur, mag_max, self._changeMag) k",
"DeviceInfo class get the number of connected cameras, camera name, etc. self.devices =",
"not open.') t_start = time.time() self.camera.StartGrabbing(pylon.GrabStrategy_LatestImageOnly) grabResult = self.camera.RetrieveResult(timeout, pylon.TimeoutHandling_ThrowException) rslt_conv = self.converter_bgr.Convert(grabResult)",
"if exposure_us == 0: self.camera.ExposureAuto.SetValue('Continuous') else: self.camera.ExposureAuto.SetValue('Off') self.camera.ExposureTime.SetValue(exposure_us) if gain == -1.0: self.camera.GainAuto.SetValue('Continuous')",
"view(self, delay=1): \"\"\" View. * Close with ESC. \"\"\" if not self.camera.IsOpen(): raise",
"1000) gain_cur = int(self.camera.Gain.GetValue()) gain_max = int(self.camera.AutoGainUpperLimit.GetValue()) mag_cur = int(self.disp_mag) mag_max = int(200)",
"coding: utf-8 -*- import time from pypylon import pylon import cv2 class CameraPylon:",
"= int(self.camera.Height.GetValue() * self.disp_mag / 100) img_resize = cv2.resize(img, (w, h)) cv2.imshow(\"img\", img_resize)",
"self.camera.ExposureTime.SetValue(exposure_us) if en_print: print('ExposureAuto = {0}'.format(self.camera.ExposureAuto.GetValue())) print('ExposureTime = {0}[us]'.format(self.camera.ExposureTime.GetValue())) def setGain(self, gain=0.0, en_print=True):",
"en_print: print('grab time : {0} ms'.format(proc_time)) return rslt_conv.GetArray() def view(self, delay=1): \"\"\" View.",
"self.camera.ExposureAuto.SetValue('Continuous') else: self.camera.ExposureAuto.SetValue('Off') self.camera.ExposureTime.SetValue(exposure_us) if en_print: print('ExposureAuto = {0}'.format(self.camera.ExposureAuto.GetValue())) print('ExposureTime = {0}[us]'.format(self.camera.ExposureTime.GetValue())) def",
"= time.time() - t_start if en_print: print('grab time : {0} ms'.format(proc_time)) return rslt_conv.GetArray()",
"class get the number of connected cameras, camera name, etc. self.devices = self.factory.EnumerateDevices()",
"present.') # Create a class to control the camera. self.camera = pylon.InstantCamera(self.factory.CreateDevice(self.devices[id])) #",
"BGR. * When en_print is True, display the set value. \"\"\" if not",
"self._changeGain) cv2.createTrackbar(\"Mag[%]\", \"img\", mag_cur, mag_max, self._changeMag) k = cv2.waitKey(delay) cv2.destroyAllWindows() def _changeExposure(self, val):",
"= {0}'.format(self.camera.GainAuto.GetValue())) print('Gain = {0}[dB]'.format(self.camera.Gain.GetValue())) def grab(self, timeout=1000, en_print=True): \"\"\" Grab. * Run",
"print('Gain = {0}[dB]'.format(self.camera.Gain.GetValue())) def grab(self, timeout=1000, en_print=True): \"\"\" Grab. * Run StartGrabbing and",
"When exposure_us is zero, auto exposure is enabled. * When en_print is True,",
"= 50 def open(self): \"\"\" Open. \"\"\" self.camera.Open() def close(self): \"\"\" Close. \"\"\"",
"gain_max, self._changeGain) cv2.createTrackbar(\"Mag[%]\", \"img\", mag_cur, mag_max, self._changeMag) k = cv2.waitKey(delay) cv2.destroyAllWindows() def _changeExposure(self,",
"mag_max, self._changeMag) k = cv2.waitKey(delay) cv2.destroyAllWindows() def _changeExposure(self, val): exp = cv2.getTrackbarPos(\"Exp[ms]\", \"img\")",
"\"img\") self.setGain(gain, False) def _changeMag(self, val): mag = cv2.getTrackbarPos(\"Mag[%]\", \"img\") self.disp_mag = int(mag)",
"pylon.PixelType_BGR8packed self.converter_bgr.OutputBitAlignment = 'MsbAligned' # Set display magnification. self.disp_mag = 50 def open(self):",
"Init * When exposure_us is zero, auto exposure is enabled. * When gain",
"== 0: raise Exception('no camera present.') # Create a class to control the",
"self.converter_bgr = pylon.ImageFormatConverter() self.converter_bgr.OutputPixelFormat = pylon.PixelType_BGR8packed self.converter_bgr.OutputBitAlignment = 'MsbAligned' # Set display magnification.",
"gain is enabled. \"\"\" self.factory = pylon.TlFactory.GetInstance() # DeviceInfo class get the number",
"\"\"\" self.camera.Open() def close(self): \"\"\" Close. \"\"\" self.camera.Close() def setExposureTime(self, exposure_us=10000, en_print=True): \"\"\"",
"\"\"\" Set exposure time. * When exposure_us is zero, auto exposure is enabled.",
"/ 100) h = int(self.camera.Height.GetValue() * self.disp_mag / 100) img_resize = cv2.resize(img, (w,",
"name, etc. self.devices = self.factory.EnumerateDevices() if len(self.devices) == 0: raise Exception('no camera present.')",
"exposure_us is zero, auto exposure is enabled. * When en_print is True, display",
"Exception('no camera present.') # Create a class to control the camera. self.camera =",
"print('Gain = {0}'.format(self.camera.Gain.GetValue())) self.camera.Close() # Set ImageFormatConverter. self.converter_bgr = pylon.ImageFormatConverter() self.converter_bgr.OutputPixelFormat = pylon.PixelType_BGR8packed",
"ImageFormatConverter. self.converter_bgr = pylon.ImageFormatConverter() self.converter_bgr.OutputPixelFormat = pylon.PixelType_BGR8packed self.converter_bgr.OutputBitAlignment = 'MsbAligned' # Set display",
"* When en_print is True, display the set value. \"\"\" if not self.camera.IsOpen():",
"100) h = int(self.camera.Height.GetValue() * self.disp_mag / 100) img_resize = cv2.resize(img, (w, h))",
"0: self.camera.ExposureAuto.SetValue('Continuous') else: self.camera.ExposureAuto.SetValue('Off') self.camera.ExposureTime.SetValue(exposure_us) if en_print: print('ExposureAuto = {0}'.format(self.camera.ExposureAuto.GetValue())) print('ExposureTime = {0}[us]'.format(self.camera.ExposureTime.GetValue()))",
"= self.camera.RetrieveResult(timeout, pylon.TimeoutHandling_ThrowException) rslt_conv = self.converter_bgr.Convert(grabResult) grabResult.Release() self.camera.StopGrabbing() proc_time = time.time() - t_start",
"if exposure_us == 0: self.camera.ExposureAuto.SetValue('Continuous') else: self.camera.ExposureAuto.SetValue('Off') self.camera.ExposureTime.SetValue(exposure_us) if en_print: print('ExposureAuto = {0}'.format(self.camera.ExposureAuto.GetValue()))",
"self.camera.IsOpen(): raise Exception('camera is not open.') k = 0 while k != 27:",
"not open.') if exposure_us == 0: self.camera.ExposureAuto.SetValue('Continuous') else: self.camera.ExposureAuto.SetValue('Off') self.camera.ExposureTime.SetValue(exposure_us) if en_print: print('ExposureAuto",
"self.camera.GainAuto.SetValue('Off') self.camera.Gain.SetValue(gain) print('--------------------') print('CameraPylon.__init__') print('--------------------') print('Name = {0}'.format(self.devices[id].GetFriendlyName())) print('Width = {0}'.format(self.camera.Width.GetValue())) print('Height =",
"camera settings cannot be changed without opening. self.camera.Open() if exposure_us == 0: self.camera.ExposureAuto.SetValue('Continuous')",
"{0} ms'.format(proc_time)) return rslt_conv.GetArray() def view(self, delay=1): \"\"\" View. * Close with ESC.",
"gain == -1.0: self.camera.GainAuto.SetValue('Continuous') else: self.camera.GainAuto.SetValue('Off') self.camera.Gain.SetValue(gain) if en_print: print('GainAuto = {0}'.format(self.camera.GainAuto.GetValue())) print('Gain",
"= int(self.camera.AutoGainUpperLimit.GetValue()) mag_cur = int(self.disp_mag) mag_max = int(200) cv2.createTrackbar(\"Exp[ms]\", \"img\", exp_cur, exp_max, self._changeExposure)",
"def open(self): \"\"\" Open. \"\"\" self.camera.Open() def close(self): \"\"\" Close. \"\"\" self.camera.Close() def",
"/ 100) img_resize = cv2.resize(img, (w, h)) cv2.imshow(\"img\", img_resize) exp_cur = int(self.camera.ExposureTime.GetValue() /",
"k != 27: img = self.grab(en_print=False) w = int(self.camera.Width.GetValue() * self.disp_mag / 100)",
"Open. \"\"\" self.camera.Open() def close(self): \"\"\" Close. \"\"\" self.camera.Close() def setExposureTime(self, exposure_us=10000, en_print=True):",
"en_print=True): \"\"\" Set exposure time. * When exposure_us is zero, auto exposure is",
"gain is -1, auto gain is enabled. * When en_print is True, display",
"value. \"\"\" if not self.camera.IsOpen(): raise Exception('camera is not open.') if gain ==",
"mag_cur, mag_max, self._changeMag) k = cv2.waitKey(delay) cv2.destroyAllWindows() def _changeExposure(self, val): exp = cv2.getTrackbarPos(\"Exp[ms]\",",
"k = 0 while k != 27: img = self.grab(en_print=False) w = int(self.camera.Width.GetValue()",
"etc. self.devices = self.factory.EnumerateDevices() if len(self.devices) == 0: raise Exception('no camera present.') #",
"pypylon import pylon import cv2 class CameraPylon: def __init__(self, id=0, exposure_us=30000, gain=0.0): \"\"\"",
"self.camera.ExposureAuto.SetValue('Off') self.camera.ExposureTime.SetValue(exposure_us) if gain == -1.0: self.camera.GainAuto.SetValue('Continuous') else: self.camera.GainAuto.SetValue('Off') self.camera.Gain.SetValue(gain) print('--------------------') print('CameraPylon.__init__') print('--------------------')",
"is enabled. \"\"\" self.factory = pylon.TlFactory.GetInstance() # DeviceInfo class get the number of",
"import time from pypylon import pylon import cv2 class CameraPylon: def __init__(self, id=0,",
"gain_cur = int(self.camera.Gain.GetValue()) gain_max = int(self.camera.AutoGainUpperLimit.GetValue()) mag_cur = int(self.disp_mag) mag_max = int(200) cv2.createTrackbar(\"Exp[ms]\",",
"View. * Close with ESC. \"\"\" if not self.camera.IsOpen(): raise Exception('camera is not",
"# Create a class to control the camera. self.camera = pylon.InstantCamera(self.factory.CreateDevice(self.devices[id])) # The",
"exposure is enabled. * When en_print is True, display the set value. \"\"\"",
"value. \"\"\" if not self.camera.IsOpen(): raise Exception('camera is not open.') if exposure_us ==",
"cv2.createTrackbar(\"Exp[ms]\", \"img\", exp_cur, exp_max, self._changeExposure) cv2.createTrackbar(\"Gain[dB]\", \"img\", gain_cur, gain_max, self._changeGain) cv2.createTrackbar(\"Mag[%]\", \"img\", mag_cur,",
"is enabled. * When en_print is True, display the set value. \"\"\" if",
"{0}[us]'.format(self.camera.ExposureTime.GetValue())) print('GainAuto = {0}'.format(self.camera.GainAuto.GetValue())) print('Gain = {0}'.format(self.camera.Gain.GetValue())) self.camera.Close() # Set ImageFormatConverter. self.converter_bgr =",
"self.factory.EnumerateDevices() if len(self.devices) == 0: raise Exception('no camera present.') # Create a class",
"self.camera.IsOpen(): raise Exception('camera is not open.') if exposure_us == 0: self.camera.ExposureAuto.SetValue('Continuous') else: self.camera.ExposureAuto.SetValue('Off')",
"= {0}[us]'.format(self.camera.ExposureTime.GetValue())) def setGain(self, gain=0.0, en_print=True): \"\"\" Set gain. * When gain is",
"print('Height = {0}'.format(self.camera.Height.GetValue())) print('ExposureAuto = {0}'.format(self.camera.ExposureAuto.GetValue())) print('ExposureTime = {0}[us]'.format(self.camera.ExposureTime.GetValue())) print('GainAuto = {0}'.format(self.camera.GainAuto.GetValue())) print('Gain",
"-1.0: self.camera.GainAuto.SetValue('Continuous') else: self.camera.GainAuto.SetValue('Off') self.camera.Gain.SetValue(gain) if en_print: print('GainAuto = {0}'.format(self.camera.GainAuto.GetValue())) print('Gain = {0}[dB]'.format(self.camera.Gain.GetValue()))",
"self.grab(en_print=False) w = int(self.camera.Width.GetValue() * self.disp_mag / 100) h = int(self.camera.Height.GetValue() * self.disp_mag",
"img = self.grab(en_print=False) w = int(self.camera.Width.GetValue() * self.disp_mag / 100) h = int(self.camera.Height.GetValue()",
"is zero, auto exposure is enabled. * When gain is zero, auto gain",
": {0} ms'.format(proc_time)) return rslt_conv.GetArray() def view(self, delay=1): \"\"\" View. * Close with",
"def setExposureTime(self, exposure_us=10000, en_print=True): \"\"\" Set exposure time. * When exposure_us is zero,",
"# -*- coding: utf-8 -*- import time from pypylon import pylon import cv2",
"pylon.TlFactory.GetInstance() # DeviceInfo class get the number of connected cameras, camera name, etc.",
"{0}'.format(self.camera.Width.GetValue())) print('Height = {0}'.format(self.camera.Height.GetValue())) print('ExposureAuto = {0}'.format(self.camera.ExposureAuto.GetValue())) print('ExposureTime = {0}[us]'.format(self.camera.ExposureTime.GetValue())) print('GainAuto = {0}'.format(self.camera.GainAuto.GetValue()))",
"100) img_resize = cv2.resize(img, (w, h)) cv2.imshow(\"img\", img_resize) exp_cur = int(self.camera.ExposureTime.GetValue() / 1000)",
"auto gain is enabled. * When en_print is True, display the set value.",
"if en_print: print('GainAuto = {0}'.format(self.camera.GainAuto.GetValue())) print('Gain = {0}[dB]'.format(self.camera.Gain.GetValue())) def grab(self, timeout=1000, en_print=True): \"\"\"",
"k = cv2.waitKey(delay) cv2.destroyAllWindows() def _changeExposure(self, val): exp = cv2.getTrackbarPos(\"Exp[ms]\", \"img\") self.setExposureTime(exp *",
"{0}'.format(self.camera.GainAuto.GetValue())) print('Gain = {0}[dB]'.format(self.camera.Gain.GetValue())) def grab(self, timeout=1000, en_print=True): \"\"\" Grab. * Run StartGrabbing",
"grabResult.Release() self.camera.StopGrabbing() proc_time = time.time() - t_start if en_print: print('grab time : {0}",
"When en_print is True, display the set value. \"\"\" if not self.camera.IsOpen(): raise",
"setGain(self, gain=0.0, en_print=True): \"\"\" Set gain. * When gain is -1, auto gain",
"* self.disp_mag / 100) h = int(self.camera.Height.GetValue() * self.disp_mag / 100) img_resize =",
"else: self.camera.GainAuto.SetValue('Off') self.camera.Gain.SetValue(gain) print('--------------------') print('CameraPylon.__init__') print('--------------------') print('Name = {0}'.format(self.devices[id].GetFriendlyName())) print('Width = {0}'.format(self.camera.Width.GetValue())) print('Height",
"* When gain is zero, auto gain is enabled. \"\"\" self.factory = pylon.TlFactory.GetInstance()",
"and StopGrabbing each time. * All convert to 24-bit BGR. * When en_print",
"1000) exp_max = int(self.camera.AutoExposureTimeUpperLimit.GetValue() / 1000) gain_cur = int(self.camera.Gain.GetValue()) gain_max = int(self.camera.AutoGainUpperLimit.GetValue()) mag_cur",
"<filename>wk_camera_pylon.py<gh_stars>1-10 # -*- coding: utf-8 -*- import time from pypylon import pylon import",
"open.') if exposure_us == 0: self.camera.ExposureAuto.SetValue('Continuous') else: self.camera.ExposureAuto.SetValue('Off') self.camera.ExposureTime.SetValue(exposure_us) if en_print: print('ExposureAuto =",
"= {0}'.format(self.camera.Gain.GetValue())) self.camera.Close() # Set ImageFormatConverter. self.converter_bgr = pylon.ImageFormatConverter() self.converter_bgr.OutputPixelFormat = pylon.PixelType_BGR8packed self.converter_bgr.OutputBitAlignment",
"en_print is True, display the set value. \"\"\" if not self.camera.IsOpen(): raise Exception('camera",
"gain_max = int(self.camera.AutoGainUpperLimit.GetValue()) mag_cur = int(self.disp_mag) mag_max = int(200) cv2.createTrackbar(\"Exp[ms]\", \"img\", exp_cur, exp_max,",
"print('CameraPylon.__init__') print('--------------------') print('Name = {0}'.format(self.devices[id].GetFriendlyName())) print('Width = {0}'.format(self.camera.Width.GetValue())) print('Height = {0}'.format(self.camera.Height.GetValue())) print('ExposureAuto =",
"'MsbAligned' # Set display magnification. self.disp_mag = 50 def open(self): \"\"\" Open. \"\"\"",
"if en_print: print('ExposureAuto = {0}'.format(self.camera.ExposureAuto.GetValue())) print('ExposureTime = {0}[us]'.format(self.camera.ExposureTime.GetValue())) def setGain(self, gain=0.0, en_print=True): \"\"\"",
"* self.disp_mag / 100) img_resize = cv2.resize(img, (w, h)) cv2.imshow(\"img\", img_resize) exp_cur =",
"h)) cv2.imshow(\"img\", img_resize) exp_cur = int(self.camera.ExposureTime.GetValue() / 1000) exp_max = int(self.camera.AutoExposureTimeUpperLimit.GetValue() / 1000)",
"raise Exception('no camera present.') # Create a class to control the camera. self.camera",
"When exposure_us is zero, auto exposure is enabled. * When gain is zero,",
"Set exposure time. * When exposure_us is zero, auto exposure is enabled. *",
"def _changeExposure(self, val): exp = cv2.getTrackbarPos(\"Exp[ms]\", \"img\") self.setExposureTime(exp * 1000, False) def _changeGain(self,",
"mag_cur = int(self.disp_mag) mag_max = int(200) cv2.createTrackbar(\"Exp[ms]\", \"img\", exp_cur, exp_max, self._changeExposure) cv2.createTrackbar(\"Gain[dB]\", \"img\",",
"= {0}'.format(self.devices[id].GetFriendlyName())) print('Width = {0}'.format(self.camera.Width.GetValue())) print('Height = {0}'.format(self.camera.Height.GetValue())) print('ExposureAuto = {0}'.format(self.camera.ExposureAuto.GetValue())) print('ExposureTime =",
"set value. \"\"\" if not self.camera.IsOpen(): raise Exception('camera is not open.') t_start =",
"enabled. * When en_print is True, display the set value. \"\"\" if not",
"not open.') if gain == -1.0: self.camera.GainAuto.SetValue('Continuous') else: self.camera.GainAuto.SetValue('Off') self.camera.Gain.SetValue(gain) if en_print: print('GainAuto",
"\"\"\" View. * Close with ESC. \"\"\" if not self.camera.IsOpen(): raise Exception('camera is",
"zero, auto gain is enabled. \"\"\" self.factory = pylon.TlFactory.GetInstance() # DeviceInfo class get",
"Exception('camera is not open.') k = 0 while k != 27: img =",
"cameras, camera name, etc. self.devices = self.factory.EnumerateDevices() if len(self.devices) == 0: raise Exception('no",
"* Run StartGrabbing and StopGrabbing each time. * All convert to 24-bit BGR.",
"is enabled. * When gain is zero, auto gain is enabled. \"\"\" self.factory",
"gain is zero, auto gain is enabled. \"\"\" self.factory = pylon.TlFactory.GetInstance() # DeviceInfo",
"int(self.camera.Width.GetValue() * self.disp_mag / 100) h = int(self.camera.Height.GetValue() * self.disp_mag / 100) img_resize",
"= cv2.resize(img, (w, h)) cv2.imshow(\"img\", img_resize) exp_cur = int(self.camera.ExposureTime.GetValue() / 1000) exp_max =",
"(w, h)) cv2.imshow(\"img\", img_resize) exp_cur = int(self.camera.ExposureTime.GetValue() / 1000) exp_max = int(self.camera.AutoExposureTimeUpperLimit.GetValue() /",
"control the camera. self.camera = pylon.InstantCamera(self.factory.CreateDevice(self.devices[id])) # The camera settings cannot be changed",
"auto exposure is enabled. * When en_print is True, display the set value.",
"else: self.camera.ExposureAuto.SetValue('Off') self.camera.ExposureTime.SetValue(exposure_us) if gain == -1.0: self.camera.GainAuto.SetValue('Continuous') else: self.camera.GainAuto.SetValue('Off') self.camera.Gain.SetValue(gain) print('--------------------') print('CameraPylon.__init__')",
"= pylon.TlFactory.GetInstance() # DeviceInfo class get the number of connected cameras, camera name,",
"print('ExposureAuto = {0}'.format(self.camera.ExposureAuto.GetValue())) print('ExposureTime = {0}[us]'.format(self.camera.ExposureTime.GetValue())) print('GainAuto = {0}'.format(self.camera.GainAuto.GetValue())) print('Gain = {0}'.format(self.camera.Gain.GetValue())) self.camera.Close()",
"exposure_us is zero, auto exposure is enabled. * When gain is zero, auto",
"open(self): \"\"\" Open. \"\"\" self.camera.Open() def close(self): \"\"\" Close. \"\"\" self.camera.Close() def setExposureTime(self,",
"def __init__(self, id=0, exposure_us=30000, gain=0.0): \"\"\" Init * When exposure_us is zero, auto",
"{0}'.format(self.devices[id].GetFriendlyName())) print('Width = {0}'.format(self.camera.Width.GetValue())) print('Height = {0}'.format(self.camera.Height.GetValue())) print('ExposureAuto = {0}'.format(self.camera.ExposureAuto.GetValue())) print('ExposureTime = {0}[us]'.format(self.camera.ExposureTime.GetValue()))",
"the number of connected cameras, camera name, etc. self.devices = self.factory.EnumerateDevices() if len(self.devices)",
"\"img\", exp_cur, exp_max, self._changeExposure) cv2.createTrackbar(\"Gain[dB]\", \"img\", gain_cur, gain_max, self._changeGain) cv2.createTrackbar(\"Mag[%]\", \"img\", mag_cur, mag_max,",
"!= 27: img = self.grab(en_print=False) w = int(self.camera.Width.GetValue() * self.disp_mag / 100) h",
"{0}'.format(self.camera.GainAuto.GetValue())) print('Gain = {0}'.format(self.camera.Gain.GetValue())) self.camera.Close() # Set ImageFormatConverter. self.converter_bgr = pylon.ImageFormatConverter() self.converter_bgr.OutputPixelFormat =",
"\"\"\" Grab. * Run StartGrabbing and StopGrabbing each time. * All convert to",
"= time.time() self.camera.StartGrabbing(pylon.GrabStrategy_LatestImageOnly) grabResult = self.camera.RetrieveResult(timeout, pylon.TimeoutHandling_ThrowException) rslt_conv = self.converter_bgr.Convert(grabResult) grabResult.Release() self.camera.StopGrabbing() proc_time",
"int(self.camera.AutoExposureTimeUpperLimit.GetValue() / 1000) gain_cur = int(self.camera.Gain.GetValue()) gain_max = int(self.camera.AutoGainUpperLimit.GetValue()) mag_cur = int(self.disp_mag) mag_max",
"0: self.camera.ExposureAuto.SetValue('Continuous') else: self.camera.ExposureAuto.SetValue('Off') self.camera.ExposureTime.SetValue(exposure_us) if gain == -1.0: self.camera.GainAuto.SetValue('Continuous') else: self.camera.GainAuto.SetValue('Off') self.camera.Gain.SetValue(gain)",
"pylon.InstantCamera(self.factory.CreateDevice(self.devices[id])) # The camera settings cannot be changed without opening. self.camera.Open() if exposure_us",
"= {0}[dB]'.format(self.camera.Gain.GetValue())) def grab(self, timeout=1000, en_print=True): \"\"\" Grab. * Run StartGrabbing and StopGrabbing",
"display magnification. self.disp_mag = 50 def open(self): \"\"\" Open. \"\"\" self.camera.Open() def close(self):",
"raise Exception('camera is not open.') if exposure_us == 0: self.camera.ExposureAuto.SetValue('Continuous') else: self.camera.ExposureAuto.SetValue('Off') self.camera.ExposureTime.SetValue(exposure_us)",
"Exception('camera is not open.') if exposure_us == 0: self.camera.ExposureAuto.SetValue('Continuous') else: self.camera.ExposureAuto.SetValue('Off') self.camera.ExposureTime.SetValue(exposure_us) if",
"self.disp_mag = 50 def open(self): \"\"\" Open. \"\"\" self.camera.Open() def close(self): \"\"\" Close.",
"gain = cv2.getTrackbarPos(\"Gain[dB]\", \"img\") self.setGain(gain, False) def _changeMag(self, val): mag = cv2.getTrackbarPos(\"Mag[%]\", \"img\")",
"int(self.disp_mag) mag_max = int(200) cv2.createTrackbar(\"Exp[ms]\", \"img\", exp_cur, exp_max, self._changeExposure) cv2.createTrackbar(\"Gain[dB]\", \"img\", gain_cur, gain_max,",
"not open.') k = 0 while k != 27: img = self.grab(en_print=False) w",
"== 0: self.camera.ExposureAuto.SetValue('Continuous') else: self.camera.ExposureAuto.SetValue('Off') self.camera.ExposureTime.SetValue(exposure_us) if en_print: print('ExposureAuto = {0}'.format(self.camera.ExposureAuto.GetValue())) print('ExposureTime =",
"grab(self, timeout=1000, en_print=True): \"\"\" Grab. * Run StartGrabbing and StopGrabbing each time. *",
"while k != 27: img = self.grab(en_print=False) w = int(self.camera.Width.GetValue() * self.disp_mag /",
"cv2.getTrackbarPos(\"Exp[ms]\", \"img\") self.setExposureTime(exp * 1000, False) def _changeGain(self, val): gain = cv2.getTrackbarPos(\"Gain[dB]\", \"img\")",
"\"\"\" self.factory = pylon.TlFactory.GetInstance() # DeviceInfo class get the number of connected cameras,",
"gain == -1.0: self.camera.GainAuto.SetValue('Continuous') else: self.camera.GainAuto.SetValue('Off') self.camera.Gain.SetValue(gain) print('--------------------') print('CameraPylon.__init__') print('--------------------') print('Name = {0}'.format(self.devices[id].GetFriendlyName()))",
"cannot be changed without opening. self.camera.Open() if exposure_us == 0: self.camera.ExposureAuto.SetValue('Continuous') else: self.camera.ExposureAuto.SetValue('Off')",
"self.camera.ExposureAuto.SetValue('Off') self.camera.ExposureTime.SetValue(exposure_us) if en_print: print('ExposureAuto = {0}'.format(self.camera.ExposureAuto.GetValue())) print('ExposureTime = {0}[us]'.format(self.camera.ExposureTime.GetValue())) def setGain(self, gain=0.0,",
"= {0}[us]'.format(self.camera.ExposureTime.GetValue())) print('GainAuto = {0}'.format(self.camera.GainAuto.GetValue())) print('Gain = {0}'.format(self.camera.Gain.GetValue())) self.camera.Close() # Set ImageFormatConverter. self.converter_bgr",
"1000, False) def _changeGain(self, val): gain = cv2.getTrackbarPos(\"Gain[dB]\", \"img\") self.setGain(gain, False) def _changeMag(self,",
"-*- import time from pypylon import pylon import cv2 class CameraPylon: def __init__(self,",
"{0}'.format(self.camera.ExposureAuto.GetValue())) print('ExposureTime = {0}[us]'.format(self.camera.ExposureTime.GetValue())) print('GainAuto = {0}'.format(self.camera.GainAuto.GetValue())) print('Gain = {0}'.format(self.camera.Gain.GetValue())) self.camera.Close() # Set",
"img_resize = cv2.resize(img, (w, h)) cv2.imshow(\"img\", img_resize) exp_cur = int(self.camera.ExposureTime.GetValue() / 1000) exp_max",
"self.devices = self.factory.EnumerateDevices() if len(self.devices) == 0: raise Exception('no camera present.') # Create",
"self.camera.Close() def setExposureTime(self, exposure_us=10000, en_print=True): \"\"\" Set exposure time. * When exposure_us is",
"if gain == -1.0: self.camera.GainAuto.SetValue('Continuous') else: self.camera.GainAuto.SetValue('Off') self.camera.Gain.SetValue(gain) print('--------------------') print('CameraPylon.__init__') print('--------------------') print('Name =",
"exposure time. * When exposure_us is zero, auto exposure is enabled. * When",
"exp = cv2.getTrackbarPos(\"Exp[ms]\", \"img\") self.setExposureTime(exp * 1000, False) def _changeGain(self, val): gain =",
"\"\"\" if not self.camera.IsOpen(): raise Exception('camera is not open.') if gain == -1.0:",
"_changeGain(self, val): gain = cv2.getTrackbarPos(\"Gain[dB]\", \"img\") self.setGain(gain, False) def _changeMag(self, val): mag =",
"# Set ImageFormatConverter. self.converter_bgr = pylon.ImageFormatConverter() self.converter_bgr.OutputPixelFormat = pylon.PixelType_BGR8packed self.converter_bgr.OutputBitAlignment = 'MsbAligned' #",
"0 while k != 27: img = self.grab(en_print=False) w = int(self.camera.Width.GetValue() * self.disp_mag",
"\"\"\" Open. \"\"\" self.camera.Open() def close(self): \"\"\" Close. \"\"\" self.camera.Close() def setExposureTime(self, exposure_us=10000,",
"the camera. self.camera = pylon.InstantCamera(self.factory.CreateDevice(self.devices[id])) # The camera settings cannot be changed without",
"to control the camera. self.camera = pylon.InstantCamera(self.factory.CreateDevice(self.devices[id])) # The camera settings cannot be",
"raise Exception('camera is not open.') t_start = time.time() self.camera.StartGrabbing(pylon.GrabStrategy_LatestImageOnly) grabResult = self.camera.RetrieveResult(timeout, pylon.TimeoutHandling_ThrowException)",
"setExposureTime(self, exposure_us=10000, en_print=True): \"\"\" Set exposure time. * When exposure_us is zero, auto",
"exposure_us=30000, gain=0.0): \"\"\" Init * When exposure_us is zero, auto exposure is enabled.",
"exposure_us=10000, en_print=True): \"\"\" Set exposure time. * When exposure_us is zero, auto exposure",
"Exception('camera is not open.') t_start = time.time() self.camera.StartGrabbing(pylon.GrabStrategy_LatestImageOnly) grabResult = self.camera.RetrieveResult(timeout, pylon.TimeoutHandling_ThrowException) rslt_conv",
"\"\"\" Close. \"\"\" self.camera.Close() def setExposureTime(self, exposure_us=10000, en_print=True): \"\"\" Set exposure time. *",
"False) def _changeGain(self, val): gain = cv2.getTrackbarPos(\"Gain[dB]\", \"img\") self.setGain(gain, False) def _changeMag(self, val):",
"\"img\", mag_cur, mag_max, self._changeMag) k = cv2.waitKey(delay) cv2.destroyAllWindows() def _changeExposure(self, val): exp =",
"raise Exception('camera is not open.') if gain == -1.0: self.camera.GainAuto.SetValue('Continuous') else: self.camera.GainAuto.SetValue('Off') self.camera.Gain.SetValue(gain)",
"Close. \"\"\" self.camera.Close() def setExposureTime(self, exposure_us=10000, en_print=True): \"\"\" Set exposure time. * When",
"def close(self): \"\"\" Close. \"\"\" self.camera.Close() def setExposureTime(self, exposure_us=10000, en_print=True): \"\"\" Set exposure",
"== -1.0: self.camera.GainAuto.SetValue('Continuous') else: self.camera.GainAuto.SetValue('Off') self.camera.Gain.SetValue(gain) if en_print: print('GainAuto = {0}'.format(self.camera.GainAuto.GetValue())) print('Gain =",
"print('ExposureTime = {0}[us]'.format(self.camera.ExposureTime.GetValue())) def setGain(self, gain=0.0, en_print=True): \"\"\" Set gain. * When gain",
"is not open.') k = 0 while k != 27: img = self.grab(en_print=False)",
"t_start if en_print: print('grab time : {0} ms'.format(proc_time)) return rslt_conv.GetArray() def view(self, delay=1):",
"gain=0.0, en_print=True): \"\"\" Set gain. * When gain is -1, auto gain is",
"not self.camera.IsOpen(): raise Exception('camera is not open.') k = 0 while k !=",
"= pylon.InstantCamera(self.factory.CreateDevice(self.devices[id])) # The camera settings cannot be changed without opening. self.camera.Open() if",
"import cv2 class CameraPylon: def __init__(self, id=0, exposure_us=30000, gain=0.0): \"\"\" Init * When",
"{0}[dB]'.format(self.camera.Gain.GetValue())) def grab(self, timeout=1000, en_print=True): \"\"\" Grab. * Run StartGrabbing and StopGrabbing each",
"print('--------------------') print('CameraPylon.__init__') print('--------------------') print('Name = {0}'.format(self.devices[id].GetFriendlyName())) print('Width = {0}'.format(self.camera.Width.GetValue())) print('Height = {0}'.format(self.camera.Height.GetValue())) print('ExposureAuto",
"\"\"\" if not self.camera.IsOpen(): raise Exception('camera is not open.') t_start = time.time() self.camera.StartGrabbing(pylon.GrabStrategy_LatestImageOnly)",
"{0}[us]'.format(self.camera.ExposureTime.GetValue())) def setGain(self, gain=0.0, en_print=True): \"\"\" Set gain. * When gain is -1,",
"self._changeMag) k = cv2.waitKey(delay) cv2.destroyAllWindows() def _changeExposure(self, val): exp = cv2.getTrackbarPos(\"Exp[ms]\", \"img\") self.setExposureTime(exp",
"gain=0.0): \"\"\" Init * When exposure_us is zero, auto exposure is enabled. *",
"# Set display magnification. self.disp_mag = 50 def open(self): \"\"\" Open. \"\"\" self.camera.Open()",
"time.time() self.camera.StartGrabbing(pylon.GrabStrategy_LatestImageOnly) grabResult = self.camera.RetrieveResult(timeout, pylon.TimeoutHandling_ThrowException) rslt_conv = self.converter_bgr.Convert(grabResult) grabResult.Release() self.camera.StopGrabbing() proc_time =",
"cv2.waitKey(delay) cv2.destroyAllWindows() def _changeExposure(self, val): exp = cv2.getTrackbarPos(\"Exp[ms]\", \"img\") self.setExposureTime(exp * 1000, False)",
"import pylon import cv2 class CameraPylon: def __init__(self, id=0, exposure_us=30000, gain=0.0): \"\"\" Init",
"cv2.getTrackbarPos(\"Gain[dB]\", \"img\") self.setGain(gain, False) def _changeMag(self, val): mag = cv2.getTrackbarPos(\"Mag[%]\", \"img\") self.disp_mag =",
"auto exposure is enabled. * When gain is zero, auto gain is enabled.",
"= {0}'.format(self.camera.GainAuto.GetValue())) print('Gain = {0}'.format(self.camera.Gain.GetValue())) self.camera.Close() # Set ImageFormatConverter. self.converter_bgr = pylon.ImageFormatConverter() self.converter_bgr.OutputPixelFormat",
"en_print: print('ExposureAuto = {0}'.format(self.camera.ExposureAuto.GetValue())) print('ExposureTime = {0}[us]'.format(self.camera.ExposureTime.GetValue())) def setGain(self, gain=0.0, en_print=True): \"\"\" Set",
"* When gain is -1, auto gain is enabled. * When en_print is",
"zero, auto exposure is enabled. * When en_print is True, display the set",
"Run StartGrabbing and StopGrabbing each time. * All convert to 24-bit BGR. *",
"== -1.0: self.camera.GainAuto.SetValue('Continuous') else: self.camera.GainAuto.SetValue('Off') self.camera.Gain.SetValue(gain) print('--------------------') print('CameraPylon.__init__') print('--------------------') print('Name = {0}'.format(self.devices[id].GetFriendlyName())) print('Width",
"int(self.camera.Height.GetValue() * self.disp_mag / 100) img_resize = cv2.resize(img, (w, h)) cv2.imshow(\"img\", img_resize) exp_cur",
"All convert to 24-bit BGR. * When en_print is True, display the set",
"__init__(self, id=0, exposure_us=30000, gain=0.0): \"\"\" Init * When exposure_us is zero, auto exposure",
"When gain is -1, auto gain is enabled. * When en_print is True,",
"delay=1): \"\"\" View. * Close with ESC. \"\"\" if not self.camera.IsOpen(): raise Exception('camera",
"print('grab time : {0} ms'.format(proc_time)) return rslt_conv.GetArray() def view(self, delay=1): \"\"\" View. *",
"len(self.devices) == 0: raise Exception('no camera present.') # Create a class to control",
"not self.camera.IsOpen(): raise Exception('camera is not open.') if exposure_us == 0: self.camera.ExposureAuto.SetValue('Continuous') else:",
"def grab(self, timeout=1000, en_print=True): \"\"\" Grab. * Run StartGrabbing and StopGrabbing each time.",
"{0}'.format(self.camera.ExposureAuto.GetValue())) print('ExposureTime = {0}[us]'.format(self.camera.ExposureTime.GetValue())) def setGain(self, gain=0.0, en_print=True): \"\"\" Set gain. * When",
"utf-8 -*- import time from pypylon import pylon import cv2 class CameraPylon: def",
"self.converter_bgr.Convert(grabResult) grabResult.Release() self.camera.StopGrabbing() proc_time = time.time() - t_start if en_print: print('grab time :",
"_changeExposure(self, val): exp = cv2.getTrackbarPos(\"Exp[ms]\", \"img\") self.setExposureTime(exp * 1000, False) def _changeGain(self, val):",
"# DeviceInfo class get the number of connected cameras, camera name, etc. self.devices",
"without opening. self.camera.Open() if exposure_us == 0: self.camera.ExposureAuto.SetValue('Continuous') else: self.camera.ExposureAuto.SetValue('Off') self.camera.ExposureTime.SetValue(exposure_us) if gain",
"= {0}'.format(self.camera.ExposureAuto.GetValue())) print('ExposureTime = {0}[us]'.format(self.camera.ExposureTime.GetValue())) def setGain(self, gain=0.0, en_print=True): \"\"\" Set gain. *",
"= int(self.camera.ExposureTime.GetValue() / 1000) exp_max = int(self.camera.AutoExposureTimeUpperLimit.GetValue() / 1000) gain_cur = int(self.camera.Gain.GetValue()) gain_max",
"self.camera.Gain.SetValue(gain) print('--------------------') print('CameraPylon.__init__') print('--------------------') print('Name = {0}'.format(self.devices[id].GetFriendlyName())) print('Width = {0}'.format(self.camera.Width.GetValue())) print('Height = {0}'.format(self.camera.Height.GetValue()))",
"self.camera.Open() def close(self): \"\"\" Close. \"\"\" self.camera.Close() def setExposureTime(self, exposure_us=10000, en_print=True): \"\"\" Set",
"not self.camera.IsOpen(): raise Exception('camera is not open.') t_start = time.time() self.camera.StartGrabbing(pylon.GrabStrategy_LatestImageOnly) grabResult =",
"h = int(self.camera.Height.GetValue() * self.disp_mag / 100) img_resize = cv2.resize(img, (w, h)) cv2.imshow(\"img\",",
"not self.camera.IsOpen(): raise Exception('camera is not open.') if gain == -1.0: self.camera.GainAuto.SetValue('Continuous') else:",
"img_resize) exp_cur = int(self.camera.ExposureTime.GetValue() / 1000) exp_max = int(self.camera.AutoExposureTimeUpperLimit.GetValue() / 1000) gain_cur =",
"print('ExposureTime = {0}[us]'.format(self.camera.ExposureTime.GetValue())) print('GainAuto = {0}'.format(self.camera.GainAuto.GetValue())) print('Gain = {0}'.format(self.camera.Gain.GetValue())) self.camera.Close() # Set ImageFormatConverter.",
"int(200) cv2.createTrackbar(\"Exp[ms]\", \"img\", exp_cur, exp_max, self._changeExposure) cv2.createTrackbar(\"Gain[dB]\", \"img\", gain_cur, gain_max, self._changeGain) cv2.createTrackbar(\"Mag[%]\", \"img\",",
"-1, auto gain is enabled. * When en_print is True, display the set",
"= cv2.getTrackbarPos(\"Exp[ms]\", \"img\") self.setExposureTime(exp * 1000, False) def _changeGain(self, val): gain = cv2.getTrackbarPos(\"Gain[dB]\",",
"if not self.camera.IsOpen(): raise Exception('camera is not open.') if exposure_us == 0: self.camera.ExposureAuto.SetValue('Continuous')",
"open.') if gain == -1.0: self.camera.GainAuto.SetValue('Continuous') else: self.camera.GainAuto.SetValue('Off') self.camera.Gain.SetValue(gain) if en_print: print('GainAuto =",
"display the set value. \"\"\" if not self.camera.IsOpen(): raise Exception('camera is not open.')",
"{0}'.format(self.camera.Height.GetValue())) print('ExposureAuto = {0}'.format(self.camera.ExposureAuto.GetValue())) print('ExposureTime = {0}[us]'.format(self.camera.ExposureTime.GetValue())) print('GainAuto = {0}'.format(self.camera.GainAuto.GetValue())) print('Gain = {0}'.format(self.camera.Gain.GetValue()))",
"exp_cur, exp_max, self._changeExposure) cv2.createTrackbar(\"Gain[dB]\", \"img\", gain_cur, gain_max, self._changeGain) cv2.createTrackbar(\"Mag[%]\", \"img\", mag_cur, mag_max, self._changeMag)",
"if gain == -1.0: self.camera.GainAuto.SetValue('Continuous') else: self.camera.GainAuto.SetValue('Off') self.camera.Gain.SetValue(gain) if en_print: print('GainAuto = {0}'.format(self.camera.GainAuto.GetValue()))",
"camera name, etc. self.devices = self.factory.EnumerateDevices() if len(self.devices) == 0: raise Exception('no camera",
"time. * When exposure_us is zero, auto exposure is enabled. * When en_print",
"return rslt_conv.GetArray() def view(self, delay=1): \"\"\" View. * Close with ESC. \"\"\" if",
"= cv2.getTrackbarPos(\"Gain[dB]\", \"img\") self.setGain(gain, False) def _changeMag(self, val): mag = cv2.getTrackbarPos(\"Mag[%]\", \"img\") self.disp_mag",
"self.factory = pylon.TlFactory.GetInstance() # DeviceInfo class get the number of connected cameras, camera",
"self.camera.RetrieveResult(timeout, pylon.TimeoutHandling_ThrowException) rslt_conv = self.converter_bgr.Convert(grabResult) grabResult.Release() self.camera.StopGrabbing() proc_time = time.time() - t_start if",
"the set value. \"\"\" if not self.camera.IsOpen(): raise Exception('camera is not open.') t_start",
"# The camera settings cannot be changed without opening. self.camera.Open() if exposure_us ==",
"camera. self.camera = pylon.InstantCamera(self.factory.CreateDevice(self.devices[id])) # The camera settings cannot be changed without opening.",
"= int(self.camera.Width.GetValue() * self.disp_mag / 100) h = int(self.camera.Height.GetValue() * self.disp_mag / 100)",
"time : {0} ms'.format(proc_time)) return rslt_conv.GetArray() def view(self, delay=1): \"\"\" View. * Close",
"cv2.destroyAllWindows() def _changeExposure(self, val): exp = cv2.getTrackbarPos(\"Exp[ms]\", \"img\") self.setExposureTime(exp * 1000, False) def",
"self.camera.GainAuto.SetValue('Continuous') else: self.camera.GainAuto.SetValue('Off') self.camera.Gain.SetValue(gain) if en_print: print('GainAuto = {0}'.format(self.camera.GainAuto.GetValue())) print('Gain = {0}[dB]'.format(self.camera.Gain.GetValue())) def",
"a class to control the camera. self.camera = pylon.InstantCamera(self.factory.CreateDevice(self.devices[id])) # The camera settings",
"\"\"\" if not self.camera.IsOpen(): raise Exception('camera is not open.') if exposure_us == 0:",
"if en_print: print('grab time : {0} ms'.format(proc_time)) return rslt_conv.GetArray() def view(self, delay=1): \"\"\"",
"print('Width = {0}'.format(self.camera.Width.GetValue())) print('Height = {0}'.format(self.camera.Height.GetValue())) print('ExposureAuto = {0}'.format(self.camera.ExposureAuto.GetValue())) print('ExposureTime = {0}[us]'.format(self.camera.ExposureTime.GetValue())) print('GainAuto",
"{0}'.format(self.camera.Gain.GetValue())) self.camera.Close() # Set ImageFormatConverter. self.converter_bgr = pylon.ImageFormatConverter() self.converter_bgr.OutputPixelFormat = pylon.PixelType_BGR8packed self.converter_bgr.OutputBitAlignment =",
"self.camera.IsOpen(): raise Exception('camera is not open.') if gain == -1.0: self.camera.GainAuto.SetValue('Continuous') else: self.camera.GainAuto.SetValue('Off')",
"int(self.camera.ExposureTime.GetValue() / 1000) exp_max = int(self.camera.AutoExposureTimeUpperLimit.GetValue() / 1000) gain_cur = int(self.camera.Gain.GetValue()) gain_max =",
"mag_max = int(200) cv2.createTrackbar(\"Exp[ms]\", \"img\", exp_cur, exp_max, self._changeExposure) cv2.createTrackbar(\"Gain[dB]\", \"img\", gain_cur, gain_max, self._changeGain)",
"self.camera.Open() if exposure_us == 0: self.camera.ExposureAuto.SetValue('Continuous') else: self.camera.ExposureAuto.SetValue('Off') self.camera.ExposureTime.SetValue(exposure_us) if gain == -1.0:",
"def _changeGain(self, val): gain = cv2.getTrackbarPos(\"Gain[dB]\", \"img\") self.setGain(gain, False) def _changeMag(self, val): mag",
"= pylon.PixelType_BGR8packed self.converter_bgr.OutputBitAlignment = 'MsbAligned' # Set display magnification. self.disp_mag = 50 def",
"= 'MsbAligned' # Set display magnification. self.disp_mag = 50 def open(self): \"\"\" Open.",
"rslt_conv.GetArray() def view(self, delay=1): \"\"\" View. * Close with ESC. \"\"\" if not",
"of connected cameras, camera name, etc. self.devices = self.factory.EnumerateDevices() if len(self.devices) == 0:",
"timeout=1000, en_print=True): \"\"\" Grab. * Run StartGrabbing and StopGrabbing each time. * All",
"Set ImageFormatConverter. self.converter_bgr = pylon.ImageFormatConverter() self.converter_bgr.OutputPixelFormat = pylon.PixelType_BGR8packed self.converter_bgr.OutputBitAlignment = 'MsbAligned' # Set",
"if not self.camera.IsOpen(): raise Exception('camera is not open.') t_start = time.time() self.camera.StartGrabbing(pylon.GrabStrategy_LatestImageOnly) grabResult",
"def view(self, delay=1): \"\"\" View. * Close with ESC. \"\"\" if not self.camera.IsOpen():",
"print('GainAuto = {0}'.format(self.camera.GainAuto.GetValue())) print('Gain = {0}'.format(self.camera.Gain.GetValue())) self.camera.Close() # Set ImageFormatConverter. self.converter_bgr = pylon.ImageFormatConverter()",
"time from pypylon import pylon import cv2 class CameraPylon: def __init__(self, id=0, exposure_us=30000,",
"The camera settings cannot be changed without opening. self.camera.Open() if exposure_us == 0:",
"changed without opening. self.camera.Open() if exposure_us == 0: self.camera.ExposureAuto.SetValue('Continuous') else: self.camera.ExposureAuto.SetValue('Off') self.camera.ExposureTime.SetValue(exposure_us) if",
"time.time() - t_start if en_print: print('grab time : {0} ms'.format(proc_time)) return rslt_conv.GetArray() def",
"enabled. \"\"\" self.factory = pylon.TlFactory.GetInstance() # DeviceInfo class get the number of connected",
"= self.converter_bgr.Convert(grabResult) grabResult.Release() self.camera.StopGrabbing() proc_time = time.time() - t_start if en_print: print('grab time",
"Create a class to control the camera. self.camera = pylon.InstantCamera(self.factory.CreateDevice(self.devices[id])) # The camera",
"set value. \"\"\" if not self.camera.IsOpen(): raise Exception('camera is not open.') if gain",
"with ESC. \"\"\" if not self.camera.IsOpen(): raise Exception('camera is not open.') k =",
"cv2.resize(img, (w, h)) cv2.imshow(\"img\", img_resize) exp_cur = int(self.camera.ExposureTime.GetValue() / 1000) exp_max = int(self.camera.AutoExposureTimeUpperLimit.GetValue()",
"-1.0: self.camera.GainAuto.SetValue('Continuous') else: self.camera.GainAuto.SetValue('Off') self.camera.Gain.SetValue(gain) print('--------------------') print('CameraPylon.__init__') print('--------------------') print('Name = {0}'.format(self.devices[id].GetFriendlyName())) print('Width =",
"is not open.') if exposure_us == 0: self.camera.ExposureAuto.SetValue('Continuous') else: self.camera.ExposureAuto.SetValue('Off') self.camera.ExposureTime.SetValue(exposure_us) if en_print:",
"ms'.format(proc_time)) return rslt_conv.GetArray() def view(self, delay=1): \"\"\" View. * Close with ESC. \"\"\"",
"time. * All convert to 24-bit BGR. * When en_print is True, display",
"if not self.camera.IsOpen(): raise Exception('camera is not open.') if gain == -1.0: self.camera.GainAuto.SetValue('Continuous')",
"if len(self.devices) == 0: raise Exception('no camera present.') # Create a class to",
"/ 1000) exp_max = int(self.camera.AutoExposureTimeUpperLimit.GetValue() / 1000) gain_cur = int(self.camera.Gain.GetValue()) gain_max = int(self.camera.AutoGainUpperLimit.GetValue())",
"* All convert to 24-bit BGR. * When en_print is True, display the",
"grabResult = self.camera.RetrieveResult(timeout, pylon.TimeoutHandling_ThrowException) rslt_conv = self.converter_bgr.Convert(grabResult) grabResult.Release() self.camera.StopGrabbing() proc_time = time.time() -",
"cv2 class CameraPylon: def __init__(self, id=0, exposure_us=30000, gain=0.0): \"\"\" Init * When exposure_us",
"0: raise Exception('no camera present.') # Create a class to control the camera.",
"gain is enabled. * When en_print is True, display the set value. \"\"\"",
"- t_start if en_print: print('grab time : {0} ms'.format(proc_time)) return rslt_conv.GetArray() def view(self,",
"en_print: print('GainAuto = {0}'.format(self.camera.GainAuto.GetValue())) print('Gain = {0}[dB]'.format(self.camera.Gain.GetValue())) def grab(self, timeout=1000, en_print=True): \"\"\" Grab.",
"auto gain is enabled. \"\"\" self.factory = pylon.TlFactory.GetInstance() # DeviceInfo class get the",
"self.disp_mag / 100) h = int(self.camera.Height.GetValue() * self.disp_mag / 100) img_resize = cv2.resize(img,",
"get the number of connected cameras, camera name, etc. self.devices = self.factory.EnumerateDevices() if",
"pylon import cv2 class CameraPylon: def __init__(self, id=0, exposure_us=30000, gain=0.0): \"\"\" Init *",
"self.camera.Gain.SetValue(gain) if en_print: print('GainAuto = {0}'.format(self.camera.GainAuto.GetValue())) print('Gain = {0}[dB]'.format(self.camera.Gain.GetValue())) def grab(self, timeout=1000, en_print=True):",
"self.camera.StartGrabbing(pylon.GrabStrategy_LatestImageOnly) grabResult = self.camera.RetrieveResult(timeout, pylon.TimeoutHandling_ThrowException) rslt_conv = self.converter_bgr.Convert(grabResult) grabResult.Release() self.camera.StopGrabbing() proc_time = time.time()",
"print('Name = {0}'.format(self.devices[id].GetFriendlyName())) print('Width = {0}'.format(self.camera.Width.GetValue())) print('Height = {0}'.format(self.camera.Height.GetValue())) print('ExposureAuto = {0}'.format(self.camera.ExposureAuto.GetValue())) print('ExposureTime",
"\"\"\" self.camera.Close() def setExposureTime(self, exposure_us=10000, en_print=True): \"\"\" Set exposure time. * When exposure_us",
"\"\"\" if not self.camera.IsOpen(): raise Exception('camera is not open.') k = 0 while",
"Close with ESC. \"\"\" if not self.camera.IsOpen(): raise Exception('camera is not open.') k",
"self.converter_bgr.OutputBitAlignment = 'MsbAligned' # Set display magnification. self.disp_mag = 50 def open(self): \"\"\"",
"exposure_us == 0: self.camera.ExposureAuto.SetValue('Continuous') else: self.camera.ExposureAuto.SetValue('Off') self.camera.ExposureTime.SetValue(exposure_us) if en_print: print('ExposureAuto = {0}'.format(self.camera.ExposureAuto.GetValue())) print('ExposureTime",
"\"img\") self.setExposureTime(exp * 1000, False) def _changeGain(self, val): gain = cv2.getTrackbarPos(\"Gain[dB]\", \"img\") self.setGain(gain,",
"int(self.camera.AutoGainUpperLimit.GetValue()) mag_cur = int(self.disp_mag) mag_max = int(200) cv2.createTrackbar(\"Exp[ms]\", \"img\", exp_cur, exp_max, self._changeExposure) cv2.createTrackbar(\"Gain[dB]\",",
"if not self.camera.IsOpen(): raise Exception('camera is not open.') k = 0 while k",
"w = int(self.camera.Width.GetValue() * self.disp_mag / 100) h = int(self.camera.Height.GetValue() * self.disp_mag /",
"raise Exception('camera is not open.') k = 0 while k != 27: img",
"is -1, auto gain is enabled. * When en_print is True, display the",
"self.camera.StopGrabbing() proc_time = time.time() - t_start if en_print: print('grab time : {0} ms'.format(proc_time))",
"exposure is enabled. * When gain is zero, auto gain is enabled. \"\"\"",
"* 1000, False) def _changeGain(self, val): gain = cv2.getTrackbarPos(\"Gain[dB]\", \"img\") self.setGain(gain, False) def",
"to 24-bit BGR. * When en_print is True, display the set value. \"\"\"",
"enabled. * When gain is zero, auto gain is enabled. \"\"\" self.factory =",
"Set gain. * When gain is -1, auto gain is enabled. * When",
"id=0, exposure_us=30000, gain=0.0): \"\"\" Init * When exposure_us is zero, auto exposure is",
"is not open.') if gain == -1.0: self.camera.GainAuto.SetValue('Continuous') else: self.camera.GainAuto.SetValue('Off') self.camera.Gain.SetValue(gain) if en_print:",
"int(self.camera.Gain.GetValue()) gain_max = int(self.camera.AutoGainUpperLimit.GetValue()) mag_cur = int(self.disp_mag) mag_max = int(200) cv2.createTrackbar(\"Exp[ms]\", \"img\", exp_cur,",
"Set display magnification. self.disp_mag = 50 def open(self): \"\"\" Open. \"\"\" self.camera.Open() def",
"print('ExposureAuto = {0}'.format(self.camera.ExposureAuto.GetValue())) print('ExposureTime = {0}[us]'.format(self.camera.ExposureTime.GetValue())) def setGain(self, gain=0.0, en_print=True): \"\"\" Set gain.",
"set value. \"\"\" if not self.camera.IsOpen(): raise Exception('camera is not open.') if exposure_us",
"* Close with ESC. \"\"\" if not self.camera.IsOpen(): raise Exception('camera is not open.')",
"val): gain = cv2.getTrackbarPos(\"Gain[dB]\", \"img\") self.setGain(gain, False) def _changeMag(self, val): mag = cv2.getTrackbarPos(\"Mag[%]\",",
"= int(self.camera.AutoExposureTimeUpperLimit.GetValue() / 1000) gain_cur = int(self.camera.Gain.GetValue()) gain_max = int(self.camera.AutoGainUpperLimit.GetValue()) mag_cur = int(self.disp_mag)",
"cv2.createTrackbar(\"Gain[dB]\", \"img\", gain_cur, gain_max, self._changeGain) cv2.createTrackbar(\"Mag[%]\", \"img\", mag_cur, mag_max, self._changeMag) k = cv2.waitKey(delay)",
"self.converter_bgr.OutputPixelFormat = pylon.PixelType_BGR8packed self.converter_bgr.OutputBitAlignment = 'MsbAligned' # Set display magnification. self.disp_mag = 50",
"camera present.') # Create a class to control the camera. self.camera = pylon.InstantCamera(self.factory.CreateDevice(self.devices[id]))",
"self.camera.GainAuto.SetValue('Off') self.camera.Gain.SetValue(gain) if en_print: print('GainAuto = {0}'.format(self.camera.GainAuto.GetValue())) print('Gain = {0}[dB]'.format(self.camera.Gain.GetValue())) def grab(self, timeout=1000,",
"each time. * All convert to 24-bit BGR. * When en_print is True,",
"True, display the set value. \"\"\" if not self.camera.IsOpen(): raise Exception('camera is not",
"= int(self.camera.Gain.GetValue()) gain_max = int(self.camera.AutoGainUpperLimit.GetValue()) mag_cur = int(self.disp_mag) mag_max = int(200) cv2.createTrackbar(\"Exp[ms]\", \"img\",",
"from pypylon import pylon import cv2 class CameraPylon: def __init__(self, id=0, exposure_us=30000, gain=0.0):",
"en_print=True): \"\"\" Grab. * Run StartGrabbing and StopGrabbing each time. * All convert",
"= {0}'.format(self.camera.Width.GetValue())) print('Height = {0}'.format(self.camera.Height.GetValue())) print('ExposureAuto = {0}'.format(self.camera.ExposureAuto.GetValue())) print('ExposureTime = {0}[us]'.format(self.camera.ExposureTime.GetValue())) print('GainAuto =",
"= int(200) cv2.createTrackbar(\"Exp[ms]\", \"img\", exp_cur, exp_max, self._changeExposure) cv2.createTrackbar(\"Gain[dB]\", \"img\", gain_cur, gain_max, self._changeGain) cv2.createTrackbar(\"Mag[%]\",",
"When gain is zero, auto gain is enabled. \"\"\" self.factory = pylon.TlFactory.GetInstance() #",
"= {0}'.format(self.camera.Height.GetValue())) print('ExposureAuto = {0}'.format(self.camera.ExposureAuto.GetValue())) print('ExposureTime = {0}[us]'.format(self.camera.ExposureTime.GetValue())) print('GainAuto = {0}'.format(self.camera.GainAuto.GetValue())) print('Gain =",
"cv2.imshow(\"img\", img_resize) exp_cur = int(self.camera.ExposureTime.GetValue() / 1000) exp_max = int(self.camera.AutoExposureTimeUpperLimit.GetValue() / 1000) gain_cur",
"exp_cur = int(self.camera.ExposureTime.GetValue() / 1000) exp_max = int(self.camera.AutoExposureTimeUpperLimit.GetValue() / 1000) gain_cur = int(self.camera.Gain.GetValue())",
"else: self.camera.GainAuto.SetValue('Off') self.camera.Gain.SetValue(gain) if en_print: print('GainAuto = {0}'.format(self.camera.GainAuto.GetValue())) print('Gain = {0}[dB]'.format(self.camera.Gain.GetValue())) def grab(self,",
"Grab. * Run StartGrabbing and StopGrabbing each time. * All convert to 24-bit",
"50 def open(self): \"\"\" Open. \"\"\" self.camera.Open() def close(self): \"\"\" Close. \"\"\" self.camera.Close()",
"self.camera.IsOpen(): raise Exception('camera is not open.') t_start = time.time() self.camera.StartGrabbing(pylon.GrabStrategy_LatestImageOnly) grabResult = self.camera.RetrieveResult(timeout,",
"Exception('camera is not open.') if gain == -1.0: self.camera.GainAuto.SetValue('Continuous') else: self.camera.GainAuto.SetValue('Off') self.camera.Gain.SetValue(gain) if",
"magnification. self.disp_mag = 50 def open(self): \"\"\" Open. \"\"\" self.camera.Open() def close(self): \"\"\"",
"= self.grab(en_print=False) w = int(self.camera.Width.GetValue() * self.disp_mag / 100) h = int(self.camera.Height.GetValue() *",
"gain_cur, gain_max, self._changeGain) cv2.createTrackbar(\"Mag[%]\", \"img\", mag_cur, mag_max, self._changeMag) k = cv2.waitKey(delay) cv2.destroyAllWindows() def",
"is not open.') t_start = time.time() self.camera.StartGrabbing(pylon.GrabStrategy_LatestImageOnly) grabResult = self.camera.RetrieveResult(timeout, pylon.TimeoutHandling_ThrowException) rslt_conv =",
"class to control the camera. self.camera = pylon.InstantCamera(self.factory.CreateDevice(self.devices[id])) # The camera settings cannot",
"self.camera.ExposureAuto.SetValue('Continuous') else: self.camera.ExposureAuto.SetValue('Off') self.camera.ExposureTime.SetValue(exposure_us) if gain == -1.0: self.camera.GainAuto.SetValue('Continuous') else: self.camera.GainAuto.SetValue('Off') self.camera.Gain.SetValue(gain) print('--------------------')",
"is True, display the set value. \"\"\" if not self.camera.IsOpen(): raise Exception('camera is"
] |